/**
 * PaymentMethodsList Component
 * Display and manage saved payment methods
 */

import React, { useState, useEffect } from 'react';
import {
  CreditCard,
  Plus,
  Trash2,
  Star,
  MoreVertical,
  AlertCircle,
  CheckCircle,
  Loader2,
  Shield,
  Building2,
  Smartphone,
  Wallet,
  Store,
  Banknote,
} from 'lucide-react';
import {
  getPaymentMethods,
  removePaymentMethod,
  setDefaultPaymentMethod,
} from '../../services/payment.service';
import type { PaymentMethodType } from '../../types/payment.types';

export interface PaymentMethod {
  id: string;
  type: PaymentMethodType;
  isDefault: boolean;
  card?: {
    brand: string;
    last4: string;
    expMonth: number;
    expYear: number;
  };
  bankAccount?: {
    bankName: string;
    last4: string;
    accountType: string;
  };
  oxxo?: {
    email: string;
  };
  spei?: {
    bankName: string;
    clabe: string;
  };
  createdAt: string;
}

interface PaymentMethodsListProps {
  onAddNew?: () => void;
  onMethodSelect?: (method: PaymentMethod) => void;
  selectable?: boolean;
  selectedId?: string;
  showAddButton?: boolean;
  compact?: boolean;
}

