/**
 * Payment Method Select Component
 * Fetches and displays available payment methods based on country
 * Shows instructions for manual payment methods (bank transfer, wallets)
 */

import { useState, useEffect } from 'react';
import { CheckCircle, Loader2, AlertCircle } from 'lucide-react';
import { API_BASE_URL } from '../../services/api';

export interface PaymentMethodConfig {
  id: number;
  payment_method: string;
  display_name: string;
  instructions: string | null;
  country_code: string;
  is_enabled: boolean;
  sort_order: number;
}

interface PaymentMethodSelectProps {
  countryCode: string;
  selectedMethod: string | null;
  onSelectMethod: (method: PaymentMethodConfig) => void;
  error?: string;
}

export default function PaymentMethodSelect({
  countryCode,
  selectedMethod,
  onSelectMethod,
  error,
}: PaymentMethodSelectProps) {
  const [methods, setMethods] = useState<PaymentMethodConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [fetchError, setFetchError] = useState('');

  useEffect(() => {
    loadPaymentMethods();
  }, [countryCode]);

  const loadPaymentMethods = async () => {
    try {
      setLoading(true);
      setFetchError('');

      const params = countryCode ? `?country=${countryCode}` : '';
      const response = await fetch(`${API_BASE_URL}/v1/billing/admin/payment-methods/${params}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.error || 'Failed to load payment methods');
      }

      const methodsList = data.results || data.data || [];
      setMethods(methodsList.filter((m: PaymentMethodConfig) => m.is_enabled));

      // Auto-select first method if none selected
      if (methodsList.length > 0 && !selectedMethod) {
        onSelectMethod(methodsList[0]);
      }
    } catch (err: any) {
      setFetchError(err.message || 'Failed to load payment methods');
      console.error('Payment methods fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <Loader2 className="w-6 h-6 animate-spin text-brand-500" />
        <span className="ml-3 text-gray-600 dark:text-gray-400">Loading payment methods...</span>
      </div>
    );
  }

  if (fetchError) {
    return (
      <div className="p-4 rounded-lg border border-red-200 bg-red-50 text-red-800 dark:border-red-800 dark:bg-red-900/20 dark:text-red-200">
        <div className="flex items-start gap-3">
          <AlertCircle className="w-5 h-5 flex-shrink-0 mt-0.5" />
          <div>
            <p className="font-medium">Failed to load payment methods</p>
            <p className="text-sm mt-1">{fetchError}</p>
            <button
              onClick={loadPaymentMethods}
              className="mt-3 text-sm font-medium underline hover:no-underline"
            >
              Try again
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (methods.length === 0) {
    return (
      <div className="p-4 rounded-lg border border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-900/20 dark:text-amber-200">
        <div className="flex items-start gap-3">
          <AlertCircle className="w-5 h-5 flex-shrink-0 mt-0.5" />
          <div>
            <p className="font-medium">No payment methods available</p>
            <p className="text-sm mt-1">
              {countryCode
                ? `No payment methods configured for ${countryCode}. Global methods may be available.`
                : 'Please select a billing country to see available payment options.'}
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {error && (
        <div className="p-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg dark:bg-red-900/20 dark:text-red-400 dark:border-red-800">
          {error}
        </div>
      )}

      <div className="mb-4">
        <h3 className="text-lg font-semibold text-gray-800 dark:text-white mb-2">
          Select Payment Method
        </h3>
        <p className="text-sm text-gray-500 dark:text-gray-400">
          {countryCode
            ? `Available payment methods for ${countryCode} (${methods.length} option${methods.length !== 1 ? 's' : ''})`
            : `${methods.length} payment method${methods.length !== 1 ? 's' : ''} available`}
        </p>
      </div>

      <div className="space-y-3">
        {methods.map((method) => (
          <div
            key={method.id}
            onClick={() => onSelectMethod(method)}
            className={`
              relative p-4 rounded-lg border-2 cursor-pointer transition-all
              ${
                selectedMethod === method.payment_method
                  ? 'border-brand-500 bg-brand-50 dark:bg-brand-500/10 dark:border-brand-400'
                  : 'border-gray-200 bg-white hover:border-gray-300 dark:border-gray-700 dark:bg-gray-800 dark:hover:border-gray-600'
              }
            `}
          >
            <div className="flex items-start gap-3">
              {/* Radio indicator */}
              <div className="flex-shrink-0 mt-0.5">
                {selectedMethod === method.payment_method ? (
                  <CheckCircle className="w-5 h-5 text-brand-500 dark:text-brand-400" />
                ) : (
                  <div className="w-5 h-5 rounded-full border-2 border-gray-300 dark:border-gray-600" />
                )}
              </div>

              {/* Method details */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <h4 className="font-semibold text-gray-900 dark:text-white">
                    {method.display_name}
                  </h4>
                  {method.country_code !== '*' && (
                    <span className="px-2 py-0.5 text-xs font-medium rounded bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300">
                      {method.country_code}
                    </span>
                  )}
                </div>

                {/* Instructions for manual methods */}
                {method.instructions && (
                  <div className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                    <p className="font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Payment Instructions:
                    </p>
                    <div className="whitespace-pre-wrap">{method.instructions}</div>
                  </div>
                )}

                {/* Method type badge */}
                <div className="mt-2">
                  <span className="inline-flex px-2 py-1 text-xs font-medium rounded bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300">
                    {method.payment_method.replace(/_/g, ' ').toUpperCase()}
                  </span>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-4 p-4 rounded-lg bg-blue-50 border border-blue-200 dark:bg-blue-900/20 dark:border-blue-800">
        <p className="text-sm text-blue-800 dark:text-blue-200">
          <span className="font-medium">Note:</span> For manual payment methods (bank transfer, local wallets), 
          you'll need to complete the payment and then submit proof of payment for admin approval.
        </p>
      </div>
    </div>
  );
}
