/**
 * AccountTransferModal Component
 * Modal for transferring funds between investment accounts
 * Epic: OQI-004 Cuentas de Inversion
 */

import React, { useState, useMemo, useCallback, useEffect } from 'react';
import {
  ArrowRightLeft,
  Wallet,
  AlertCircle,
  CheckCircle,
  Info,
  X,
  ChevronDown,
  Loader2,
  ArrowRight,
} from 'lucide-react';

// Types
export interface TransferAccount {
  id: string;
  name: string;
  productName: string;
  balance: number;
  availableBalance: number;
  status: 'active' | 'pending' | 'locked';
  color: string;
}

export interface TransferFee {
  type: 'fixed' | 'percentage';
  value: number;
  minFee?: number;
  maxFee?: number;
}

export interface TransferData {
  sourceAccountId: string;
  destinationAccountId: string;
  amount: number;
  fee: number;
  note?: string;
}

export interface AccountTransferModalProps {
  isOpen: boolean;
  accounts: TransferAccount[];
  defaultSourceId?: string;
  defaultDestinationId?: string;
  transferFee?: TransferFee;
  minTransfer?: number;
  maxTransfer?: number;
  onTransfer?: (data: TransferData) => void;
  onClose?: () => void;
  isSubmitting?: boolean;
}