const PaymentMethodsList: React.FC<PaymentMethodsListProps> = ({
  onAddNew,
  onMethodSelect,
  selectable = false,
  selectedId,
  showAddButton = true,
  compact = false,
}) => {
  const [methods, setMethods] = useState<PaymentMethod[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [openMenuId, setOpenMenuId] = useState<string | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);

  const fetchMethods = async () => {
    setLoading(true);
    setError(null);

    try {
      const data = await getPaymentMethods();
      setMethods(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load payment methods');
    } finally {
      setLoading(false);
    }
  };

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

  const handleSetDefault = async (methodId: string) => {
    setActionLoading(methodId);
    setOpenMenuId(null);

    try {
      await setDefaultPaymentMethod(methodId);
      setMethods((prev) =>
        prev.map((m) => ({
          ...m,
          isDefault: m.id === methodId,
        }))
      );
    } catch (err) {
      console.error('Failed to set default:', err);
    } finally {
      setActionLoading(null);
    }
  };

  const handleRemove = async (methodId: string) => {
    setActionLoading(methodId);
    setConfirmDelete(null);
    setOpenMenuId(null);

    try {
      await removePaymentMethod(methodId);
      setMethods((prev) => prev.filter((m) => m.id !== methodId));
    } catch (err) {
      console.error('Failed to remove:', err);
    } finally {
      setActionLoading(null);
    }
  };

  const getPaymentMethodIcon = (method: PaymentMethod) => {
    switch (method.type) {
      case 'card':
        return <CreditCard className="w-6 h-6" />;
      case 'bank_account':
      case 'spei':
        return <Building2 className="w-6 h-6" />;
      case 'oxxo':
        return <Store className="w-6 h-6" />;
      case 'paypal':
        return <Wallet className="w-6 h-6" />;
      case 'google_pay':
      case 'apple_pay':
        return <Smartphone className="w-6 h-6" />;
      default:
        return <Banknote className="w-6 h-6" />;
    }
  };

  const getPaymentMethodColor = (method: PaymentMethod) => {
    switch (method.type) {
      case 'card':
        return getCardBrandColor(method.card?.brand || '');
      case 'oxxo':
        return 'text-red-400';
      case 'spei':
        return 'text-blue-500';
      case 'paypal':
        return 'text-blue-400';
      case 'google_pay':
        return 'text-green-400';
      case 'apple_pay':
        return 'text-gray-300';
      case 'bank_account':
        return 'text-emerald-400';
      default:
        return 'text-gray-400';
    }
  };

  const getPaymentMethodLabel = (method: PaymentMethod): string => {
    switch (method.type) {
      case 'card':
        return method.card?.brand || 'Card';
      case 'oxxo':
        return 'OXXO Pay';
      case 'spei':
        return 'SPEI';
      case 'paypal':
        return 'PayPal';
      case 'google_pay':
        return 'Google Pay';
      case 'apple_pay':
        return 'Apple Pay';
      case 'bank_account':
        return method.bankAccount?.bankName || 'Bank Account';
      default:
        return 'Payment Method';
    }
  };

  const getPaymentMethodDetails = (method: PaymentMethod): string => {
    switch (method.type) {
      case 'card':
        return `**** ${method.card?.last4}`;
      case 'oxxo':
        return method.oxxo?.email || '';
      case 'spei':
        return method.spei?.clabe ? `CLABE: ****${method.spei.clabe.slice(-4)}` : '';
      case 'bank_account':
        return `**** ${method.bankAccount?.last4}`;
      default:
        return '';
    }
  };

  const getCardBrandColor = (brand: string) => {
    switch (brand.toLowerCase()) {
      case 'visa':
        return 'text-blue-400';
      case 'mastercard':
        return 'text-orange-400';
      case 'amex':
        return 'text-blue-300';
      case 'discover':
        return 'text-orange-300';
      default:
        return 'text-gray-400';
    }
  };

  const isExpiringSoon = (expMonth: number, expYear: number) => {
    const now = new Date();
    const expDate = new Date(expYear, expMonth - 1);
    const threeMonths = new Date();
    threeMonths.setMonth(threeMonths.getMonth() + 3);
    return expDate <= threeMonths && expDate >= now;
  };

  const isExpired = (expMonth: number, expYear: number) => {
    const now = new Date();
    const expDate = new Date(expYear, expMonth);
    return expDate < now;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-8">
        <Loader2 className="w-6 h-6 text-blue-400 animate-spin" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-8">
        <AlertCircle className="w-10 h-10 text-red-400 mx-auto mb-3" />
        <p className="text-gray-400 mb-4">{error}</p>
        <button
          onClick={fetchMethods}
          className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm"
        >
          Retry
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {/* Payment Methods List */}
      {methods.length === 0 ? (
        <div className="text-center py-8 bg-gray-800/50 rounded-xl border border-gray-700">
          <CreditCard className="w-12 h-12 text-gray-600 mx-auto mb-3" />
          <p className="text-gray-400 mb-4">No payment methods saved</p>
          {showAddButton && onAddNew && (
            <button
              onClick={onAddNew}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm"
            >
              Add Payment Method
            </button>
          )}
        </div>
      ) : (
        <>
          {methods.map((method) => {
            const isSelected = selectable && selectedId === method.id;
            const expired = method.card && isExpired(method.card.expMonth, method.card.expYear);
            const expiringSoon = method.card && !expired && isExpiringSoon(method.card.expMonth, method.card.expYear);

            return (
              <div
                key={method.id}
                onClick={() => selectable && !expired && onMethodSelect?.(method)}
                className={`relative flex items-center justify-between p-4 bg-gray-800/50 rounded-xl border transition-all ${
                  isSelected
                    ? 'border-blue-500 ring-2 ring-blue-500/20'
                    : expired
                    ? 'border-red-500/30 opacity-60'
                    : 'border-gray-700 hover:border-gray-600'
                } ${selectable && !expired ? 'cursor-pointer' : ''}`}
              >
                {/* Payment Method Info */}
                <div className="flex items-center gap-4">
                  <div className={`p-3 bg-gray-900 rounded-lg ${getPaymentMethodColor(method)}`}>
                    {getPaymentMethodIcon(method)}
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-white font-medium capitalize">
                        {getPaymentMethodLabel(method)}
                      </span>
                      {getPaymentMethodDetails(method) && (
                        <span className="text-gray-400">{getPaymentMethodDetails(method)}</span>
                      )}
                      {method.isDefault && (
                        <span className="flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 rounded text-xs">
                          <Star className="w-3 h-3" />
                          Default
                        </span>
                      )}
                    </div>
                    <div className="flex items-center gap-2 mt-1">
                      {method.type === 'card' && method.card && (
                        <span className={`text-sm ${expired ? 'text-red-400' : expiringSoon ? 'text-yellow-400' : 'text-gray-500'}`}>
                          {expired ? 'Expired' : `Expires ${method.card.expMonth}/${method.card.expYear}`}
                        </span>
                      )}
                      {method.type === 'oxxo' && (
                        <span className="text-sm text-gray-500">Pay at any OXXO store</span>
                      )}
                      {method.type === 'spei' && (
                        <span className="text-sm text-gray-500">Bank transfer (Mexico)</span>
                      )}
                      {method.type === 'bank_account' && method.bankAccount && (
                        <span className="text-sm text-gray-500">{method.bankAccount.accountType}</span>
                      )}
                      {expiringSoon && !expired && method.type === 'card' && (
                        <span className="text-xs text-yellow-400">(expiring soon)</span>
                      )}
                    </div>
                  </div>
                </div>

                {/* Actions */}
                {!selectable && (
                  <div className="relative">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setOpenMenuId(openMenuId === method.id ? null : method.id);
                      }}
                      disabled={actionLoading === method.id}
                      className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
                    >
                      {actionLoading === method.id ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <MoreVertical className="w-4 h-4" />
                      )}
                    </button>

                    {/* Dropdown Menu */}
                    {openMenuId === method.id && (
                      <>
                        <div
                          className="fixed inset-0 z-10"
                          onClick={() => setOpenMenuId(null)}
                        />
                        <div className="absolute right-0 top-full mt-1 w-48 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-20 py-1">
                          {!method.isDefault && (
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                handleSetDefault(method.id);
                              }}
                              className="w-full flex items-center gap-3 px-3 py-2 text-sm text-gray-300 hover:bg-gray-700"
                            >
                              <Star className="w-4 h-4" />
                              Set as Default
                            </button>
                          )}
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              setConfirmDelete(method.id);
                              setOpenMenuId(null);
                            }}
                            className="w-full flex items-center gap-3 px-3 py-2 text-sm text-red-400 hover:bg-red-500/10"
                          >
                            <Trash2 className="w-4 h-4" />
                            Remove
                          </button>
                        </div>
                      </>
                    )}
                  </div>
                )}

                {/* Selection Indicator */}
                {selectable && isSelected && (
                  <div className="p-1 bg-blue-600 rounded-full">
                    <CheckCircle className="w-5 h-5 text-white" />
                  </div>
                )}
              </div>
            );
          })}

          {/* Add New Button */}
          {showAddButton && onAddNew && (
            <button
              onClick={onAddNew}
              className="w-full flex items-center justify-center gap-2 p-4 border-2 border-dashed border-gray-700 hover:border-gray-600 rounded-xl text-gray-400 hover:text-white transition-colors"
            >
              <Plus className="w-5 h-5" />
              Add New Payment Method
            </button>
          )}
        </>
      )}

      {/* Delete Confirmation Modal */}
      {confirmDelete && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70">
          <div className="w-full max-w-sm bg-gray-800 rounded-xl p-6">
            <div className="text-center">
              <div className="w-12 h-12 mx-auto mb-4 bg-red-500/20 rounded-full flex items-center justify-center">
                <Trash2 className="w-6 h-6 text-red-400" />
              </div>
              <h3 className="text-lg font-semibold text-white mb-2">Remove Payment Method?</h3>
              <p className="text-gray-400 text-sm mb-6">
                This payment method will be permanently removed. This action cannot be undone.
              </p>
              <div className="flex items-center gap-3">
                <button
                  onClick={() => setConfirmDelete(null)}
                  className="flex-1 py-2.5 bg-gray-700 hover:bg-gray-600 text-white rounded-lg font-medium transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => handleRemove(confirmDelete)}
                  disabled={actionLoading === confirmDelete}
                  className="flex-1 py-2.5 bg-red-600 hover:bg-red-500 text-white rounded-lg font-medium transition-colors disabled:opacity-50"
                >
                  {actionLoading === confirmDelete ? (
                    <Loader2 className="w-5 h-5 mx-auto animate-spin" />
                  ) : (
                    'Remove'
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Security Note */}
      {!compact && methods.length > 0 && (
        <div className="flex items-center gap-2 p-3 bg-gray-900/50 rounded-lg">
          <Shield className="w-4 h-4 text-green-400" />
          <p className="text-xs text-gray-500">
            Your payment information is securely stored and encrypted
          </p>
        </div>
      )}
    </div>
  );
};

export default PaymentMethodsList;
