/**
 * Reports Page
 * Investment analytics and performance reports
 */

import React, { useEffect, useState, useRef } from 'react';
import { Link } from 'react-router-dom';
import { ArrowLeft, TrendingUp, TrendingDown, PieChart, BarChart3, Download, Calendar, AlertCircle, FileText, FileSpreadsheet, ChevronDown } from 'lucide-react';
import investmentService, { AccountSummary, InvestmentAccount } from '../../../services/investment.service';

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

type Period = 'week' | 'month' | '3months' | 'year' | 'all';

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

interface AllocationChartProps {
  accounts: InvestmentAccount[];
}

const AllocationChart: React.FC<AllocationChartProps> = ({ accounts }) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || accounts.length === 0) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const total = accounts.reduce((sum, a) => sum + a.balance, 0);
    if (total === 0) return;

    const colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = Math.min(centerX, centerY) - 20;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    let startAngle = -Math.PI / 2;
    accounts.forEach((account, i) => {
      const sliceAngle = (account.balance / total) * 2 * Math.PI;

      ctx.beginPath();
      ctx.moveTo(centerX, centerY);
      ctx.arc(centerX, centerY, radius, startAngle, startAngle + sliceAngle);
      ctx.closePath();
      ctx.fillStyle = colors[i % colors.length];
      ctx.fill();

      startAngle += sliceAngle;
    });

    // Inner circle (donut)
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius * 0.6, 0, 2 * Math.PI);
    ctx.fillStyle = '#1F2937';
    ctx.fill();

    // Center text
    ctx.fillStyle = '#FFFFFF';
    ctx.font = 'bold 24px system-ui';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(`$${(total / 1000).toFixed(1)}k`, centerX, centerY);
  }, [accounts]);

  const colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];
  const total = accounts.reduce((sum, a) => sum + a.balance, 0);

  return (
    <div className="flex items-center gap-6">
      <canvas ref={canvasRef} width={200} height={200} />
      <div className="space-y-2">
        {accounts.map((account, i) => (
          <div key={account.id} className="flex items-center gap-2">
            <div
              className="w-3 h-3 rounded-full"
              style={{ backgroundColor: colors[i % colors.length] }}
            />
            <span className="text-sm text-gray-600 dark:text-gray-400">
              {account.product.name}
            </span>
            <span className="text-sm font-medium text-gray-900 dark:text-white">
              {total > 0 ? ((account.balance / total) * 100).toFixed(1) : 0}%
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

interface PerformanceBarChartProps {
  data: { label: string; value: number }[];
}

const PerformanceBarChart: React.FC<PerformanceBarChartProps> = ({ data }) => {
  const maxValue = Math.max(...data.map(d => Math.abs(d.value)), 1);

  return (
    <div className="space-y-3">
      {data.map((item, i) => (
        <div key={i}>
          <div className="flex justify-between text-sm mb-1">
            <span className="text-gray-600 dark:text-gray-400">{item.label}</span>
            <span className={`font-medium ${item.value >= 0 ? 'text-green-500' : 'text-red-500'}`}>
              {item.value >= 0 ? '+' : ''}{item.value.toFixed(2)}%
            </span>
          </div>
          <div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full ${item.value >= 0 ? 'bg-green-500' : 'bg-red-500'}`}
              style={{ width: `${(Math.abs(item.value) / maxValue) * 100}%` }}
            />
          </div>
        </div>
      ))}
    </div>
  );
};

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

export const Reports: React.FC = () => {
  const [summary, setSummary] = useState<AccountSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [period, setPeriod] = useState<Period>('month');

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

  const loadData = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await investmentService.getAccountSummary();
      setSummary(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error loading reports');
    } finally {
      setLoading(false);
    }
  };

  const periodOptions: { value: Period; label: string }[] = [
    { value: 'week', label: '7 días' },
    { value: 'month', label: '30 días' },
    { value: '3months', label: '3 meses' },
    { value: 'year', label: '1 año' },
    { value: 'all', label: 'Todo' },
  ];

  const performanceByAccount = summary?.accounts.map(account => {
    const totalReturn = account.balance - account.totalDeposited + account.totalWithdrawn;
    const returnPercent = account.totalDeposited > 0 ? (totalReturn / account.totalDeposited) * 100 : 0;
    return {
      label: account.product.name,
      value: returnPercent,
    };
  }) || [];

  const [showExportMenu, setShowExportMenu] = useState(false);

  const handleExportCSV = () => {
    if (!summary) return;

    const headers = ['Cuenta', 'Balance', 'Invertido', 'Retirado', 'Ganancias', 'Retorno %'];
    const rows = summary.accounts.map(a => {
      const totalReturn = a.balance - a.totalDeposited + a.totalWithdrawn;
      const returnPercent = a.totalDeposited > 0 ? (totalReturn / a.totalDeposited) * 100 : 0;
      return [
        a.product.name,
        a.balance.toFixed(2),
        a.totalDeposited.toFixed(2),
        a.totalWithdrawn.toFixed(2),
        a.totalEarnings.toFixed(2),
        returnPercent.toFixed(2) + '%',
      ];
    });

    const summaryRow = [
      'TOTAL',
      summary.totalBalance.toFixed(2),
      summary.totalDeposited.toFixed(2),
      summary.totalWithdrawn.toFixed(2),
      summary.overallReturn.toFixed(2),
      summary.overallReturnPercent.toFixed(2) + '%',
    ];

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.join(',')),
      '',
      summaryRow.join(','),
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `investment-report-${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
    URL.revokeObjectURL(url);
    setShowExportMenu(false);
  };

  const handleExportPDF = () => {
    if (!summary) return;

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    const htmlContent = `
      <!DOCTYPE html>
      <html>
      <head>
        <title>Investment Report - ${new Date().toLocaleDateString()}</title>
        <style>
          body { font-family: Arial, sans-serif; padding: 40px; color: #333; }
          h1 { color: #1e40af; border-bottom: 2px solid #1e40af; padding-bottom: 10px; }
          .summary { display: flex; gap: 20px; margin: 20px 0; }
          .summary-card { background: #f3f4f6; padding: 15px; border-radius: 8px; flex: 1; }
          .summary-card h3 { margin: 0 0 5px 0; font-size: 12px; color: #666; }
          .summary-card p { margin: 0; font-size: 20px; font-weight: bold; }
          .positive { color: #10b981; }
          .negative { color: #ef4444; }
          table { width: 100%; border-collapse: collapse; margin-top: 20px; }
          th, td { padding: 12px; text-align: left; border-bottom: 1px solid #e5e7eb; }
          th { background: #f9fafb; font-weight: 600; }
          .right { text-align: right; }
          .footer { margin-top: 40px; font-size: 12px; color: #999; }
        </style>
      </head>
      <body>
        <h1>Investment Report</h1>
        <p>Generated: ${new Date().toLocaleString()}</p>

        <div class="summary">
          <div class="summary-card">
            <h3>Total Balance</h3>
            <p>$${summary.totalBalance.toLocaleString(undefined, { minimumFractionDigits: 2 })}</p>
          </div>
          <div class="summary-card">
            <h3>Total Invested</h3>
            <p>$${summary.totalDeposited.toLocaleString(undefined, { minimumFractionDigits: 2 })}</p>
          </div>
          <div class="summary-card">
            <h3>Overall Return</h3>
            <p class="${summary.overallReturn >= 0 ? 'positive' : 'negative'}">
              ${summary.overallReturn >= 0 ? '+' : ''}$${Math.abs(summary.overallReturn).toLocaleString(undefined, { minimumFractionDigits: 2 })}
              (${summary.overallReturnPercent >= 0 ? '+' : ''}${summary.overallReturnPercent.toFixed(2)}%)
            </p>
          </div>
        </div>

        <h2>Account Details</h2>
        <table>
          <thead>
            <tr>
              <th>Account</th>
              <th class="right">Balance</th>
              <th class="right">Invested</th>
              <th class="right">Earnings</th>
              <th class="right">Return</th>
            </tr>
          </thead>
          <tbody>
            ${summary.accounts.map(a => {
              const totalReturn = a.balance - a.totalDeposited + a.totalWithdrawn;
              const returnPercent = a.totalDeposited > 0 ? (totalReturn / a.totalDeposited) * 100 : 0;
              return `
                <tr>
                  <td>${a.product.name}</td>
                  <td class="right">$${a.balance.toLocaleString(undefined, { minimumFractionDigits: 2 })}</td>
                  <td class="right">$${a.totalDeposited.toLocaleString(undefined, { minimumFractionDigits: 2 })}</td>
                  <td class="right ${totalReturn >= 0 ? 'positive' : 'negative'}">
                    ${totalReturn >= 0 ? '+' : ''}$${Math.abs(totalReturn).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                  </td>
                  <td class="right ${returnPercent >= 0 ? 'positive' : 'negative'}">
                    ${returnPercent >= 0 ? '+' : ''}${returnPercent.toFixed(2)}%
                  </td>
                </tr>
              `;
            }).join('')}
          </tbody>
        </table>

        <div class="footer">
          <p>This report is for informational purposes only. Past performance does not guarantee future results.</p>
          <p>Trading Platform - Investment Reports</p>
        </div>
      </body>
      </html>
    `;

    printWindow.document.write(htmlContent);
    printWindow.document.close();
    printWindow.print();
    setShowExportMenu(false);
  };

  const handleExportJSON = () => {
    if (!summary) return;

    const reportData = {
      generatedAt: new Date().toISOString(),
      summary: {
        totalBalance: summary.totalBalance,
        totalDeposited: summary.totalDeposited,
        totalWithdrawn: summary.totalWithdrawn,
        overallReturn: summary.overallReturn,
        overallReturnPercent: summary.overallReturnPercent,
      },
      accounts: summary.accounts.map(a => ({
        name: a.product.name,
        balance: a.balance,
        deposited: a.totalDeposited,
        withdrawn: a.totalWithdrawn,
        earnings: a.totalEarnings,
      })),
    };

    const blob = new Blob([JSON.stringify(reportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `investment-report-${new Date().toISOString().split('T')[0]}.json`;
    link.click();
    URL.revokeObjectURL(url);
    setShowExportMenu(false);
  };

  if (loading) {
    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 (error) {
    return (
      <div className="max-w-4xl 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" />
          <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>
      </div>
    );
  }

  if (!summary) return null;

  return (
    <div className="max-w-6xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div className="flex items-center gap-4">
          <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">
              Reportes
            </h1>
            <p className="text-gray-500 dark:text-gray-400">
              Análisis de rendimiento de inversiones
            </p>
          </div>
        </div>
        <div className="relative">
          <button
            onClick={() => setShowExportMenu(!showExportMenu)}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Download className="w-4 h-4" />
            Exportar
            <ChevronDown className="w-4 h-4" />
          </button>
          {showExportMenu && (
            <div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 py-1 z-10">
              <button
                onClick={handleExportPDF}
                className="w-full flex items-center gap-3 px-4 py-2 text-left text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                <FileText className="w-4 h-4 text-red-500" />
                Exportar PDF
              </button>
              <button
                onClick={handleExportCSV}
                className="w-full flex items-center gap-3 px-4 py-2 text-left text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                <FileSpreadsheet className="w-4 h-4 text-green-500" />
                Exportar CSV
              </button>
              <button
                onClick={handleExportJSON}
                className="w-full flex items-center gap-3 px-4 py-2 text-left text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                <Download className="w-4 h-4 text-blue-500" />
                Exportar JSON
              </button>
            </div>
          )}
        </div>
      </div>

      {/* Period Filter */}
      <div className="flex items-center gap-2 mb-8 overflow-x-auto pb-2">
        <Calendar className="w-4 h-4 text-gray-500 flex-shrink-0" />
        {periodOptions.map(option => (
          <button
            key={option.value}
            onClick={() => setPeriod(option.value)}
            className={`px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${
              period === 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>

      {/* Summary Cards */}
      <div className="grid md:grid-cols-4 gap-4 mb-8">
        <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
          <div className="flex items-center justify-between mb-2">
            <span className="text-gray-500 dark:text-gray-400 text-sm">Valor Total</span>
            <TrendingUp className="w-5 h-5 text-blue-500" />
          </div>
          <p className="text-2xl font-bold text-gray-900 dark:text-white">
            ${summary.totalBalance.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </p>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
          <div className="flex items-center justify-between mb-2">
            <span className="text-gray-500 dark:text-gray-400 text-sm">Total Invertido</span>
            <BarChart3 className="w-5 h-5 text-purple-500" />
          </div>
          <p className="text-2xl font-bold text-gray-900 dark:text-white">
            ${summary.totalDeposited.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </p>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
          <div className="flex items-center justify-between mb-2">
            <span className="text-gray-500 dark:text-gray-400 text-sm">Ganancia/Pérdida</span>
            {summary.overallReturn >= 0 ? (
              <TrendingUp className="w-5 h-5 text-green-500" />
            ) : (
              <TrendingDown className="w-5 h-5 text-red-500" />
            )}
          </div>
          <p className={`text-2xl font-bold ${summary.overallReturn >= 0 ? 'text-green-500' : 'text-red-500'}`}>
            {summary.overallReturn >= 0 ? '+' : ''}${Math.abs(summary.overallReturn).toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </p>
          <p className={`text-sm ${summary.overallReturnPercent >= 0 ? 'text-green-500' : 'text-red-500'}`}>
            {summary.overallReturnPercent >= 0 ? '+' : ''}{summary.overallReturnPercent.toFixed(2)}%
          </p>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
          <div className="flex items-center justify-between mb-2">
            <span className="text-gray-500 dark:text-gray-400 text-sm">Total Retirado</span>
            <PieChart className="w-5 h-5 text-orange-500" />
          </div>
          <p className="text-2xl font-bold text-gray-900 dark:text-white">
            ${summary.totalWithdrawn.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </p>
        </div>
      </div>

      {/* Charts */}
      <div className="grid md:grid-cols-2 gap-6 mb-8">
        {/* Allocation Chart */}
        <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
          <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-6">
            Distribución del Portfolio
          </h3>
          {summary.accounts.length > 0 ? (
            <AllocationChart accounts={summary.accounts} />
          ) : (
            <p className="text-gray-500 dark:text-gray-400 text-center py-8">
              No hay cuentas para mostrar
            </p>
          )}
        </div>

        {/* Performance by Account */}
        <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
          <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-6">
            Rendimiento por Cuenta
          </h3>
          {performanceByAccount.length > 0 ? (
            <PerformanceBarChart data={performanceByAccount} />
          ) : (
            <p className="text-gray-500 dark:text-gray-400 text-center py-8">
              No hay datos de rendimiento
            </p>
          )}
        </div>
      </div>

      {/* Account Details Table */}
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg overflow-hidden">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <h3 className="text-lg font-bold text-gray-900 dark:text-white">
            Detalle por Cuenta
          </h3>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-900/50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Cuenta
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Balance
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Invertido
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Ganancias
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Retorno
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
              {summary.accounts.map(account => {
                const totalReturn = account.balance - account.totalDeposited + account.totalWithdrawn;
                const returnPercent = account.totalDeposited > 0 ? (totalReturn / account.totalDeposited) * 100 : 0;
                return (
                  <tr key={account.id} className="hover:bg-gray-50 dark:hover:bg-gray-900/30">
                    <td className="px-6 py-4">
                      <Link
                        to={`/investment/accounts/${account.id}`}
                        className="font-medium text-blue-600 hover:text-blue-700"
                      >
                        {account.product.name}
                      </Link>
                      <p className="text-xs text-gray-500 dark:text-gray-400 capitalize">
                        {account.product.riskProfile}
                      </p>
                    </td>
                    <td className="px-6 py-4 text-right font-medium text-gray-900 dark:text-white">
                      ${account.balance.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                    </td>
                    <td className="px-6 py-4 text-right text-gray-600 dark:text-gray-400">
                      ${account.totalDeposited.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                    </td>
                    <td className={`px-6 py-4 text-right font-medium ${totalReturn >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                      {totalReturn >= 0 ? '+' : ''}${Math.abs(totalReturn).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                    </td>
                    <td className={`px-6 py-4 text-right font-medium ${returnPercent >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                      {returnPercent >= 0 ? '+' : ''}{returnPercent.toFixed(2)}%
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default Reports;
