/**
 * WithdrawForm Component
 * Form for withdrawing funds from an investment account
 */

import { useState } from 'react';
import { useForm } from 'react-hook-form';

// ============================================================================
// Types
// ============================================================================

type WithdrawalMethod = 'bank_transfer' | 'crypto';

interface WithdrawFormData {
  amount: number;
  accountId: string;
  method: WithdrawalMethod;
  // Bank details
  bankName?: string;
  accountNumber?: string;
  routingNumber?: string;
  accountHolderName?: string;
  // Crypto details
  network?: string;
  walletAddress?: string;
  // 2FA
  verificationCode: string;
}

interface WithdrawFormProps {
  accounts: Array<{
    id: string;
    accountNumber: string;
    productName: string;
    currentBalance: number;
  }>;
  onSuccess?: (withdrawalId: string) => void;
  onCancel?: () => void;
}

// ============================================================================
// Constants
// ============================================================================

const DAILY_LIMIT = 10000;
const MIN_WITHDRAWAL = 50;

// ============================================================================
// Component
// ============================================================================

export function WithdrawForm({ accounts, onSuccess, onCancel }: WithdrawFormProps) {
  const [processing, setProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [step, setStep] = useState<'details' | 'verify'>('details');

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<WithdrawFormData>({
    defaultValues: {
      amount: MIN_WITHDRAWAL,
      accountId: accounts[0]?.id || '',
      method: 'bank_transfer',
      verificationCode: '',
    },
  });

  const selectedAccountId = watch('accountId');
  const selectedAccount = accounts.find((a) => a.id === selectedAccountId);
  const selectedMethod = watch('method');
  const amount = watch('amount');

  const maxWithdrawal = Math.min(selectedAccount?.currentBalance || 0, DAILY_LIMIT);

  const handleDetailsSubmit = async () => {
    // Move to verification step
    setStep('verify');
  };

  const onSubmit = async (data: WithdrawFormData) => {
    setProcessing(true);
    setError(null);

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('Please log in to continue');
      }

      const withdrawalData = {
        accountId: data.accountId,
        amount: data.amount,
        ...(data.method === 'bank_transfer'
          ? {
              bankInfo: {
                bankName: data.bankName,
                accountNumber: data.accountNumber,
                routingNumber: data.routingNumber,
                accountHolderName: data.accountHolderName,
              },
            }
          : {
              cryptoInfo: {
                network: data.network,
                address: data.walletAddress,
              },
            }),
        verificationCode: data.verificationCode,
      };

      const response = await fetch('/api/v1/investment/accounts/' + data.accountId + '/withdraw', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(withdrawalData),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Withdrawal request failed');
      }

      const result = await response.json();
      setSuccess(true);
      onSuccess?.(result.data?.id);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
      // Go back to details step on error
      setStep('details');
    } finally {
      setProcessing(false);
    }
  };

  if (success) {
    return (
      <div className="text-center py-8">
        <div className="w-16 h-16 mx-auto mb-4 bg-emerald-500/20 rounded-full flex items-center justify-center">
          <svg className="w-8 h-8 text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
          </svg>
        </div>
        <h3 className="text-lg font-semibold text-white mb-2">Withdrawal Requested!</h3>
        <p className="text-slate-400">
          Your withdrawal request has been submitted. It will be processed within 1-3 business days.
        </p>
        <button
          type="button"
          onClick={onCancel}
          className="mt-6 px-6 py-2 bg-slate-700 text-white rounded-lg hover:bg-slate-600 transition-colors"
        >
          Close
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit(step === 'details' ? handleDetailsSubmit : onSubmit)} className="space-y-6">
      {step === 'details' && (
        <>
          {/* Account Selection */}
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-2">
              Withdraw From
            </label>
            <select
              {...register('accountId', { required: 'Please select an account' })}
              className="w-full px-4 py-2.5 bg-slate-800 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {accounts.map((account) => (
                <option key={account.id} value={account.id}>
                  {account.productName} ({account.accountNumber}) - ${account.currentBalance.toFixed(2)}
                </option>
              ))}
            </select>
            {errors.accountId && (
              <p className="mt-1 text-sm text-red-400">{errors.accountId.message}</p>
            )}
          </div>

          {/* Amount Input */}
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-2">
              Amount (USD)
            </label>
            <div className="relative">
              <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">$</span>
              <input
                type="number"
                step="0.01"
                min={MIN_WITHDRAWAL}
                max={maxWithdrawal}
                {...register('amount', {
                  required: 'Amount is required',
                  min: { value: MIN_WITHDRAWAL, message: `Minimum withdrawal is $${MIN_WITHDRAWAL}` },
                  max: { value: maxWithdrawal, message: `Maximum withdrawal is $${maxWithdrawal.toFixed(2)}` },
                })}
                className="w-full pl-8 pr-4 py-2.5 bg-slate-800 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="0.00"
              />
            </div>
            {errors.amount && (
              <p className="mt-1 text-sm text-red-400">{errors.amount.message}</p>
            )}
            <div className="mt-2 flex items-center justify-between text-sm">
              <span className="text-slate-400">Available: ${selectedAccount?.currentBalance.toFixed(2) || '0.00'}</span>
              <button
                type="button"
                onClick={() => {
                  const input = document.querySelector<HTMLInputElement>('input[name="amount"]');
                  if (input) {
                    input.value = String(maxWithdrawal);
                    input.dispatchEvent(new Event('input', { bubbles: true }));
                  }
                }}
                className="text-blue-400 hover:text-blue-300"
              >
                Withdraw Max
              </button>
            </div>
          </div>

          {/* Withdrawal Method */}
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-2">
              Withdrawal Method
            </label>
            <div className="grid grid-cols-2 gap-3">
              <label className={`
                flex items-center gap-3 p-4 rounded-lg border cursor-pointer transition-colors
                ${selectedMethod === 'bank_transfer'
                  ? 'bg-blue-500/10 border-blue-500/50'
                  : 'bg-slate-800 border-slate-700 hover:border-slate-600'
                }
              `}>
                <input
                  type="radio"
                  {...register('method')}
                  value="bank_transfer"
                  className="sr-only"
                />
                <svg className="w-6 h-6 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                    d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                </svg>
                <div>
                  <p className="font-medium text-white">Bank Transfer</p>
                  <p className="text-xs text-slate-400">1-3 business days</p>
                </div>
              </label>

              <label className={`
                flex items-center gap-3 p-4 rounded-lg border cursor-pointer transition-colors
                ${selectedMethod === 'crypto'
                  ? 'bg-blue-500/10 border-blue-500/50'
                  : 'bg-slate-800 border-slate-700 hover:border-slate-600'
                }
              `}>
                <input
                  type="radio"
                  {...register('method')}
                  value="crypto"
                  className="sr-only"
                />
                <svg className="w-6 h-6 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                    d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <div>
                  <p className="font-medium text-white">Crypto</p>
                  <p className="text-xs text-slate-400">24-48 hours</p>
                </div>
              </label>
            </div>
          </div>

          {/* Bank Details */}
          {selectedMethod === 'bank_transfer' && (
            <div className="space-y-4 p-4 bg-slate-800/50 rounded-lg border border-slate-700">
              <h4 className="font-medium text-white">Bank Account Details</h4>

              <div className="grid grid-cols-2 gap-4">
                <div className="col-span-2">
                  <label className="block text-sm text-slate-400 mb-1">Bank Name</label>
                  <input
                    type="text"
                    {...register('bankName', { required: selectedMethod === 'bank_transfer' ? 'Bank name is required' : false })}
                    className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Bank of America"
                  />
                </div>
                <div>
                  <label className="block text-sm text-slate-400 mb-1">Account Number</label>
                  <input
                    type="text"
                    {...register('accountNumber', { required: selectedMethod === 'bank_transfer' ? 'Account number is required' : false })}
                    className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="****1234"
                  />
                </div>
                <div>
                  <label className="block text-sm text-slate-400 mb-1">Routing Number</label>
                  <input
                    type="text"
                    {...register('routingNumber', { required: selectedMethod === 'bank_transfer' ? 'Routing number is required' : false })}
                    className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="021000021"
                  />
                </div>
                <div className="col-span-2">
                  <label className="block text-sm text-slate-400 mb-1">Account Holder Name</label>
                  <input
                    type="text"
                    {...register('accountHolderName', { required: selectedMethod === 'bank_transfer' ? 'Account holder name is required' : false })}
                    className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="John Doe"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Crypto Details */}
          {selectedMethod === 'crypto' && (
            <div className="space-y-4 p-4 bg-slate-800/50 rounded-lg border border-slate-700">
              <h4 className="font-medium text-white">Crypto Wallet Details</h4>

              <div>
                <label className="block text-sm text-slate-400 mb-1">Network</label>
                <select
                  {...register('network', { required: selectedMethod === 'crypto' ? 'Network is required' : false })}
                  className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">Select network</option>
                  <option value="ethereum">Ethereum (ERC-20)</option>
                  <option value="bitcoin">Bitcoin</option>
                  <option value="tron">Tron (TRC-20)</option>
                  <option value="bsc">BNB Smart Chain (BEP-20)</option>
                </select>
              </div>
              <div>
                <label className="block text-sm text-slate-400 mb-1">Wallet Address</label>
                <input
                  type="text"
                  {...register('walletAddress', { required: selectedMethod === 'crypto' ? 'Wallet address is required' : false })}
                  className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white font-mono text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="0x..."
                />
              </div>
            </div>
          )}
        </>
      )}

      {step === 'verify' && (
        <div className="space-y-6">
          {/* Summary */}
          <div className="p-4 bg-slate-800/50 rounded-lg border border-slate-700">
            <h4 className="font-medium text-white mb-3">Withdrawal Summary</h4>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-slate-400">Amount</span>
                <span className="text-white font-medium">${amount?.toFixed(2)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-400">From Account</span>
                <span className="text-white">{selectedAccount?.accountNumber}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-400">Method</span>
                <span className="text-white capitalize">{selectedMethod?.replace('_', ' ')}</span>
              </div>
            </div>
          </div>

          {/* 2FA Verification */}
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-2">
              Verification Code
            </label>
            <p className="text-sm text-slate-400 mb-3">
              Enter the 6-digit code from your authenticator app or the code sent to your email.
            </p>
            <input
              type="text"
              maxLength={6}
              {...register('verificationCode', {
                required: 'Verification code is required',
                pattern: { value: /^\d{6}$/, message: 'Please enter a valid 6-digit code' },
              })}
              className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-white text-center text-2xl tracking-widest font-mono focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="000000"
            />
            {errors.verificationCode && (
              <p className="mt-1 text-sm text-red-400">{errors.verificationCode.message}</p>
            )}
          </div>

          <button
            type="button"
            onClick={() => setStep('details')}
            className="text-sm text-slate-400 hover:text-white"
          >
            ← Back to details
          </button>
        </div>
      )}

      {/* Error Message */}
      {error && (
        <div className="p-4 bg-red-500/10 border border-red-500/30 rounded-lg">
          <p className="text-sm text-red-400">{error}</p>
        </div>
      )}

      {/* Warning */}
      <div className="p-4 bg-amber-500/10 border border-amber-500/30 rounded-lg">
        <div className="flex items-start gap-3">
          <svg className="w-5 h-5 text-amber-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
          <div className="text-sm text-slate-400">
            <p className="font-medium text-amber-400 mb-1">Important</p>
            <p>Daily withdrawal limit: ${DAILY_LIMIT.toLocaleString()}. Withdrawals are subject to review and may take 1-3 business days to process.</p>
          </div>
        </div>
      </div>

      {/* Actions */}
      <div className="flex gap-3">
        <button
          type="submit"
          disabled={processing}
          className="flex-1 px-6 py-2.5 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          {processing ? (
            <span className="flex items-center justify-center gap-2">
              <svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
              </svg>
              Processing...
            </span>
          ) : step === 'details' ? (
            'Continue'
          ) : (
            'Confirm Withdrawal'
          )}
        </button>
        {onCancel && (
          <button
            type="button"
            onClick={onCancel}
            disabled={processing}
            className="px-6 py-2.5 bg-slate-700 text-white font-medium rounded-lg hover:bg-slate-600 disabled:opacity-50 transition-colors"
          >
            Cancel
          </button>
        )}
      </div>
    </form>
  );
}

export default WithdrawForm;
