/**
 * Withdraw Page
 * Standalone page for withdrawing funds from investment accounts
 * Epic: OQI-004 Cuentas de Inversion
 */

import React, { useEffect, useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import {
  ArrowLeft,
  AlertCircle,
  Wallet,
  Shield,
  Clock,
  AlertTriangle,
} from 'lucide-react';
import { WithdrawForm } from '../components/WithdrawForm';
import { useInvestmentAccounts, useAccountSummary, useKYCStatus } from '../hooks';
import { KYCStatusBadge } from '../components/KYCStatusBadge';

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

interface AccountOption {
  id: string;
  accountNumber: string;
  productName: string;
  currentBalance: number;
}

// ============================================================================
// Main Component
// ============================================================================

export const Withdraw: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const preselectedAccountId = searchParams.get('accountId');

  const { data: accounts, isLoading: loadingAccounts, error: accountsError } = useInvestmentAccounts();
  const { data: summary } = useAccountSummary();
  const { data: kycData, isLoading: loadingKYC } = useKYCStatus();

  const [accountOptions, setAccountOptions] = useState<AccountOption[]>([]);

  useEffect(() => {
    if (accounts) {
      const options = accounts
        .filter(a => a.status === 'active' && a.balance > 0)
        .map(a => ({
          id: a.id,
          accountNumber: a.accountNumber,
          productName: a.product.name,
          currentBalance: a.balance,
        }));
      setAccountOptions(options);
    }
  }, [accounts]);

  const handleSuccess = (withdrawalId: string) => {
    // Navigate to withdrawals list with success message
    navigate('/investment/withdrawals', {
      state: { withdrawalSuccess: true, withdrawalId },
    });
  };

  const handleCancel = () => {
    navigate('/investment/portfolio');
  };

  const isLoading = loadingAccounts || loadingKYC;
  const isKYCApproved = kycData?.status === 'approved';
  const isKYCPending = kycData?.status === 'pending' || kycData?.status === 'in_review';

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-96">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (accountsError) {
    return (
      <div className="max-w-2xl mx-auto px-4 py-8">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-6 text-center">
          <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-red-600 dark:text-red-400 mb-2">
            Error al cargar cuentas
          </h3>
          <p className="text-red-500 dark:text-red-400 mb-4">
            {accountsError.message}
          </p>
          <Link
            to="/investment/portfolio"
            className="inline-block px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
          >
            Volver al Portfolio
          </Link>
        </div>
      </div>
    );
  }

  // KYC not approved - show verification required
  if (!isKYCApproved) {
    return (
      <div className="max-w-2xl mx-auto px-4 py-8">
        <div className="flex items-center gap-4 mb-8">
          <Link
            to="/investment/portfolio"
            className="p-2 rounded-lg bg-slate-800 border border-slate-700 hover:border-slate-600"
          >
            <ArrowLeft className="w-5 h-5 text-slate-400" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-white">Retirar Fondos</h1>
            <p className="text-slate-400">Solicita un retiro de tus cuentas de inversion</p>
          </div>
        </div>

        <div className="bg-slate-800/50 border border-slate-700 rounded-xl p-8 text-center">
          <Shield className="w-16 h-16 text-amber-400 mx-auto mb-4" />
          <h3 className="text-xl font-bold text-white mb-2">
            Verificacion de Identidad Requerida
          </h3>
          <p className="text-slate-400 mb-6 max-w-md mx-auto">
            Para poder realizar retiros, necesitas completar la verificacion de identidad (KYC).
            Este proceso ayuda a proteger tu cuenta y cumplir con regulaciones.
          </p>

          {kycData && (
            <div className="mb-6">
              <KYCStatusBadge status={kycData.status} size="lg" />
            </div>
          )}

          {isKYCPending ? (
            <div className="bg-blue-900/20 border border-blue-800/50 rounded-lg p-4 mb-6">
              <div className="flex items-center justify-center gap-2 text-blue-400">
                <Clock className="w-5 h-5" />
                <span>Tu verificacion esta en proceso. Te notificaremos cuando este lista.</span>
              </div>
            </div>
          ) : (
            <Link
              to="/investment/kyc"
              className="inline-block px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
            >
              Iniciar Verificacion KYC
            </Link>
          )}
        </div>
      </div>
    );
  }

  // No accounts with balance
  if (accountOptions.length === 0) {
    return (
      <div className="max-w-2xl mx-auto px-4 py-8">
        <div className="flex items-center gap-4 mb-8">
          <Link
            to="/investment/portfolio"
            className="p-2 rounded-lg bg-slate-800 border border-slate-700 hover:border-slate-600"
          >
            <ArrowLeft className="w-5 h-5 text-slate-400" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-white">Retirar Fondos</h1>
            <p className="text-slate-400">Solicita un retiro de tus cuentas de inversion</p>
          </div>
        </div>

        <div className="text-center py-16 bg-slate-800/50 border border-slate-700 rounded-xl">
          <Wallet className="w-16 h-16 text-slate-600 mx-auto mb-4" />
          <h3 className="text-xl font-bold text-white mb-2">
            No hay fondos disponibles para retiro
          </h3>
          <p className="text-slate-400 mb-6">
            No tienes cuentas activas con balance disponible para retirar
          </p>
          <Link
            to="/investment/portfolio"
            className="inline-block px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
          >
            Volver al Portfolio
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex items-center gap-4 mb-8">
        <Link
          to="/investment/portfolio"
          className="p-2 rounded-lg bg-slate-800 border border-slate-700 hover:border-slate-600"
        >
          <ArrowLeft className="w-5 h-5 text-slate-400" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-white">Retirar Fondos</h1>
          <p className="text-slate-400">Solicita un retiro de tus cuentas de inversion</p>
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-8">
        {/* Form Section */}
        <div className="lg:col-span-2">
          <div className="bg-slate-800/50 border border-slate-700 rounded-xl p-6">
            <h2 className="text-lg font-semibold text-white mb-6">
              Solicitud de Retiro
            </h2>
            <WithdrawForm
              accounts={accountOptions}
              onSuccess={handleSuccess}
              onCancel={handleCancel}
            />
          </div>
        </div>

        {/* Info Sidebar */}
        <div className="space-y-6">
          {/* Available Balance */}
          {summary && (
            <div className="bg-slate-800/50 border border-slate-700 rounded-xl p-6">
              <h3 className="text-sm font-medium text-slate-400 mb-4">Disponible para Retiro</h3>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-emerald-500/20 flex items-center justify-center">
                  <Wallet className="w-5 h-5 text-emerald-400" />
                </div>
                <div>
                  <p className="text-sm text-slate-400">Balance Total</p>
                  <p className="text-xl font-bold text-white">
                    ${summary.totalBalance.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Process Info */}
          <div className="bg-slate-800/50 border border-slate-700 rounded-xl p-6">
            <div className="flex items-center gap-2 mb-4">
              <Clock className="w-5 h-5 text-blue-400" />
              <h3 className="text-sm font-medium text-white">Proceso de Retiro</h3>
            </div>
            <ul className="space-y-3 text-sm text-slate-400">
              <li className="flex items-start gap-2">
                <span className="text-blue-400 font-medium">1.</span>
                <span>Solicita tu retiro completando el formulario</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-400 font-medium">2.</span>
                <span>Verifica con tu codigo 2FA</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-400 font-medium">3.</span>
                <span>Nuestro equipo revisa la solicitud (24h)</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-400 font-medium">4.</span>
                <span>Fondos enviados (1-3 dias habiles)</span>
              </li>
            </ul>
          </div>

          {/* Important Notice */}
          <div className="bg-amber-900/20 border border-amber-800/50 rounded-xl p-4">
            <div className="flex items-start gap-3">
              <AlertTriangle className="w-5 h-5 text-amber-400 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-slate-400">
                <p className="font-medium text-amber-400 mb-1">Importante</p>
                <ul className="space-y-1">
                  <li>- Limite diario: $10,000</li>
                  <li>- Minimo por retiro: $50</li>
                  <li>- Se requiere verificacion 2FA</li>
                  <li>- Los retiros estan sujetos a revision</li>
                </ul>
              </div>
            </div>
          </div>

          {/* View History Link */}
          <Link
            to="/investment/withdrawals"
            className="block text-center py-3 px-4 bg-slate-700 hover:bg-slate-600 text-white font-medium rounded-lg transition-colors"
          >
            Ver Historial de Retiros
          </Link>
        </div>
      </div>
    </div>
  );
};

export default Withdraw;
