'use client';

import { useState } from 'react';
import { Header } from '@/components/layouts/header';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { KpiCard } from '@/components/charts/kpi-card';
import { useIvaMensual, useResumenIva, useResumenIsr } from '@/lib/hooks/use-impuestos';
import { Calculator, TrendingUp, TrendingDown, Receipt } from 'lucide-react';

const meses = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];

export default function ImpuestosPage() {
  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;
  const [año] = useState(currentYear);
  const [activeTab, setActiveTab] = useState<'iva' | 'isr'>('iva');

  const { data: ivaMensual, isLoading: ivaLoading } = useIvaMensual(año);
  const { data: resumenIva } = useResumenIva(año, currentMonth);
  const { data: resumenIsr } = useResumenIsr(año, currentMonth);

  const formatCurrency = (value: number) =>
    new Intl.NumberFormat('es-MX', {
      style: 'currency',
      currency: 'MXN',
      minimumFractionDigits: 0,
    }).format(value);

  return (
    <>
      <Header title="Control de Impuestos" />
      <main className="p-6 space-y-6">
        {/* Tabs */}
        <div className="flex gap-2">
          <Button
            variant={activeTab === 'iva' ? 'default' : 'outline'}
            onClick={() => setActiveTab('iva')}
          >
            <Receipt className="h-4 w-4 mr-2" />
            IVA
          </Button>
          <Button
            variant={activeTab === 'isr' ? 'default' : 'outline'}
            onClick={() => setActiveTab('isr')}
          >
            <Calculator className="h-4 w-4 mr-2" />
            ISR
          </Button>
        </div>

        {activeTab === 'iva' && (
          <>
            {/* IVA KPIs */}
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
              <KpiCard
                title="IVA Trasladado"
                value={resumenIva?.trasladado || 0}
                icon={<TrendingUp className="h-4 w-4" />}
                subtitle="Cobrado a clientes"
              />
              <KpiCard
                title="IVA Acreditable"
                value={resumenIva?.acreditable || 0}
                icon={<TrendingDown className="h-4 w-4" />}
                subtitle="Pagado a proveedores"
              />
              <KpiCard
                title="Resultado del Mes"
                value={resumenIva?.resultado || 0}
                icon={<Calculator className="h-4 w-4" />}
                trend={(resumenIva?.resultado || 0) > 0 ? 'up' : 'down'}
                trendValue={(resumenIva?.resultado || 0) > 0 ? 'Por pagar' : 'A favor'}
              />
              <KpiCard
                title="Acumulado Anual"
                value={resumenIva?.acumuladoAnual || 0}
                icon={<Receipt className="h-4 w-4" />}
                trend={(resumenIva?.acumuladoAnual || 0) < 0 ? 'up' : 'neutral'}
                trendValue={(resumenIva?.acumuladoAnual || 0) < 0 ? 'Saldo a favor' : ''}
              />
            </div>

            {/* IVA Mensual Table */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Histórico IVA {año}</CardTitle>
              </CardHeader>
              <CardContent>
                {ivaLoading ? (
                  <div className="text-center py-8 text-muted-foreground">
                    Cargando...
                  </div>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="w-full">
                      <thead>
                        <tr className="border-b text-left text-sm text-muted-foreground">
                          <th className="pb-3 font-medium">Mes</th>
                          <th className="pb-3 font-medium text-right">Trasladado</th>
                          <th className="pb-3 font-medium text-right">Acreditable</th>
                          <th className="pb-3 font-medium text-right">Retenido</th>
                          <th className="pb-3 font-medium text-right">Resultado</th>
                          <th className="pb-3 font-medium text-right">Acumulado</th>
                          <th className="pb-3 font-medium">Estado</th>
                        </tr>
                      </thead>
                      <tbody className="text-sm">
                        {ivaMensual?.map((row) => (
                          <tr key={row.mes} className="border-b hover:bg-muted/50">
                            <td className="py-3 font-medium">{meses[row.mes - 1]}</td>
                            <td className="py-3 text-right">
                              {formatCurrency(row.ivaTrasladado)}
                            </td>
                            <td className="py-3 text-right">
                              {formatCurrency(row.ivaAcreditable)}
                            </td>
                            <td className="py-3 text-right">
                              {formatCurrency(row.ivaRetenido)}
                            </td>
                            <td
                              className={`py-3 text-right font-medium ${
                                row.resultado > 0
                                  ? 'text-destructive'
                                  : 'text-success'
                              }`}
                            >
                              {formatCurrency(row.resultado)}
                            </td>
                            <td
                              className={`py-3 text-right font-medium ${
                                row.acumulado > 0
                                  ? 'text-destructive'
                                  : 'text-success'
                              }`}
                            >
                              {formatCurrency(row.acumulado)}
                            </td>
                            <td className="py-3">
                              <span
                                className={`px-2 py-1 rounded-full text-xs font-medium ${
                                  row.estado === 'declarado'
                                    ? 'bg-success/10 text-success'
                                    : 'bg-warning/10 text-warning'
                                }`}
                              >
                                {row.estado === 'declarado' ? 'Declarado' : 'Pendiente'}
                              </span>
                            </td>
                          </tr>
                        ))}
                        {(!ivaMensual || ivaMensual.length === 0) && (
                          <tr>
                            <td colSpan={7} className="py-8 text-center text-muted-foreground">
                              No hay registros de IVA para este año
                            </td>
                          </tr>
                        )}
                      </tbody>
                    </table>
                  </div>
                )}
              </CardContent>
            </Card>
          </>
        )}

        {activeTab === 'isr' && (
          <>
            {/* ISR KPIs */}
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
              <KpiCard
                title="Ingresos Acumulados"
                value={resumenIsr?.ingresosAcumulados || 0}
                icon={<TrendingUp className="h-4 w-4" />}
              />
              <KpiCard
                title="Deducciones"
                value={resumenIsr?.deducciones || 0}
                icon={<TrendingDown className="h-4 w-4" />}
              />
              <KpiCard
                title="Base Gravable"
                value={resumenIsr?.baseGravable || 0}
                icon={<Calculator className="h-4 w-4" />}
              />
              <KpiCard
                title="ISR a Pagar"
                value={resumenIsr?.isrAPagar || 0}
                icon={<Receipt className="h-4 w-4" />}
                trend={(resumenIsr?.isrAPagar || 0) > 0 ? 'up' : 'neutral'}
              />
            </div>

            {/* ISR Info Card */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Cálculo de ISR Acumulado</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex justify-between py-2 border-b">
                    <span className="text-muted-foreground">Ingresos acumulados</span>
                    <span className="font-medium">
                      {formatCurrency(resumenIsr?.ingresosAcumulados || 0)}
                    </span>
                  </div>
                  <div className="flex justify-between py-2 border-b">
                    <span className="text-muted-foreground">(-) Deducciones autorizadas</span>
                    <span className="font-medium">
                      {formatCurrency(resumenIsr?.deducciones || 0)}
                    </span>
                  </div>
                  <div className="flex justify-between py-2 border-b">
                    <span className="text-muted-foreground">(=) Base gravable</span>
                    <span className="font-medium">
                      {formatCurrency(resumenIsr?.baseGravable || 0)}
                    </span>
                  </div>
                  <div className="flex justify-between py-2 border-b">
                    <span className="text-muted-foreground">ISR causado (estimado)</span>
                    <span className="font-medium">
                      {formatCurrency(resumenIsr?.isrCausado || 0)}
                    </span>
                  </div>
                  <div className="flex justify-between py-2 border-b">
                    <span className="text-muted-foreground">(-) ISR retenido</span>
                    <span className="font-medium">
                      {formatCurrency(resumenIsr?.isrRetenido || 0)}
                    </span>
                  </div>
                  <div className="flex justify-between py-2 bg-muted/50 px-4 rounded-lg">
                    <span className="font-medium">ISR a pagar</span>
                    <span className="font-bold text-lg">
                      {formatCurrency(resumenIsr?.isrAPagar || 0)}
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>
          </>
        )}
      </main>
    </>
  );
}
