import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { BarChart3 } from 'lucide-react';
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from 'recharts';
import { Card, Input, EmptyState, Skeleton, toast } from '../ui';
import { ExportButton } from '../ui/ExportButton';
import { exportToExcel } from '../../lib/exporter';
import { odooApi } from '../../services/odoo';

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

const metodoLabels: Record<string, string> = {
  cash: 'Efectivo', card: 'Tarjeta', transfer: 'Transferencia',
  stripe: 'Stripe', mercadopago: 'MercadoPago',
};

const inicioDeMes = () => {
  const d = new Date();
  d.setDate(1);
  return d.toISOString().split('T')[0];
};
const hoy = () => new Date().toISOString().split('T')[0];

interface SalesData {
  total_sales: number;
  total_paid: number;
  total_due: number;
  count: number;
  by_day: { date: string; total: number }[];
}

const IngresosReport: FC = () => {
  const [start, setStart] = useState(inicioDeMes());
  const [end, setEnd] = useState(hoy());
  const [sales, setSales] = useState<SalesData | null>(null);
  const [byMethod, setByMethod] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const [salesRes, cashRes] = await Promise.all([
        odooApi.getSalesReport(start, end),
        odooApi.getCashReportRange(start, end),
      ]);
      if (salesRes.status === 'success') {
        setSales({
          total_sales: salesRes.total_sales,
          total_paid: salesRes.total_paid,
          total_due: salesRes.total_due,
          count: salesRes.count,
          by_day: salesRes.by_day || [],
        });
      }
      if (cashRes.status === 'success') setByMethod(cashRes.by_method);
    } catch (err) {
      toast.error('Error al cargar ingresos');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [start, end]);

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

  const [exporting, setExporting] = useState(false);
  const exportar = async () => {
    if (!sales) return;
    try {
      setExporting(true);
      const rows: Record<string, unknown>[] = sales.by_day.map((d) => ({
        fecha: d.date, total: d.total, metodo: '',
      }));
      Object.entries(byMethod).forEach(([k, v]) =>
        rows.push({ fecha: '', metodo: metodoLabels[k] || k, total: v }));
      await exportToExcel({
        filename: `ingresos-${start}_${end}`,
        sheetName: 'Ingresos',
        title: 'Ingresos',
        subtitle: `Del ${start} al ${end} · primeras filas por día, luego por método de cobro`,
        columns: [
          { header: 'Fecha', key: 'fecha', format: 'date' },
          { header: 'Método', key: 'metodo' },
          { header: 'Total', key: 'total', format: 'currency' },
        ],
        rows,
        totals: { fecha: '', metodo: 'Total vendido', total: sales.total_sales },
      });
      toast.success('Excel descargado');
    } catch (err) {
      toast.error('Error al exportar');
      console.error(err);
    } finally {
      setExporting(false);
    }
  };

  const chartData = (sales?.by_day || []).map((d) => ({
    name: new Date(`${d.date}T12:00:00`).toLocaleDateString('es-MX', { day: 'numeric', month: 'short' }),
    total: d.total,
  }));
  const ticketPromedio = sales && sales.count > 0 ? sales.total_sales / sales.count : 0;

  return (
    <div className="space-y-4 sm:space-y-6">
      <Card>
        <Card.Body>
          <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 items-end">
            <Input label="Inicio" type="date" value={start} onChange={(e) => setStart(e.target.value)} className="sm:max-w-[180px]" />
            <Input label="Fin" type="date" value={end} onChange={(e) => setEnd(e.target.value)} className="sm:max-w-[180px]" />
            <div className="sm:ml-auto">
              <ExportButton onClick={exportar} loading={exporting} />
            </div>
          </div>
        </Card.Body>
      </Card>

      {loading ? (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-24 w-full" />)}
        </div>
      ) : sales ? (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Card className="p-4 bg-theme-bg border-0">
            <p className="text-xs text-theme-muted">Total vendido</p>
            <p className="text-xl font-heading font-semibold text-theme-heading">{formatCurrency(sales.total_sales)}</p>
          </Card>
          <Card className="p-4 bg-theme-bg border-0">
            <p className="text-xs text-theme-muted">Total cobrado</p>
            <p className="text-xl font-heading font-semibold text-theme-heading">{formatCurrency(sales.total_paid)}</p>
          </Card>
          <Card className="p-4 bg-theme-bg border-0">
            <p className="text-xs text-theme-muted">Por cobrar</p>
            <p className={`text-xl font-heading font-semibold ${sales.total_due > 0 ? 'text-rose-600' : 'text-theme-heading'}`}>
              {formatCurrency(sales.total_due)}
            </p>
          </Card>
          <Card className="p-4 bg-theme-bg border-0">
            <p className="text-xs text-theme-muted">Ticket promedio</p>
            <p className="text-xl font-heading font-semibold text-theme-heading">{formatCurrency(ticketPromedio)}</p>
          </Card>
        </div>
      ) : null}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6">
        <Card className="lg:col-span-2">
          <Card.Body>
            <h3 className="font-heading text-xl text-theme-heading mb-4">Ingresos por día</h3>
            {loading ? (
              <Skeleton className="h-[280px] w-full" />
            ) : chartData.length === 0 ? (
              <EmptyState title="Sin datos" subtitle="No hay ventas en el periodo." icon={<BarChart3 size={28} />} />
            ) : (
              <ResponsiveContainer width="100%" height={280}>
                <AreaChart data={chartData} margin={{ top: 8, right: 8, left: -12, bottom: 0 }}>
                  <defs>
                    <linearGradient id="ingresosGradient" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#57534e" stopOpacity={0.25} />
                      <stop offset="100%" stopColor="#57534e" stopOpacity={0.02} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e7e5e4" />
                  <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fill: '#78716c', fontSize: 12 }} />
                  <YAxis axisLine={false} tickLine={false} tick={{ fill: '#78716c', fontSize: 12 }} tickFormatter={(v: number) => formatCurrency(v)} />
                  <Tooltip
                    contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 12px rgba(0,0,0,0.08)' }}
                    formatter={(v) => formatCurrency(Number(v))}
                  />
                  <Area type="monotone" dataKey="total" stroke="#57534e" strokeWidth={2} fill="url(#ingresosGradient)" name="Ingresos" />
                </AreaChart>
              </ResponsiveContainer>
            )}
          </Card.Body>
        </Card>

        <Card>
          <Card.Body>
            <h3 className="font-heading text-xl text-theme-heading mb-4">Cobros por método</h3>
            {loading ? (
              <Skeleton className="h-32 w-full" />
            ) : Object.keys(byMethod).length === 0 ? (
              <p className="text-sm text-theme-muted">Sin cobros en el periodo.</p>
            ) : (
              <div className="space-y-2">
                {Object.entries(byMethod).map(([method, amount]) => (
                  <div key={method} className="flex items-center justify-between p-2.5 bg-theme-bg rounded-lg text-sm">
                    <span className="text-theme-heading">{metodoLabels[method] || method}</span>
                    <span className="font-medium text-theme-heading">{formatCurrency(amount)}</span>
                  </div>
                ))}
              </div>
            )}
          </Card.Body>
        </Card>
      </div>
    </div>
  );
};

export default IngresosReport;
