/**
 * Purchase Credits Page
 * Displays available credit packages and payment methods
 */

import { useState, useEffect } from 'react';
import { AlertCircle, Check, CreditCard, Building2, Wallet, Loader2 } from 'lucide-react';
import Button from '../../components/ui/button/Button';
import {
  getCreditPackages,
  getAvailablePaymentMethods,
  purchaseCreditPackage,
  createManualPayment,
  type CreditPackage,
  type PaymentMethod,
} from '../../services/billing.api';

export default function PurchaseCreditsPage() {
  const [packages, setPackages] = useState<CreditPackage[]>([]);
  const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([]);
  const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null);
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [purchasing, setPurchasing] = useState(false);
  const [error, setError] = useState<string>('');
  const [showManualPaymentForm, setShowManualPaymentForm] = useState(false);
  const [manualPaymentData, setManualPaymentData] = useState({
    transaction_reference: '',
    notes: '',
  });
  const [invoiceData, setInvoiceData] = useState<any>(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      setLoading(true);
      const [packagesRes, methodsRes] = await Promise.all([
        getCreditPackages(),
        getAvailablePaymentMethods(),
      ]);

      setPackages(packagesRes?.results || []);
      setPaymentMethods(methodsRes?.results || []);

      // Auto-select bank_transfer first, then manual
      const methods = methodsRes?.results || [];
      const bank = methods.find((m) => m.type === 'bank_transfer');
      const manual = methods.find((m) => m.type === 'manual');
      const preferred = bank || manual || methods[0];
      if (preferred) {
        setSelectedPaymentMethod(preferred.type);
      }
    } catch (err) {
      setError('Failed to load credit packages');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const handlePurchase = async () => {
    if (!selectedPackage || !selectedPaymentMethod) {
      setError('Please select a package and payment method');
      return;
    }

    try {
      setPurchasing(true);
      setError('');

      const response = await purchaseCreditPackage({
        package_id: selectedPackage.id,
        payment_method: selectedPaymentMethod as 'stripe' | 'paypal' | 'bank_transfer' | 'local_wallet'
      });

      if (selectedPaymentMethod === 'stripe') {
        // Redirect to Stripe checkout
        setError('Stripe integration pending - coming soon!');
      } else if (selectedPaymentMethod === 'paypal') {
        // Redirect to PayPal
        setError('PayPal integration pending - coming soon!');
      } else {
        // Manual payment - show form
        setInvoiceData(response);
        setShowManualPaymentForm(true);
      }
    } catch (err: any) {
      setError(err.message || 'Failed to initiate purchase');
    } finally {
      setPurchasing(false);
    }
  };

  const handleManualPaymentSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!invoiceData || !manualPaymentData.transaction_reference) {
      setError('Please provide transaction reference');
      return;
    }

    try {
      setPurchasing(true);
      setError('');

      await createManualPayment({
        invoice_id: invoiceData?.invoice_id || invoiceData?.id,
        amount: String(selectedPackage?.price || 0),
        payment_method: selectedPaymentMethod as 'stripe' | 'paypal' | 'bank_transfer' | 'local_wallet',
        reference: manualPaymentData.transaction_reference,
        notes: manualPaymentData.notes,
      });

      // Success
      alert('Payment submitted successfully! Your payment will be reviewed within 1-2 business days.');
      setShowManualPaymentForm(false);
      setSelectedPackage(null);
      setManualPaymentData({ transaction_reference: '', notes: '' });
      setInvoiceData(null);
    } catch (err: any) {
      setError(err.message || 'Failed to submit payment');
    } finally {
      setPurchasing(false);
    }
  };

  const getPaymentMethodIcon = (type: string) => {
    switch (type) {
      case 'stripe':
        return <CreditCard className="w-5 h-5" />;
      case 'bank_transfer':
        return <Building2 className="w-5 h-5" />;
      case 'local_wallet':
        return <Wallet className="w-5 h-5" />;
      default:
        return <CreditCard className="w-5 h-5" />;
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin text-[var(--color-brand-500)]" />
      </div>
    );
  }

  if (showManualPaymentForm && invoiceData) {
    const selectedMethod = paymentMethods.find((m) => m.type === selectedPaymentMethod);

    return (
      <div className="container mx-auto px-4 py-8 max-w-2xl">
        <h1 className="text-3xl font-bold mb-6">Complete Payment</h1>

        {/* Invoice Details */}
        <div className="bg-white rounded-lg shadow p-6 mb-6">
          <h2 className="text-xl font-semibold mb-4">Invoice Details</h2>
          <div className="space-y-2">
            <div className="flex justify-between">
              <span className="text-gray-600">Invoice Number:</span>
              <span className="font-mono">{invoiceData.invoice_number}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Package:</span>
              <span>{selectedPackage?.name}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Credits:</span>
              <span>{selectedPackage?.credits.toLocaleString()}</span>
            </div>
            <div className="flex justify-between text-lg font-bold border-t pt-2 mt-2">
              <span>Total Amount:</span>
              <span>${invoiceData.total_amount}</span>
            </div>
          </div>
        </div>

        {/* Payment Instructions */}
        <div className="bg-[var(--color-info-50)] border border-[var(--color-info-200)] dark:bg-[var(--color-info-900)]/20 dark:border-[var(--color-info-700)] rounded-lg p-6 mb-6">
          <h3 className="font-semibold mb-3 text-[var(--color-info-900)] dark:text-[var(--color-info-100)]">Payment Instructions</h3>
          <p className="text-[var(--color-info-800)] dark:text-[var(--color-info-200)] mb-4">{selectedMethod?.instructions}</p>

          {selectedMethod?.bank_details && (
            <div className="bg-white rounded p-4 space-y-2">
              <h4 className="font-semibold mb-2">Bank Account Details:</h4>
              <div className="grid grid-cols-2 gap-2 text-sm">
                <div className="text-gray-600">Bank Name:</div>
                <div className="font-mono">{selectedMethod.bank_details.bank_name}</div>
                <div className="text-gray-600">Account Number:</div>
                <div className="font-mono">{selectedMethod.bank_details.account_number}</div>
                <div className="text-gray-600">Routing Number:</div>
                <div className="font-mono">{selectedMethod.bank_details.routing_number}</div>
                {selectedMethod.bank_details.swift_code && (
                  <>
                    <div className="text-gray-600">SWIFT Code:</div>
                    <div className="font-mono">{selectedMethod.bank_details.swift_code}</div>
                  </>
                )}
              </div>
            </div>
          )}

          {selectedMethod?.wallet_details && (
            <div className="bg-white rounded p-4 space-y-2">
              <h4 className="font-semibold mb-2">Wallet Details:</h4>
              <div className="grid grid-cols-2 gap-2 text-sm">
                <div className="text-gray-600">Wallet Type:</div>
                <div className="font-mono">{selectedMethod.wallet_details.wallet_type}</div>
                <div className="text-gray-600">Wallet ID:</div>
                <div className="font-mono">{selectedMethod.wallet_details.wallet_id}</div>
              </div>
            </div>
          )}
        </div>

        {/* Manual Payment Form */}
        <form onSubmit={handleManualPaymentSubmit} className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-semibold mb-4">Submit Payment Proof</h3>

          {error && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4 flex items-start gap-2">
              <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
              <p className="text-red-800 text-sm">{error}</p>
            </div>
          )}

          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Transaction Reference / ID *
              </label>
              <input
                type="text"
                required
                value={manualPaymentData.transaction_reference}
                onChange={(e) =>
                  setManualPaymentData({ ...manualPaymentData, transaction_reference: e.target.value })
                }
                placeholder="Enter transaction ID or reference number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-brand-500)] focus:border-[var(--color-brand-500)]"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Additional Notes (Optional)
              </label>
              <textarea
                value={manualPaymentData.notes}
                onChange={(e) =>
                  setManualPaymentData({ ...manualPaymentData, notes: e.target.value })
                }
                placeholder="Any additional information..."
                rows={3}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-brand-500)] focus:border-[var(--color-brand-500)]"
              />
            </div>

            <div className="flex gap-3 pt-4">
              <Button
                variant="outline"
                tone="neutral"
                onClick={() => {
                  setShowManualPaymentForm(false);
                  setInvoiceData(null);
                }}
                disabled={purchasing}
                className="flex-1"
              >
                Cancel
              </Button>
              <Button
                variant="primary"
                tone="brand"
                type="submit"
                disabled={purchasing}
                startIcon={purchasing ? <Loader2 className="w-4 h-4 animate-spin" /> : undefined}
                className="flex-1"
              >
                {purchasing ? 'Submitting...' : 'Submit Payment'}
              </Button>
            </div>
          </div>
        </form>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-6xl mx-auto">
        <h1 className="text-3xl font-bold mb-2">Purchase Credits</h1>
        <p className="text-gray-600 mb-8">
          Choose a credit package and payment method to top up your account balance.
        </p>

        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6 flex items-start gap-2">
            <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
            <p className="text-red-800">{error}</p>
          </div>
        )}

        {/* Credit Packages */}
        <div className="mb-8">
          <h2 className="text-xl font-semibold mb-4">Select Credit Package</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {packages.map((pkg) => (
              <div
                key={pkg.id}
                onClick={() => setSelectedPackage(pkg)}
                className={`relative cursor-pointer rounded-lg border-2 p-6 transition-all ${
                  selectedPackage?.id === pkg.id
                    ? 'border-[var(--color-brand-500)] bg-[var(--color-brand-50)]'
                    : 'border-gray-200 hover:border-[var(--color-brand-300)] bg-white'
                } ${pkg.is_featured ? 'ring-2 ring-yellow-400' : ''}`}
              >
                {pkg.is_featured && (
                  <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-yellow-400 text-yellow-900 text-xs font-bold px-3 py-1 rounded-full">
                    FEATURED
                  </div>
                )}

                <div className="text-center">
                  <h3 className="text-lg font-bold mb-2">{pkg.name}</h3>
                  <div className="text-3xl font-bold text-[var(--color-brand-500)] mb-1">
                    {pkg.credits.toLocaleString()}
                  </div>
                  <div className="text-sm text-gray-600 mb-3">credits</div>
                  <div className="text-2xl font-bold mb-1">${pkg.price}</div>
                  {pkg.discount_percentage > 0 && (
                    <div className="text-sm text-green-600 font-semibold">
                      Save {pkg.discount_percentage}%
                    </div>
                  )}
                  {pkg.description && (
                    <p className="text-sm text-gray-600 mt-3">{pkg.description}</p>
                  )}
                </div>

                {selectedPackage?.id === pkg.id && (
                  <div className="absolute top-3 right-3">
                    <div className="w-6 h-6 bg-[var(--color-brand-500)] rounded-full flex items-center justify-center">
                      <Check className="w-4 h-4 text-white" />
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Payment Methods */}
        {selectedPackage && (
          <div className="mb-8">
            <h2 className="text-xl font-semibold mb-4">Select Payment Method</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {paymentMethods.map((method) => (
                <div
                  key={method.id || method.type}
                  onClick={() => setSelectedPaymentMethod(method.type)}
                  className={`cursor-pointer rounded-lg border-2 p-4 transition-all ${
                    selectedPaymentMethod === method.type
                      ? 'border-[var(--color-brand-500)] bg-[var(--color-brand-50)]'
                      : 'border-gray-200 hover:border-[var(--color-brand-300)] bg-white'
                  }`}
                >
                  <div className="flex items-start gap-3">
                    <div
                      className={`p-2 rounded-lg ${
                        selectedPaymentMethod === method.type
                          ? 'bg-[var(--color-brand-500)] text-white'
                          : 'bg-gray-100 text-gray-600'
                      }`}
                    >
                      {getPaymentMethodIcon(method.type)}
                    </div>
                    <div className="flex-1">
                      <h3 className="font-semibold mb-1">{method.name || method.display_name}</h3>
                      <p className="text-sm text-gray-600">{method.instructions}</p>
                    </div>
                    {selectedPaymentMethod === method.type && (
                      <Check className="w-5 h-5 text-[var(--color-brand-500)] flex-shrink-0" />
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Purchase Button */}
        {selectedPackage && selectedPaymentMethod && (
          <div className="bg-white rounded-lg shadow p-6">
            <div className="flex items-center justify-between mb-4">
              <div>
                <div className="text-sm text-gray-600">You're purchasing:</div>
                <div className="text-lg font-bold">{selectedPackage.name}</div>
                <div className="text-sm text-gray-600">
                  {selectedPackage.credits.toLocaleString()} credits
                </div>
              </div>
              <div className="text-right">
                <div className="text-sm text-gray-600">Total:</div>
                <div className="text-3xl font-bold text-[var(--color-brand-500)]">
                  ${selectedPackage.price}
                </div>
              </div>
            </div>

            <Button
              variant="primary"
              tone="brand"
              size="lg"
              onClick={handlePurchase}
              disabled={purchasing}
              startIcon={purchasing ? <Loader2 className="w-5 h-5 animate-spin" /> : undefined}
              fullWidth
            >
              {purchasing ? 'Processing...' : 'Proceed to Payment'}
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
