/**
 * Transactions Page
 * Global transaction history across all investment accounts
 */

import React, { useEffect, useState, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { ArrowLeft, ArrowDownCircle, ArrowUpCircle, Gift, Receipt, RefreshCw, Filter, Calendar, AlertCircle, ChevronLeft, ChevronRight } from 'lucide-react';
import investmentService, { Transaction, InvestmentAccount } from '../../../services/investment.service';

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

type TransactionType = 'all' | 'deposit' | 'withdrawal' | 'distribution' | 'fee';

interface TransactionWithAccount extends Transaction {
  accountName?: string;
}

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

interface TransactionRowProps {
  transaction: TransactionWithAccount;
}

const TransactionRow: React.FC<TransactionRowProps> = ({ transaction }) => {
  const typeConfig = {
    deposit: {
      icon: <ArrowDownCircle className="w-5 h-5" />,
      color: 'text-green-500',
      bg: 'bg-green-100 dark:bg-green-900/30',
      label: 'Depósito',
      sign: '+',
    },
    withdrawal: {
      icon: <ArrowUpCircle className="w-5 h-5" />,
      color: 'text-red-500',
      bg: 'bg-red-100 dark:bg-red-900/30',
      label: 'Retiro',
      sign: '-',
    },
    distribution: {
      icon: <Gift className="w-5 h-5" />,
      color: 'text-blue-500',
      bg: 'bg-blue-100 dark:bg-blue-900/30',
      label: 'Distribución',
      sign: '+',
    },
    fee: {
      icon: <Receipt className="w-5 h-5" />,
      color: 'text-orange-500',
      bg: 'bg-orange-100 dark:bg-orange-900/30',
      label: 'Comisión',
      sign: '-',
    },
    adjustment: {
      icon: <RefreshCw className="w-5 h-5" />,
      color: 'text-purple-500',
      bg: 'bg-purple-100 dark:bg-purple-900/30',
      label: 'Ajuste',
      sign: '',
    },
  };

  const config = typeConfig[transaction.type] || typeConfig.adjustment;
  const isCredit = ['deposit', 'distribution'].includes(transaction.type);

  const statusColors: Record<string, string> = {
    pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    completed: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    failed: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    cancelled: 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400',
  };

  return (
    <div className="flex items-center justify-between py-4 px-4 bg-white dark:bg-gray-800 rounded-lg shadow mb-2 hover:shadow-md transition-shadow">
      <div className="flex items-center gap-4">
        <div className={`p-2 rounded-lg ${config.bg} ${config.color}`}>
          {config.icon}
        </div>
        <div>
          <div className="flex items-center gap-2">
            <p className="font-medium text-gray-900 dark:text-white">{config.label}</p>
            <span className={`text-xs px-2 py-0.5 rounded-full ${statusColors[transaction.status]}`}>
              {transaction.status}
            </span>
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            {new Date(transaction.createdAt).toLocaleDateString()} - {transaction.description || transaction.accountName || 'Sin descripción'}
          </p>
        </div>
      </div>
      <div className="text-right">
        <p className={`font-bold text-lg ${isCredit ? 'text-green-500' : 'text-red-500'}`}>
          {config.sign}${Math.abs(transaction.amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}
        </p>
        <p className="text-xs text-gray-500 dark:text-gray-400">
          Balance: ${transaction.balanceAfter.toLocaleString(undefined, { minimumFractionDigits: 2 })}
        </p>
      </div>
    </div>
  );
};

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

const ITEMS_PER_PAGE = 10;

export const Transactions: React.FC = () => {
  const [transactions, setTransactions] = useState<TransactionWithAccount[]>([]);
  const [accounts, setAccounts] = useState<InvestmentAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [typeFilter, setTypeFilter] = useState<TransactionType>('all');
  const [selectedAccount, setSelectedAccount] = useState<string>('all');
  const [dateRange, setDateRange] = useState<'week' | 'month' | '3months' | 'all'>('month');
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    if (accounts.length > 0) {
      loadTransactions();
    }
  }, [typeFilter, selectedAccount, accounts]);

  const loadData = async () => {
    try {
      setLoading(true);
      setError(null);
      const accountsData = await investmentService.getUserAccounts();
      setAccounts(accountsData);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error loading accounts');
    } finally {
      setLoading(false);
    }
  };

  const loadTransactions = async () => {
    try {
      setLoading(true);
      const allTransactions: TransactionWithAccount[] = [];

      const accountsToFetch = selectedAccount === 'all'
        ? accounts
        : accounts.filter(a => a.id === selectedAccount);

      for (const account of accountsToFetch) {
        const { transactions: txs } = await investmentService.getTransactions(account.id, {
          type: typeFilter === 'all' ? undefined : typeFilter,
          limit: 50,
        });
        allTransactions.push(
          ...txs.map(tx => ({ ...tx, accountName: account.product.name }))
        );
      }

      // Sort by date descending
      allTransactions.sort((a, b) =>
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      );

      setTransactions(allTransactions);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error loading transactions');
    } finally {
      setLoading(false);
    }
  };

  const typeOptions: { value: TransactionType; label: string }[] = [
    { value: 'all', label: 'Todos' },
    { value: 'deposit', label: 'Depósitos' },
    { value: 'withdrawal', label: 'Retiros' },
    { value: 'distribution', label: 'Distribuciones' },
    { value: 'fee', label: 'Comisiones' },
  ];

  const stats = {
    deposits: transactions.filter(t => t.type === 'deposit').reduce((sum, t) => sum + t.amount, 0),
    withdrawals: transactions.filter(t => t.type === 'withdrawal').reduce((sum, t) => sum + t.amount, 0),
    distributions: transactions.filter(t => t.type === 'distribution').reduce((sum, t) => sum + t.amount, 0),
    fees: transactions.filter(t => t.type === 'fee').reduce((sum, t) => sum + t.amount, 0),
  };

  const totalPages = Math.ceil(transactions.length / ITEMS_PER_PAGE);
  const paginatedTransactions = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    return transactions.slice(startIndex, startIndex + ITEMS_PER_PAGE);
  }, [transactions, currentPage]);

  useEffect(() => {
    setCurrentPage(1);
  }, [typeFilter, selectedAccount]);

  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">
            Transacciones
          </h1>
          <p className="text-gray-500 dark:text-gray-400">
            Historial completo de movimientos
          </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">Depósitos</p>
          <p className="text-xl font-bold text-green-500">
            +${stats.deposits.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </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">Retiros</p>
          <p className="text-xl font-bold text-red-500">
            -${stats.withdrawals.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </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">Distribuciones</p>
          <p className="text-xl font-bold text-blue-500">
            +${stats.distributions.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </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">Comisiones</p>
          <p className="text-xl font-bold text-orange-500">
            -${stats.fees.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow mb-6">
        <div className="flex flex-wrap items-center gap-4">
          {/* Type Filter */}
          <div className="flex items-center gap-2">
            <Filter className="w-4 h-4 text-gray-500" />
            <div className="flex gap-1">
              {typeOptions.map(option => (
                <button
                  key={option.value}
                  onClick={() => setTypeFilter(option.value)}
                  className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                    typeFilter === option.value
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                  }`}
                >
                  {option.label}
                </button>
              ))}
            </div>
          </div>

          {/* Account Filter */}
          {accounts.length > 1 && (
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-500">Cuenta:</span>
              <select
                value={selectedAccount}
                onChange={(e) => setSelectedAccount(e.target.value)}
                className="px-3 py-1.5 bg-gray-100 dark:bg-gray-700 rounded-lg text-sm text-gray-900 dark:text-white border-0 focus:ring-2 focus:ring-blue-500"
              >
                <option value="all">Todas las cuentas</option>
                {accounts.map(account => (
                  <option key={account.id} value={account.id}>
                    {account.product.name}
                  </option>
                ))}
              </select>
            </div>
          )}
        </div>
      </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={loadData}
            className="mt-4 px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
          >
            Reintentar
          </button>
        </div>
      ) : transactions.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 transacciones
          </h3>
          <p className="text-gray-600 dark:text-gray-400 mb-6">
            {typeFilter === 'all'
              ? 'Aún no tienes transacciones registradas'
              : `No hay transacciones de tipo "${typeOptions.find(f => f.value === typeFilter)?.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>
          {paginatedTransactions.map(transaction => (
            <TransactionRow key={transaction.id} transaction={transaction} />
          ))}

          {totalPages > 1 && (
            <div className="flex items-center justify-between mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
              <div className="text-sm text-gray-500 dark:text-gray-400">
                Mostrando {((currentPage - 1) * ITEMS_PER_PAGE) + 1} - {Math.min(currentPage * ITEMS_PER_PAGE, transactions.length)} de {transactions.length} transacciones
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                  disabled={currentPage === 1}
                  className="p-2 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <ChevronLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
                </button>
                <div className="flex items-center gap-1">
                  {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                    let pageNum: number;
                    if (totalPages <= 5) {
                      pageNum = i + 1;
                    } else if (currentPage <= 3) {
                      pageNum = i + 1;
                    } else if (currentPage >= totalPages - 2) {
                      pageNum = totalPages - 4 + i;
                    } else {
                      pageNum = currentPage - 2 + i;
                    }
                    return (
                      <button
                        key={pageNum}
                        onClick={() => setCurrentPage(pageNum)}
                        className={`w-10 h-10 rounded-lg text-sm font-medium transition-colors ${
                          currentPage === pageNum
                            ? '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'
                        }`}
                      >
                        {pageNum}
                      </button>
                    );
                  })}
                </div>
                <button
                  onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                  disabled={currentPage === totalPages}
                  className="p-2 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <ChevronRight className="w-5 h-5 text-gray-600 dark:text-gray-400" />
                </button>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default Transactions;