const AccountTransferModal: React.FC<AccountTransferModalProps> = ({
  isOpen,
  accounts,
  defaultSourceId,
  defaultDestinationId,
  transferFee = { type: 'fixed', value: 0 },
  minTransfer = 100,
  maxTransfer = 100000,
  onTransfer,
  onClose,
  isSubmitting = false,
}) => {
  const [sourceAccountId, setSourceAccountId] = useState<string>(defaultSourceId || '');
  const [destinationAccountId, setDestinationAccountId] = useState<string>(defaultDestinationId || '');
  const [amount, setAmount] = useState<string>('');
  const [note, setNote] = useState<string>('');
  const [showSourceDropdown, setShowSourceDropdown] = useState(false);
  const [showDestDropdown, setShowDestDropdown] = useState(false);
  const [step, setStep] = useState<'form' | 'confirm' | 'success'>('form');

  // Reset state when modal opens
  useEffect(() => {
    if (isOpen) {
      setSourceAccountId(defaultSourceId || '');
      setDestinationAccountId(defaultDestinationId || '');
      setAmount('');
      setNote('');
      setStep('form');
    }
  }, [isOpen, defaultSourceId, defaultDestinationId]);

  // Get selected accounts
  const sourceAccount = useMemo(() => {
    return accounts.find((acc) => acc.id === sourceAccountId);
  }, [accounts, sourceAccountId]);

  const destinationAccount = useMemo(() => {
    return accounts.find((acc) => acc.id === destinationAccountId);
  }, [accounts, destinationAccountId]);

  // Calculate fee
  const calculatedFee = useMemo(() => {
    const transferAmount = parseFloat(amount) || 0;
    if (transferFee.type === 'fixed') {
      return transferFee.value;
    }
    let fee = transferAmount * (transferFee.value / 100);
    if (transferFee.minFee) fee = Math.max(fee, transferFee.minFee);
    if (transferFee.maxFee) fee = Math.min(fee, transferFee.maxFee);
    return fee;
  }, [amount, transferFee]);

  // Calculate total deduction
  const totalDeduction = useMemo(() => {
    return (parseFloat(amount) || 0) + calculatedFee;
  }, [amount, calculatedFee]);

  // Validation
  const validation = useMemo(() => {
    const transferAmount = parseFloat(amount) || 0;
    const errors: string[] = [];

    if (!sourceAccountId) {
      errors.push('Select a source account');
    }
    if (!destinationAccountId) {
      errors.push('Select a destination account');
    }
    if (sourceAccountId && destinationAccountId && sourceAccountId === destinationAccountId) {
      errors.push('Source and destination must be different');
    }
    if (transferAmount < minTransfer) {
      errors.push(`Minimum transfer is $${minTransfer.toLocaleString()}`);
    }
    if (transferAmount > maxTransfer) {
      errors.push(`Maximum transfer is $${maxTransfer.toLocaleString()}`);
    }
    if (sourceAccount && totalDeduction > sourceAccount.availableBalance) {
      errors.push('Insufficient available balance');
    }
    if (sourceAccount && sourceAccount.status !== 'active') {
      errors.push('Source account is not active');
    }
    if (destinationAccount && destinationAccount.status !== 'active') {
      errors.push('Destination account is not active');
    }

    return {
      isValid: errors.length === 0 && transferAmount > 0,
      errors,
    };
  }, [sourceAccountId, destinationAccountId, amount, sourceAccount, destinationAccount, totalDeduction, minTransfer, maxTransfer]);

  // Handle transfer
  const handleTransfer = useCallback(() => {
    if (!validation.isValid) return;

    const transferData: TransferData = {
      sourceAccountId,
      destinationAccountId,
      amount: parseFloat(amount),
      fee: calculatedFee,
      note: note || undefined,
    };

    onTransfer?.(transferData);
  }, [validation.isValid, sourceAccountId, destinationAccountId, amount, calculatedFee, note, onTransfer]);

  // Handle confirm step
  const handleProceed = useCallback(() => {
    if (step === 'form' && validation.isValid) {
      setStep('confirm');
    } else if (step === 'confirm') {
      handleTransfer();
    }
  }, [step, validation.isValid, handleTransfer]);

  // Swap accounts
  const handleSwapAccounts = useCallback(() => {
    const temp = sourceAccountId;
    setSourceAccountId(destinationAccountId);
    setDestinationAccountId(temp);
  }, [sourceAccountId, destinationAccountId]);

  // Quick amount buttons
  const quickAmounts = useMemo(() => {
    if (!sourceAccount) return [];
    const balance = sourceAccount.availableBalance;
    return [
      { label: '25%', value: Math.floor(balance * 0.25) },
      { label: '50%', value: Math.floor(balance * 0.5) },
      { label: '75%', value: Math.floor(balance * 0.75) },
      { label: 'Max', value: Math.floor(balance - calculatedFee) },
    ].filter((q) => q.value >= minTransfer);
  }, [sourceAccount, calculatedFee, minTransfer]);

  // Render account selector
  const renderAccountSelector = (
    type: 'source' | 'destination',
    selectedId: string,
    onSelect: (id: string) => void,
    isOpen: boolean,
    setIsOpen: (open: boolean) => void
  ) => {
    const selectedAccount = accounts.find((acc) => acc.id === selectedId);
    const availableAccounts = accounts.filter((acc) => {
      if (type === 'source') return acc.id !== destinationAccountId && acc.status === 'active';
      return acc.id !== sourceAccountId;
    });

    return (
      <div className="relative">
        <button
          onClick={() => setIsOpen(!isOpen)}
          className="w-full flex items-center justify-between bg-slate-800 border border-slate-700 rounded-lg px-4 py-3 text-left hover:border-slate-600 transition-colors"
        >
          {selectedAccount ? (
            <div className="flex items-center gap-3">
              <div
                className="w-3 h-3 rounded-full"
                style={{ backgroundColor: selectedAccount.color }}
              />
              <div>
                <p className="text-white font-medium">{selectedAccount.name}</p>
                <p className="text-slate-400 text-sm">
                  Available: ${selectedAccount.availableBalance.toLocaleString()}
                </p>
              </div>
            </div>
          ) : (
            <span className="text-slate-400">Select {type} account</span>
          )}
          <ChevronDown className={`w-5 h-5 text-slate-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
        </button>

        {isOpen && (
          <div className="absolute z-10 w-full mt-2 bg-slate-800 border border-slate-700 rounded-lg shadow-xl overflow-hidden">
            {availableAccounts.map((account) => (
              <button
                key={account.id}
                onClick={() => {
                  onSelect(account.id);
                  setIsOpen(false);
                }}
                disabled={account.status !== 'active'}
                className={`w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-slate-700 transition-colors ${
                  account.status !== 'active' ? 'opacity-50 cursor-not-allowed' : ''
                }`}
              >
                <div
                  className="w-3 h-3 rounded-full"
                  style={{ backgroundColor: account.color }}
                />
                <div className="flex-1">
                  <div className="flex items-center justify-between">
                    <p className="text-white font-medium">{account.name}</p>
                    {account.status !== 'active' && (
                      <span className="text-xs text-amber-400 capitalize">{account.status}</span>
                    )}
                  </div>
                  <p className="text-slate-400 text-sm">{account.productName}</p>
                  <p className="text-slate-500 text-xs">
                    Balance: ${account.balance.toLocaleString()} |
                    Available: ${account.availableBalance.toLocaleString()}
                  </p>
                </div>
              </button>
            ))}
            {availableAccounts.length === 0 && (
              <p className="px-4 py-3 text-slate-400 text-sm">No accounts available</p>
            )}
          </div>
        )}
      </div>
    );
  };

  // Render form step
  const renderFormStep = () => (
    <div className="space-y-6">
      {/* Source Account */}
      <div>
        <label className="block text-slate-300 text-sm font-medium mb-2">From Account</label>
        {renderAccountSelector(
          'source',
          sourceAccountId,
          setSourceAccountId,
          showSourceDropdown,
          setShowSourceDropdown
        )}
      </div>

      {/* Swap Button */}
      <div className="flex justify-center">
        <button
          onClick={handleSwapAccounts}
          disabled={!sourceAccountId || !destinationAccountId}
          className="p-2 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          title="Swap accounts"
        >
          <ArrowRightLeft className="w-5 h-5" />
        </button>
      </div>

      {/* Destination Account */}
      <div>
        <label className="block text-slate-300 text-sm font-medium mb-2">To Account</label>
        {renderAccountSelector(
          'destination',
          destinationAccountId,
          setDestinationAccountId,
          showDestDropdown,
          setShowDestDropdown
        )}
      </div>

      {/* Amount */}
      <div>
        <label className="block text-slate-300 text-sm font-medium mb-2">Amount</label>
        <div className="relative">
          <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500">$</span>
          <input
            type="number"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            placeholder="0.00"
            min={minTransfer}
            max={maxTransfer}
            className="w-full bg-slate-800 border border-slate-700 rounded-lg pl-8 pr-4 py-3 text-white text-lg focus:border-blue-500 focus:outline-none"
          />
        </div>
        <div className="flex justify-between text-xs text-slate-500 mt-1">
          <span>Min: ${minTransfer.toLocaleString()}</span>
          <span>Max: ${maxTransfer.toLocaleString()}</span>
        </div>

        {/* Quick Amount Buttons */}
        {quickAmounts.length > 0 && (
          <div className="flex gap-2 mt-3">
            {quickAmounts.map((quick) => (
              <button
                key={quick.label}
                onClick={() => setAmount(quick.value.toString())}
                className="px-3 py-1.5 bg-slate-800 text-slate-300 text-sm rounded-lg hover:bg-slate-700 transition-colors"
              >
                {quick.label}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Note */}
      <div>
        <label className="block text-slate-300 text-sm font-medium mb-2">Note (Optional)</label>
        <input
          type="text"
          value={note}
          onChange={(e) => setNote(e.target.value)}
          placeholder="Add a note for this transfer"
          maxLength={100}
          className="w-full bg-slate-800 border border-slate-700 rounded-lg px-4 py-2 text-white focus:border-blue-500 focus:outline-none"
        />
      </div>

      {/* Summary */}
      {parseFloat(amount) > 0 && (
        <div className="bg-slate-800/50 rounded-lg p-4 border border-slate-700 space-y-2">
          <div className="flex justify-between text-sm">
            <span className="text-slate-400">Transfer Amount</span>
            <span className="text-white">${parseFloat(amount).toLocaleString()}</span>
          </div>
          {calculatedFee > 0 && (
            <div className="flex justify-between text-sm">
              <span className="text-slate-400">Transfer Fee</span>
              <span className="text-slate-300">${calculatedFee.toFixed(2)}</span>
            </div>
          )}
          <div className="flex justify-between text-sm pt-2 border-t border-slate-700">
            <span className="text-slate-300 font-medium">Total Deduction</span>
            <span className="text-white font-medium">${totalDeduction.toLocaleString()}</span>
          </div>
        </div>
      )}

      {/* Validation Errors */}
      {validation.errors.length > 0 && parseFloat(amount) > 0 && (
        <div className="space-y-2">
          {validation.errors.map((error, index) => (
            <p key={index} className="text-red-400 text-sm flex items-center gap-2">
              <AlertCircle className="w-4 h-4" />
              {error}
            </p>
          ))}
        </div>
      )}
    </div>
  );

  // Render confirm step
  const renderConfirmStep = () => (
    <div className="space-y-6">
      <div className="text-center">
        <div className="w-16 h-16 rounded-full bg-blue-600/20 flex items-center justify-center mx-auto mb-4">
          <ArrowRightLeft className="w-8 h-8 text-blue-400" />
        </div>
        <h3 className="text-white text-xl font-semibold">Confirm Transfer</h3>
        <p className="text-slate-400 mt-1">Please review the details below</p>
      </div>

      {/* Transfer Visual */}
      <div className="flex items-center justify-between gap-4">
        {/* Source */}
        <div className="flex-1 bg-slate-800/50 rounded-lg p-4 border border-slate-700">
          <div className="flex items-center gap-2 mb-2">
            <div
              className="w-3 h-3 rounded-full"
              style={{ backgroundColor: sourceAccount?.color }}
            />
            <span className="text-slate-400 text-sm">From</span>
          </div>
          <p className="text-white font-medium">{sourceAccount?.name}</p>
          <p className="text-red-400 text-sm mt-1">-${totalDeduction.toLocaleString()}</p>
        </div>

        <ArrowRight className="w-6 h-6 text-slate-500 flex-shrink-0" />

        {/* Destination */}
        <div className="flex-1 bg-slate-800/50 rounded-lg p-4 border border-slate-700">
          <div className="flex items-center gap-2 mb-2">
            <div
              className="w-3 h-3 rounded-full"
              style={{ backgroundColor: destinationAccount?.color }}
            />
            <span className="text-slate-400 text-sm">To</span>
          </div>
          <p className="text-white font-medium">{destinationAccount?.name}</p>
          <p className="text-emerald-400 text-sm mt-1">+${parseFloat(amount).toLocaleString()}</p>
        </div>
      </div>

      {/* Summary */}
      <div className="bg-slate-800/50 rounded-lg p-4 border border-slate-700 space-y-3">
        <div className="flex justify-between">
          <span className="text-slate-400">Transfer Amount</span>
          <span className="text-white font-medium">${parseFloat(amount).toLocaleString()}</span>
        </div>
        {calculatedFee > 0 && (
          <div className="flex justify-between">
            <span className="text-slate-400">Fee</span>
            <span className="text-slate-300">${calculatedFee.toFixed(2)}</span>
          </div>
        )}
        {note && (
          <div className="flex justify-between">
            <span className="text-slate-400">Note</span>
            <span className="text-slate-300 text-right max-w-[200px] truncate">{note}</span>
          </div>
        )}
        <div className="flex justify-between pt-3 border-t border-slate-700">
          <span className="text-white font-medium">Total Deduction</span>
          <span className="text-white font-semibold">${totalDeduction.toLocaleString()}</span>
        </div>
      </div>

      {/* Info */}
      <div className="bg-blue-900/20 border border-blue-800/50 rounded-lg p-4">
        <div className="flex items-start gap-3">
          <Info className="w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5" />
          <p className="text-slate-300 text-sm">
            The transfer will be processed immediately. Funds will be available in the destination
            account within minutes. This action cannot be undone.
          </p>
        </div>
      </div>
    </div>
  );

  // Render success step
  const renderSuccessStep = () => (
    <div className="text-center py-8">
      <div className="w-20 h-20 rounded-full bg-emerald-600/20 flex items-center justify-center mx-auto mb-6">
        <CheckCircle className="w-10 h-10 text-emerald-400" />
      </div>
      <h3 className="text-white text-xl font-semibold">Transfer Complete!</h3>
      <p className="text-slate-400 mt-2">
        ${parseFloat(amount).toLocaleString()} has been transferred from{' '}
        <span className="text-white">{sourceAccount?.name}</span> to{' '}
        <span className="text-white">{destinationAccount?.name}</span>
      </p>
      <button
        onClick={onClose}
        className="mt-8 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-500 transition-colors"
      >
        Done
      </button>
    </div>
  );

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative w-full max-w-lg bg-slate-900 rounded-xl border border-slate-800 shadow-2xl mx-4">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-800">
          <div className="flex items-center gap-3">
            <Wallet className="w-6 h-6 text-blue-400" />
            <h2 className="text-white text-lg font-semibold">Transfer Funds</h2>
          </div>
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-white transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6">
          {step === 'form' && renderFormStep()}
          {step === 'confirm' && renderConfirmStep()}
          {step === 'success' && renderSuccessStep()}
        </div>

        {/* Footer */}
        {step !== 'success' && (
          <div className="flex justify-between gap-4 p-6 border-t border-slate-800">
            <button
              onClick={step === 'form' ? onClose : () => setStep('form')}
              className="px-4 py-2 text-slate-300 hover:text-white transition-colors"
            >
              {step === 'form' ? 'Cancel' : 'Back'}
            </button>
            <button
              onClick={handleProceed}
              disabled={!validation.isValid || isSubmitting}
              className="flex items-center gap-2 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Processing...
                </>
              ) : step === 'form' ? (
                'Continue'
              ) : (
                'Confirm Transfer'
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default AccountTransferModal;
