/**
 * Deposit Page
 * Standalone page for depositing funds to 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, TrendingUp, Shield } from 'lucide-react';
import { DepositForm } from '../components/DepositForm';
import { useInvestmentAccounts, useAccountSummary } from '../hooks';

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

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

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

export const Deposit: 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 [accountOptions, setAccountOptions] = useState<AccountOption[]>([]);

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

  const handleSuccess = (transactionId: string) => {
    // Navigate to portfolio with success message
    navigate('/investment/portfolio', {
      state: { depositSuccess: true, transactionId },
    });
  };

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

  if (loadingAccounts) {
    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>
    );
  }

  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">Depositar Fondos</h1>
            <p className="text-slate-400">Agrega fondos a 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 tienes cuentas activas
          </h3>
          <p className="text-slate-400 mb-6">
            Primero necesitas abrir una cuenta de inversion para poder depositar
          </p>
          <Link
            to="/investment/products"
            className="inline-block px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
          >
            Ver Productos de Inversion
          </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">Depositar Fondos</h1>
          <p className="text-slate-400">Agrega fondos a 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">
              Detalles del Deposito
            </h2>
            <DepositForm
              accounts={accountOptions}
              onSuccess={handleSuccess}
              onCancel={handleCancel}
            />
          </div>
        </div>

        {/* Info Sidebar */}
        <div className="space-y-6">
          {/* Portfolio Summary */}
          {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">Tu Portfolio</h3>
              <div className="space-y-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center">
                    <Wallet className="w-5 h-5 text-blue-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 className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-lg bg-emerald-500/20 flex items-center justify-center">
                    <TrendingUp className="w-5 h-5 text-emerald-400" />
                  </div>
                  <div>
                    <p className="text-sm text-slate-400">Rendimiento</p>
                    <p className={`text-lg font-bold ${summary.overallReturnPercent >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
                      {summary.overallReturnPercent >= 0 ? '+' : ''}{summary.overallReturnPercent.toFixed(2)}%
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Security Info */}
          <div className="bg-slate-800/50 border border-slate-700 rounded-xl p-6">
            <div className="flex items-center gap-2 mb-4">
              <Shield className="w-5 h-5 text-blue-400" />
              <h3 className="text-sm font-medium text-white">Pago Seguro</h3>
            </div>
            <ul className="space-y-3 text-sm text-slate-400">
              <li className="flex items-start gap-2">
                <span className="text-emerald-400">✓</span>
                <span>Procesado por Stripe, lider en pagos seguros</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-emerald-400">✓</span>
                <span>Encriptacion SSL de 256 bits</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-emerald-400">✓</span>
                <span>No almacenamos datos de tarjeta</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-emerald-400">✓</span>
                <span>Fondos acreditados al instante</span>
              </li>
            </ul>
          </div>

          {/* Help */}
          <div className="bg-amber-900/20 border border-amber-800/50 rounded-xl p-4">
            <p className="text-sm text-amber-400">
              <strong>Nota:</strong> Los depositos se acreditan inmediatamente despues
              de la confirmacion del pago. Si tienes problemas, contacta a soporte.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Deposit;
