/**
 * Withdrawals Page
 * Lists all user withdrawal requests across all investment accounts
 */

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { ArrowLeft, Clock, CheckCircle, XCircle, AlertCircle, Filter } from 'lucide-react';
import investmentService, { Withdrawal } from '../../../services/investment.service';

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

type StatusFilter = 'all' | 'pending' | 'approved' | 'processing' | 'completed' | 'rejected';

// ============================================================================
// Subcomponents
// ============================================================================

interface WithdrawalCardProps {
  withdrawal: Withdrawal;
}

const WithdrawalCard: React.FC<WithdrawalCardProps> = ({ withdrawal }) => {
  const statusConfig = {
    pending: {
      icon: <Clock className="w-5 h-5" />,
      color: 'text-yellow-500',
      bg: 'bg-yellow-100 dark:bg-yellow-900/30',
      label: 'Pendiente',
    },
    approved: {
      icon: <CheckCircle className="w-5 h-5" />,
      color: 'text-blue-500',
      bg: 'bg-blue-100 dark:bg-blue-900/30',
      label: 'Aprobado',
    },
    processing: {
      icon: <Clock className="w-5 h-5" />,
      color: 'text-purple-500',
      bg: 'bg-purple-100 dark:bg-purple-900/30',
      label: 'Procesando',
    },
    completed: {
      icon: <CheckCircle className="w-5 h-5" />,
      color: 'text-green-500',
      bg: 'bg-green-100 dark:bg-green-900/30',
      label: 'Completado',
    },
    rejected: {
      icon: <XCircle className="w-5 h-5" />,
      color: 'text-red-500',
      bg: 'bg-red-100 dark:bg-red-900/30',
      label: 'Rechazado',
    },
  };

  const config = statusConfig[withdrawal.status];

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
      <div className="flex items-start justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${config.bg} ${config.color}`}>
            {config.icon}
          </div>
          <div>
            <p className="font-bold text-2xl text-gray-900 dark:text-white">
              ${withdrawal.amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
            </p>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {new Date(withdrawal.requestedAt).toLocaleDateString()} {new Date(withdrawal.requestedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
            </p>
          </div>
        </div>
        <span className={`px-3 py-1 rounded-full text-sm font-medium ${config.bg} ${config.color}`}>
          {config.label}
        </span>
      </div>

      <div className="space-y-2 text-sm">
        {withdrawal.bankInfo && (
          <div className="flex justify-between">
            <span className="text-gray-500 dark:text-gray-400">Destino</span>
            <span className="text-gray-900 dark:text-white">
              {withdrawal.bankInfo.bankName} ****{withdrawal.bankInfo.accountLast4}
            </span>
          </div>
        )}
        {withdrawal.cryptoInfo && (
          <div className="flex justify-between">
            <span className="text-gray-500 dark:text-gray-400">Destino</span>
            <span className="text-gray-900 dark:text-white font-mono">
              {withdrawal.cryptoInfo.network}: ...{withdrawal.cryptoInfo.addressLast8}
            </span>
          </div>
        )}
        {withdrawal.processedAt && (
          <div className="flex justify-between">
            <span className="text-gray-500 dark:text-gray-400">Procesado</span>
            <span className="text-gray-900 dark:text-white">
              {new Date(withdrawal.processedAt).toLocaleDateString()}
            </span>
          </div>
        )}
        {withdrawal.rejectionReason && (
          <div className="mt-3 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
            <p className="text-sm text-red-600 dark:text-red-400">
              <strong>Motivo:</strong> {withdrawal.rejectionReason}
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

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

export const Withdrawals: React.FC = () => {
  const [withdrawals, setWithdrawals] = useState<Withdrawal[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');

  useEffect(() => {
    loadWithdrawals();
  }, [statusFilter]);

  const loadWithdrawals = async () => {
    try {
      setLoading(true);
      setError(null);
      const status = statusFilter === 'all' ? undefined : statusFilter;
      const data = await investmentService.getWithdrawals(status);
      setWithdrawals(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error loading withdrawals');
    } finally {
      setLoading(false);
    }
  };

  const stats = {
    total: withdrawals.length,
    pending: withdrawals.filter(w => ['pending', 'approved', 'processing'].includes(w.status)).length,
    completed: withdrawals.filter(w => w.status === 'completed').length,
    totalAmount: withdrawals
      .filter(w => w.status === 'completed')
      .reduce((sum, w) => sum + w.amount, 0),
  };

  const filterOptions: { value: StatusFilter; label: string }[] = [
    { value: 'all', label: 'Todos' },
    { value: 'pending', label: 'Pendientes' },
    { value: 'processing', label: 'En Proceso' },
    { value: 'completed', label: 'Completados' },
    { value: 'rejected', label: 'Rechazados' },
  ];

  return (
    <div className="max-w-6xl 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-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700"
        >
          <ArrowLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
            Mis Retiros
          </h1>
          <p className="text-gray-500 dark:text-gray-400">
            Historial de solicitudes de retiro
          </p>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
          <p className="text-sm text-gray-500 dark:text-gray-400">Total Solicitudes</p>
          <p className="text-2xl font-bold text-gray-900 dark:text-white">{stats.total}</p>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
          <p className="text-sm text-gray-500 dark:text-gray-400">En Proceso</p>
          <p className="text-2xl font-bold text-yellow-500">{stats.pending}</p>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
          <p className="text-sm text-gray-500 dark:text-gray-400">Completados</p>
          <p className="text-2xl font-bold text-green-500">{stats.completed}</p>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
          <p className="text-sm text-gray-500 dark:text-gray-400">Total Retirado</p>
          <p className="text-2xl font-bold text-gray-900 dark:text-white">
            ${stats.totalAmount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-2 mb-6 overflow-x-auto pb-2">
        <Filter className="w-4 h-4 text-gray-500 flex-shrink-0" />
        {filterOptions.map(option => (
          <button
            key={option.value}
            onClick={() => setStatusFilter(option.value)}
            className={`px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${
              statusFilter === option.value
                ? 'bg-blue-600 text-white'
                : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
            }`}
          >
            {option.label}
          </button>
        ))}
      </div>

      {/* Content */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>
      ) : error ? (
        <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" />
          <p className="text-red-600 dark:text-red-400">{error}</p>
          <button
            onClick={loadWithdrawals}
            className="mt-4 px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
          >
            Reintentar
          </button>
        </div>
      ) : withdrawals.length === 0 ? (
        <div className="text-center py-16 bg-white dark:bg-gray-800 rounded-xl shadow-lg">
          <span className="text-6xl mb-4 block">💸</span>
          <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
            No hay retiros
          </h3>
          <p className="text-gray-600 dark:text-gray-400 mb-6">
            {statusFilter === 'all'
              ? 'Aún no has solicitado ningún retiro'
              : `No hay retiros con estado "${filterOptions.find(f => f.value === statusFilter)?.label}"`}
          </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"
          >
            Ir al Portfolio
          </Link>
        </div>
      ) : (
        <div className="grid md:grid-cols-2 gap-4">
          {withdrawals.map(withdrawal => (
            <WithdrawalCard key={withdrawal.id} withdrawal={withdrawal} />
          ))}
        </div>
      )}
    </div>
  );
};

export default Withdrawals;
