import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { reportService, categoryService } from '../services/api';
import useFormatters from '../hooks/useFormatters';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  LineElement,
  PointElement,
  ArcElement,
  Title,
  Tooltip,
  Legend,
  Filler,
} from 'chart.js';
import { Bar, Line, Doughnut, Pie } from 'react-chartjs-2';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  LineElement,
  PointElement,
  ArcElement,
  Title,
  Tooltip,
  Legend,
  Filler
);

const Reports = () => {
  const { t } = useTranslation();
  const { currency } = useFormatters();
  
  const [activeTab, setActiveTab] = useState('summary');
  const [loading, setLoading] = useState(true);
  const [year, setYear] = useState(new Date().getFullYear());
  const [months, setMonths] = useState(12);
  
  // Data states
  const [summary, setSummary] = useState(null);
  const [categoryData, setCategoryData] = useState(null);
  const [evolutionData, setEvolutionData] = useState(null);
  const [dayOfWeekData, setDayOfWeekData] = useState(null);
  const [topExpenses, setTopExpenses] = useState(null);
  const [projection, setProjection] = useState(null);
  const [comparison, setComparison] = useState(null);

  // Load data based on active tab
  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      switch (activeTab) {
        case 'summary':
          const summaryRes = await reportService.getSummary({ year });
          setSummary(summaryRes);
          break;
        case 'category':
          const catRes = await reportService.getByCategory({ type: 'debit' });
          setCategoryData(catRes);
          break;
        case 'evolution':
          const evoRes = await reportService.getMonthlyEvolution({ months });
          setEvolutionData(evoRes);
          break;
        case 'dayOfWeek':
          const dowRes = await reportService.getByDayOfWeek({ months: 6 });
          setDayOfWeekData(dowRes);
          break;
        case 'topExpenses':
          const topRes = await reportService.getTopExpenses({ limit: 20 });
          setTopExpenses(topRes);
          break;
        case 'projection':
          const projRes = await reportService.getProjection();
          setProjection(projRes);
          break;
        case 'comparison':
          const compRes = await reportService.comparePeriods();
          setComparison(compRes);
          break;
      }
    } catch (error) {
      console.error('Error loading report data:', error);
    } finally {
      setLoading(false);
    }
  }, [activeTab, year, months]);

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

  const tabs = [
    { id: 'summary', label: t('reports.summary'), icon: 'bi-clipboard-data' },
    { id: 'category', label: t('reports.byCategory'), icon: 'bi-pie-chart' },
    { id: 'evolution', label: t('reports.monthlyEvolution'), icon: 'bi-graph-up' },
    { id: 'comparison', label: t('reports.comparison'), icon: 'bi-arrow-left-right' },
    { id: 'topExpenses', label: t('reports.topExpenses'), icon: 'bi-sort-down' },
    { id: 'projection', label: t('reports.projection'), icon: 'bi-lightning' },
    { id: 'dayOfWeek', label: 'Por día', icon: 'bi-calendar-week' },
  ];

  // Chart options
  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        labels: { color: '#94a3b8' }
      }
    },
    scales: {
      x: {
        ticks: { color: '#94a3b8' },
        grid: { color: 'rgba(148, 163, 184, 0.1)' }
      },
      y: {
        ticks: { color: '#94a3b8' },
        grid: { color: 'rgba(148, 163, 184, 0.1)' }
      }
    }
  };

  const doughnutOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: 'right',
        labels: { color: '#94a3b8', padding: 15, font: { size: 11 } }
      }
    }
  };

  // Render Summary Tab
  const renderSummary = () => {
    if (!summary) return null;

    return (
      <div className="row g-4">
        {/* Year Selector */}
        <div className="col-12">
          <div className="d-flex gap-2 mb-3">
            {[2024, 2025].map(y => (
              <button
                key={y}
                className={`btn btn-sm ${year === y ? 'btn-primary' : 'btn-outline-secondary'}`}
                onClick={() => setYear(y)}
              >
                {y}
              </button>
            ))}
          </div>
        </div>

        {/* Summary Cards */}
        <div className="col-md-4">
          <div className="card border-0 h-100" style={{ background: 'linear-gradient(135deg, #059669 0%, #047857 100%)' }}>
            <div className="card-body text-white">
              <h6 className="opacity-75">{t('reports.income')} {year}</h6>
              <h3 className="mb-2">{currency(summary.current.income)}</h3>
              {summary.variation.income !== 0 && (
                <span className={`badge ${summary.variation.income >= 0 ? 'bg-success' : 'bg-danger'}`}>
                  <i className={`bi bi-arrow-${summary.variation.income >= 0 ? 'up' : 'down'} me-1`}></i>
                  {Math.abs(summary.variation.income)}% {t('reports.vsLastPeriod')}
                </span>
              )}
            </div>
          </div>
        </div>

        <div className="col-md-4">
          <div className="card border-0 h-100" style={{ background: 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)' }}>
            <div className="card-body text-white">
              <h6 className="opacity-75">{t('reports.expenses')} {year}</h6>
              <h3 className="mb-2">{currency(summary.current.expense)}</h3>
              {summary.variation.expense !== 0 && (
                <span className={`badge ${summary.variation.expense <= 0 ? 'bg-success' : 'bg-danger'}`}>
                  <i className={`bi bi-arrow-${summary.variation.expense >= 0 ? 'up' : 'down'} me-1`}></i>
                  {Math.abs(summary.variation.expense)}% {t('reports.vsLastPeriod')}
                </span>
              )}
            </div>
          </div>
        </div>

        <div className="col-md-4">
          <div className="card border-0 h-100" style={{ background: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)' }}>
            <div className="card-body text-white">
              <h6 className="opacity-75">{t('reports.balance')} {year}</h6>
              <h3 className="mb-2">{currency(summary.current.balance)}</h3>
              <span className="small opacity-75">
                Tasa de ahorro: {summary.current.income > 0 
                  ? ((summary.current.balance / summary.current.income) * 100).toFixed(1) 
                  : 0}%
              </span>
            </div>
          </div>
        </div>

        {/* Comparison Chart */}
        <div className="col-12">
          <div className="card border-0" style={{ background: '#0f172a' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">
                <i className="bi bi-bar-chart me-2"></i>
                Comparativa Anual
              </h6>
            </div>
            <div className="card-body" style={{ height: '300px' }}>
              <Bar
                data={{
                  labels: ['Ingresos', 'Gastos', 'Balance'],
                  datasets: [
                    {
                      label: String(year - 1),
                      data: [summary.previous.income, summary.previous.expense, summary.previous.balance],
                      backgroundColor: 'rgba(148, 163, 184, 0.5)',
                      borderColor: '#94a3b8',
                      borderWidth: 1,
                    },
                    {
                      label: String(year),
                      data: [summary.current.income, summary.current.expense, summary.current.balance],
                      backgroundColor: ['rgba(16, 185, 129, 0.7)', 'rgba(239, 68, 68, 0.7)', 'rgba(59, 130, 246, 0.7)'],
                      borderColor: ['#10b981', '#ef4444', '#3b82f6'],
                      borderWidth: 1,
                    },
                  ],
                }}
                options={chartOptions}
              />
            </div>
          </div>
        </div>
      </div>
    );
  };

  // Render Category Tab
  const renderCategory = () => {
    if (!categoryData) return null;

    const colors = categoryData.data.map((_, i) => 
      `hsl(${(i * 360) / categoryData.data.length}, 70%, 50%)`
    );

    return (
      <div className="row g-4">
        <div className="col-lg-6">
          <div className="card border-0" style={{ background: '#0f172a' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">
                <i className="bi bi-pie-chart me-2"></i>
                Distribución de Gastos
              </h6>
            </div>
            <div className="card-body" style={{ height: '400px' }}>
              <Doughnut
                data={{
                  labels: categoryData.data.map(c => c.category_name),
                  datasets: [{
                    data: categoryData.data.map(c => c.total),
                    backgroundColor: colors,
                    borderWidth: 0,
                  }],
                }}
                options={doughnutOptions}
              />
            </div>
          </div>
        </div>

        <div className="col-lg-6">
          <div className="card border-0" style={{ background: '#0f172a' }}>
            <div className="card-header border-0 bg-transparent d-flex justify-content-between">
              <h6 className="text-white mb-0">
                <i className="bi bi-list-ol me-2"></i>
                Detalle por Categoría
              </h6>
              <span className="text-success fw-bold">{currency(categoryData.total)}</span>
            </div>
            <div className="card-body p-0" style={{ maxHeight: '400px', overflowY: 'auto' }}>
              <table className="table table-dark table-hover mb-0">
                <thead className="sticky-top" style={{ background: '#1e293b' }}>
                  <tr>
                    <th>Categoría</th>
                    <th className="text-end">Total</th>
                    <th className="text-end">%</th>
                  </tr>
                </thead>
                <tbody>
                  {categoryData.data.map((cat, i) => (
                    <tr key={cat.category_id}>
                      <td>
                        <i className={`bi ${cat.icon} me-2`} style={{ color: colors[i] }}></i>
                        {cat.category_name}
                      </td>
                      <td className="text-end">{currency(cat.total)}</td>
                      <td className="text-end">
                        <span className="badge bg-secondary">{cat.percentage}%</span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // Render Evolution Tab
  const renderEvolution = () => {
    if (!evolutionData) return null;

    return (
      <div className="row g-4">
        <div className="col-12">
          <div className="d-flex gap-2 mb-3">
            {[6, 12, 24].map(m => (
              <button
                key={m}
                className={`btn btn-sm ${months === m ? 'btn-primary' : 'btn-outline-secondary'}`}
                onClick={() => setMonths(m)}
              >
                {m} meses
              </button>
            ))}
          </div>
        </div>

        {/* Averages Cards */}
        <div className="col-md-3">
          <div className="card border-0 text-center" style={{ background: '#1e293b' }}>
            <div className="card-body">
              <small className="text-slate-400">{t('reports.avgIncome')}</small>
              <h5 className="text-success mb-0">{currency(evolutionData.averages.income)}</h5>
            </div>
          </div>
        </div>
        <div className="col-md-3">
          <div className="card border-0 text-center" style={{ background: '#1e293b' }}>
            <div className="card-body">
              <small className="text-slate-400">{t('reports.avgExpense')}</small>
              <h5 className="text-danger mb-0">{currency(evolutionData.averages.expense)}</h5>
            </div>
          </div>
        </div>
        <div className="col-md-3">
          <div className="card border-0 text-center" style={{ background: '#1e293b' }}>
            <div className="card-body">
              <small className="text-slate-400">{t('reports.balance')}</small>
              <h5 className={`mb-0 ${evolutionData.averages.balance >= 0 ? 'text-success' : 'text-danger'}`}>
                {currency(evolutionData.averages.balance)}
              </h5>
            </div>
          </div>
        </div>
        <div className="col-md-3">
          <div className="card border-0 text-center" style={{ background: '#1e293b' }}>
            <div className="card-body">
              <small className="text-slate-400">{t('reports.savingsRate')}</small>
              <h5 className="text-primary mb-0">{evolutionData.averages.savings_rate}%</h5>
            </div>
          </div>
        </div>

        {/* Evolution Chart */}
        <div className="col-12">
          <div className="card border-0" style={{ background: '#0f172a' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">
                <i className="bi bi-graph-up me-2"></i>
                {t('reports.monthlyEvolution')}
              </h6>
            </div>
            <div className="card-body" style={{ height: '350px' }}>
              <Line
                data={{
                  labels: evolutionData.data.map(d => d.month_label),
                  datasets: [
                    {
                      label: t('reports.income'),
                      data: evolutionData.data.map(d => d.income),
                      borderColor: '#10b981',
                      backgroundColor: 'rgba(16, 185, 129, 0.1)',
                      fill: true,
                      tension: 0.3,
                    },
                    {
                      label: t('reports.expenses'),
                      data: evolutionData.data.map(d => d.expense),
                      borderColor: '#ef4444',
                      backgroundColor: 'rgba(239, 68, 68, 0.1)',
                      fill: true,
                      tension: 0.3,
                    },
                    {
                      label: t('reports.balance'),
                      data: evolutionData.data.map(d => d.balance),
                      borderColor: '#3b82f6',
                      backgroundColor: 'transparent',
                      borderDash: [5, 5],
                      tension: 0.3,
                    },
                  ],
                }}
                options={chartOptions}
              />
            </div>
          </div>
        </div>

        {/* Savings Rate Chart */}
        <div className="col-12">
          <div className="card border-0" style={{ background: '#0f172a' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">
                <i className="bi bi-percent me-2"></i>
                {t('reports.savingsRate')} por mes
              </h6>
            </div>
            <div className="card-body" style={{ height: '250px' }}>
              <Bar
                data={{
                  labels: evolutionData.data.map(d => d.month_label),
                  datasets: [{
                    label: t('reports.savingsRate'),
                    data: evolutionData.data.map(d => d.savings_rate),
                    backgroundColor: evolutionData.data.map(d => 
                      d.savings_rate >= 20 ? 'rgba(16, 185, 129, 0.7)' :
                      d.savings_rate >= 10 ? 'rgba(245, 158, 11, 0.7)' :
                      d.savings_rate >= 0 ? 'rgba(239, 68, 68, 0.5)' :
                      'rgba(239, 68, 68, 0.8)'
                    ),
                    borderRadius: 4,
                  }],
                }}
                options={{
                  ...chartOptions,
                  plugins: {
                    ...chartOptions.plugins,
                    legend: { display: false }
                  }
                }}
              />
            </div>
          </div>
        </div>
      </div>
    );
  };

  // Render Comparison Tab
  const renderComparison = () => {
    if (!comparison) return null;

    return (
      <div className="row g-4">
        <div className="col-md-6">
          <div className="card border-0" style={{ background: '#1e293b' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">{comparison.period2.label}</h6>
            </div>
            <div className="card-body">
              <div className="d-flex justify-content-between mb-3">
                <span className="text-slate-400">{t('reports.income')}</span>
                <span className="text-success">{currency(comparison.period2.income)}</span>
              </div>
              <div className="d-flex justify-content-between mb-3">
                <span className="text-slate-400">{t('reports.expenses')}</span>
                <span className="text-danger">{currency(comparison.period2.expense)}</span>
              </div>
              <div className="d-flex justify-content-between">
                <span className="text-slate-400">{t('reports.balance')}</span>
                <span className={comparison.period2.balance >= 0 ? 'text-success' : 'text-danger'}>
                  {currency(comparison.period2.balance)}
                </span>
              </div>
            </div>
          </div>
        </div>

        <div className="col-md-6">
          <div className="card border-0" style={{ background: '#0f172a', border: '2px solid #3b82f6' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">
                {comparison.period1.label}
                <span className="badge bg-primary ms-2">Actual</span>
              </h6>
            </div>
            <div className="card-body">
              <div className="d-flex justify-content-between mb-3">
                <span className="text-slate-400">{t('reports.income')}</span>
                <div>
                  <span className="text-success">{currency(comparison.period1.income)}</span>
                  {comparison.variation.income !== 0 && (
                    <span className={`badge ms-2 ${comparison.variation.income >= 0 ? 'bg-success' : 'bg-danger'}`}>
                      {comparison.variation.income > 0 ? '+' : ''}{comparison.variation.income}%
                    </span>
                  )}
                </div>
              </div>
              <div className="d-flex justify-content-between mb-3">
                <span className="text-slate-400">{t('reports.expenses')}</span>
                <div>
                  <span className="text-danger">{currency(comparison.period1.expense)}</span>
                  {comparison.variation.expense !== 0 && (
                    <span className={`badge ms-2 ${comparison.variation.expense <= 0 ? 'bg-success' : 'bg-danger'}`}>
                      {comparison.variation.expense > 0 ? '+' : ''}{comparison.variation.expense}%
                    </span>
                  )}
                </div>
              </div>
              <div className="d-flex justify-content-between">
                <span className="text-slate-400">{t('reports.balance')}</span>
                <span className={comparison.period1.balance >= 0 ? 'text-success' : 'text-danger'}>
                  {currency(comparison.period1.balance)}
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* Comparison Chart */}
        <div className="col-12">
          <div className="card border-0" style={{ background: '#0f172a' }}>
            <div className="card-body" style={{ height: '300px' }}>
              <Bar
                data={{
                  labels: [t('reports.income'), t('reports.expenses'), t('reports.balance')],
                  datasets: [
                    {
                      label: comparison.period2.label,
                      data: [comparison.period2.income, comparison.period2.expense, comparison.period2.balance],
                      backgroundColor: 'rgba(148, 163, 184, 0.5)',
                      borderRadius: 4,
                    },
                    {
                      label: comparison.period1.label,
                      data: [comparison.period1.income, comparison.period1.expense, comparison.period1.balance],
                      backgroundColor: ['rgba(16, 185, 129, 0.7)', 'rgba(239, 68, 68, 0.7)', 'rgba(59, 130, 246, 0.7)'],
                      borderRadius: 4,
                    },
                  ],
                }}
                options={chartOptions}
              />
            </div>
          </div>
        </div>
      </div>
    );
  };

  // Render Top Expenses Tab
  const renderTopExpenses = () => {
    if (!topExpenses) return null;

    return (
      <div className="card border-0" style={{ background: '#0f172a' }}>
        <div className="card-header border-0 bg-transparent d-flex justify-content-between">
          <h6 className="text-white mb-0">
            <i className="bi bi-sort-down me-2"></i>
            Top 20 Gastos del Mes
          </h6>
          <span className="text-danger fw-bold">{currency(topExpenses.total)}</span>
        </div>
        <div className="card-body p-0">
          <div className="table-responsive">
            <table className="table table-dark table-hover mb-0">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Descripción</th>
                  <th>Categoría</th>
                  <th>Fecha</th>
                  <th className="text-end">Monto</th>
                </tr>
              </thead>
              <tbody>
                {topExpenses.data.map((t, i) => (
                  <tr key={t.id}>
                    <td><span className="badge bg-secondary">{i + 1}</span></td>
                    <td className="text-truncate" style={{ maxWidth: '200px' }}>{t.description}</td>
                    <td><span className="badge bg-primary">{t.category || '-'}</span></td>
                    <td className="text-slate-400">{t.date}</td>
                    <td className="text-end text-danger fw-bold">{currency(t.amount)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );
  };

  // Render Projection Tab
  const renderProjection = () => {
    if (!projection) return null;

    return (
      <div className="row g-4">
        <div className="col-md-6">
          <div className="card border-0" style={{ background: '#1e293b' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">
                <i className="bi bi-calendar3 me-2"></i>
                Mes Actual
              </h6>
            </div>
            <div className="card-body">
              <div className="d-flex justify-content-between mb-3">
                <span className="text-slate-400">{t('reports.income')}</span>
                <span className="text-success">{currency(projection.current_month.income)}</span>
              </div>
              <div className="d-flex justify-content-between mb-3">
                <span className="text-slate-400">{t('reports.expenses')}</span>
                <span className="text-danger">{currency(projection.current_month.expense)}</span>
              </div>
              <hr className="border-secondary" />
              <div className="d-flex justify-content-between">
                <span className="text-slate-400">{t('reports.daysRemaining')}</span>
                <span className="text-white">{projection.current_month.days_remaining} días</span>
              </div>
            </div>
          </div>
        </div>

        <div className="col-md-6">
          <div className="card border-0" style={{ background: 'linear-gradient(135deg, #1e40af 0%, #3b82f6 100%)' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">
                <i className="bi bi-lightning me-2"></i>
                {t('reports.projectionTitle')}
              </h6>
            </div>
            <div className="card-body text-white">
              <div className="d-flex justify-content-between mb-3">
                <span className="opacity-75">{t('reports.projectedIncome')}</span>
                <span className="fw-bold">{currency(projection.projection.income)}</span>
              </div>
              <div className="d-flex justify-content-between mb-3">
                <span className="opacity-75">{t('reports.projectedExpense')}</span>
                <span className="fw-bold">{currency(projection.projection.expense)}</span>
              </div>
              <hr className="border-white opacity-25" />
              <div className="d-flex justify-content-between">
                <span className="opacity-75">{t('reports.balance')}</span>
                <span className={`fw-bold ${projection.projection.balance >= 0 ? '' : 'text-warning'}`}>
                  {currency(projection.projection.balance)}
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* vs Average */}
        <div className="col-12">
          <div className="card border-0" style={{ background: '#0f172a' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">
                <i className="bi bi-bar-chart me-2"></i>
                {t('reports.vsAverage')} (últimos 3 meses)
              </h6>
            </div>
            <div className="card-body" style={{ height: '250px' }}>
              <Bar
                data={{
                  labels: [t('reports.income'), t('reports.expenses')],
                  datasets: [
                    {
                      label: 'Promedio histórico',
                      data: [projection.historical_average.income, projection.historical_average.expense],
                      backgroundColor: 'rgba(148, 163, 184, 0.5)',
                      borderRadius: 4,
                    },
                    {
                      label: 'Proyección mes',
                      data: [projection.projection.income, projection.projection.expense],
                      backgroundColor: ['rgba(16, 185, 129, 0.7)', 'rgba(239, 68, 68, 0.7)'],
                      borderRadius: 4,
                    },
                  ],
                }}
                options={chartOptions}
              />
            </div>
          </div>
        </div>
      </div>
    );
  };

  // Render Day of Week Tab
  const renderDayOfWeek = () => {
    if (!dayOfWeekData) return null;

    const days = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];

    return (
      <div className="row g-4">
        <div className="col-12">
          <div className="card border-0" style={{ background: '#0f172a' }}>
            <div className="card-header border-0 bg-transparent">
              <h6 className="text-white mb-0">
                <i className="bi bi-calendar-week me-2"></i>
                Gastos por Día de la Semana
              </h6>
            </div>
            <div className="card-body" style={{ height: '300px' }}>
              <Bar
                data={{
                  labels: dayOfWeekData.map(d => days[d.day_num - 1]),
                  datasets: [{
                    label: 'Total gastado',
                    data: dayOfWeekData.map(d => d.total),
                    backgroundColor: dayOfWeekData.map(d => 
                      d.day_num === 1 || d.day_num === 7 
                        ? 'rgba(245, 158, 11, 0.7)' 
                        : 'rgba(59, 130, 246, 0.7)'
                    ),
                    borderRadius: 4,
                  }],
                }}
                options={{
                  ...chartOptions,
                  plugins: { ...chartOptions.plugins, legend: { display: false } }
                }}
              />
            </div>
          </div>
        </div>

        <div className="col-12">
          <div className="card border-0" style={{ background: '#1e293b' }}>
            <div className="card-body p-0">
              <table className="table table-dark mb-0">
                <thead>
                  <tr>
                    <th>Día</th>
                    <th className="text-center">Transacciones</th>
                    <th className="text-end">Total</th>
                    <th className="text-end">Promedio</th>
                  </tr>
                </thead>
                <tbody>
                  {dayOfWeekData.map(d => (
                    <tr key={d.day_num}>
                      <td>
                        <i className={`bi bi-calendar3 me-2 ${d.day_num === 1 || d.day_num === 7 ? 'text-warning' : 'text-primary'}`}></i>
                        {d.day}
                      </td>
                      <td className="text-center"><span className="badge bg-secondary">{d.count}</span></td>
                      <td className="text-end text-danger">{currency(d.total)}</td>
                      <td className="text-end text-slate-400">{currency(d.average)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    );
  };

  const renderContent = () => {
    if (loading) {
      return (
        <div className="text-center py-5">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">{t('common.loading')}</span>
          </div>
        </div>
      );
    }

    switch (activeTab) {
      case 'summary': return renderSummary();
      case 'category': return renderCategory();
      case 'evolution': return renderEvolution();
      case 'comparison': return renderComparison();
      case 'topExpenses': return renderTopExpenses();
      case 'projection': return renderProjection();
      case 'dayOfWeek': return renderDayOfWeek();
      default: return null;
    }
  };

  return (
    <div className="reports-container">
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h4 className="text-white mb-1 fw-bold">
            <i className="bi bi-bar-chart-line me-2"></i>
            {t('reports.title')}
          </h4>
          <p className="text-slate-400 mb-0 small">{t('reports.subtitle')}</p>
        </div>
      </div>

      {/* Tabs */}
      <div className="card border-0 mb-4" style={{ background: '#0f172a' }}>
        <div className="card-body p-2">
          <div className="d-flex flex-wrap gap-2">
            {tabs.map(tab => (
              <button
                key={tab.id}
                className={`btn btn-sm ${activeTab === tab.id ? 'btn-primary' : 'btn-outline-secondary'}`}
                onClick={() => setActiveTab(tab.id)}
              >
                <i className={`bi ${tab.icon} me-1`}></i>
                {tab.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Content */}
      {renderContent()}
    </div>
  );
};

export default Reports;
