import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Calendar, ShoppingCart, CreditCard, Boxes, Stethoscope } from 'lucide-react';
import { Card, Input, Badge, Skeleton, toast } from '../ui';
import { ExportButton } from '../ui/ExportButton';
import { exportToExcel } from '../../lib/exporter';
import { odooApi, type DailyReport as DailyReportData, type DailyPorMedico } from '../../services/odoo';
import type { BadgeVariant } from '../ui/Badge';

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

const citaStateLabels: Record<string, string> = {
  pending: 'Pendiente', confirmed: 'Confirmada', arrived: 'Llegó',
  in_progress: 'En curso', done: 'Completada', cancelled: 'Cancelada', no_show: 'No show',
};

const citaStateBadge = (state: string): BadgeVariant => {
  switch (state) {
    case 'done': return 'success';
    case 'cancelled': case 'no_show': return 'danger';
    case 'pending': return 'warning';
    default: return 'info';
  }
};

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

const moveTypeLabels: Record<string, string> = {
  compra: 'Compra', venta: 'Venta', baja: 'Baja', ajuste: 'Ajuste',
};

const hoy = () => new Date().toISOString().split('T')[0];

const DailyReport: FC = () => {
  const [fecha, setFecha] = useState(hoy());
  const [report, setReport] = useState<DailyReportData | null>(null);
  const [porMedico, setPorMedico] = useState<DailyPorMedico[] | null>(null);
  const [verPorMedico, setVerPorMedico] = useState(false);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getDailyReport(fecha, verPorMedico ? 'medico' : undefined);
      if (res.status === 'success') {
        const { citas, ventas, pagos, inventario, date } = res;
        setReport({ citas, ventas, pagos, inventario, date });
        setPorMedico(res.por_medico || null);
      }
    } catch (err) {
      toast.error('Error al cargar movimientos del día');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [fecha, verPorMedico]);

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

  const [exporting, setExporting] = useState(false);
  const exportar = async () => {
    if (!report) return;
    try {
      setExporting(true);
      const rows: Record<string, unknown>[] = [];
      Object.entries(report.citas.by_state).forEach(([k, v]) =>
        rows.push({ seccion: 'Citas', concepto: citaStateLabels[k] || k, cantidad: v, monto: null }));
      rows.push({ seccion: 'Ventas', concepto: 'Cantidad', cantidad: report.ventas.count, monto: null });
      rows.push({ seccion: 'Ventas', concepto: 'Total', cantidad: null, monto: report.ventas.total });
      rows.push({ seccion: 'Ventas', concepto: 'Pagado', cantidad: null, monto: report.ventas.total_paid });
      rows.push({ seccion: 'Ventas', concepto: 'Por cobrar', cantidad: null, monto: report.ventas.total_due });
      Object.entries(report.pagos.by_method).forEach(([k, v]) =>
        rows.push({ seccion: 'Cobros', concepto: metodoLabels[k] || k, cantidad: null, monto: v }));
      Object.entries(report.inventario.by_type).forEach(([k, v]) =>
        rows.push({ seccion: 'Inventario', concepto: moveTypeLabels[k] || k, cantidad: v, monto: null }));
      if (porMedico) {
        porMedico.forEach((r) =>
          rows.push({ seccion: 'Por médico', concepto: r.medico, cantidad: r.citas, monto: r.ventas + r.cobros }));
      }
      await exportToExcel({
        filename: `movimientos-diarios-${fecha}`,
        sheetName: 'Movimientos diarios',
        title: 'Movimientos diarios',
        subtitle: `Fecha: ${fecha}${verPorMedico ? ' · desglose por médico' : ''}`,
        columns: [
          { header: 'Sección', key: 'seccion' },
          { header: 'Concepto', key: 'concepto' },
          { header: 'Cantidad', key: 'cantidad', format: 'number' },
          { header: 'Monto', key: 'monto', format: 'currency' },
        ],
        rows,
        totals: { seccion: '', concepto: 'Cobros del día', cantidad: report.pagos.count, monto: report.pagos.total },
      });
      toast.success('Excel descargado');
    } catch (err) {
      toast.error('Error al exportar');
      console.error(err);
    } finally {
      setExporting(false);
    }
  };

  return (
    <div className="space-y-4 sm:space-y-6">
      <Card>
        <Card.Body>
          <div className="flex items-end gap-3">
            <Input
              label="Fecha"
              type="date"
              value={fecha}
              onChange={(e) => setFecha(e.target.value)}
              className="sm:max-w-[200px]"
            />
            <button
              type="button"
              onClick={() => setVerPorMedico((v) => !v)}
              className={`mb-1 px-3 py-2 text-sm font-medium rounded-full transition flex items-center gap-1.5 ${
                verPorMedico ? 'bg-theme-accent text-theme-inverse' : 'bg-theme-accent-bg text-theme-heading hover:bg-theme-bg'
              }`}
            >
              <Stethoscope size={14} />
              Por médico
            </button>
            <div className="ml-auto mb-1">
              <ExportButton onClick={exportar} loading={exporting} />
            </div>
          </div>
        </Card.Body>
      </Card>

      {verPorMedico ? (
        <Card>
          <Card.Body>
            <h3 className="font-heading text-xl text-theme-heading mb-4">Movimientos del día por médico</h3>
            {loading ? (
              <Skeleton count={5} className="h-12 w-full" />
            ) : !porMedico || porMedico.length === 0 ? (
              <p className="text-sm text-theme-muted">Sin actividad por médico este día.</p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-theme-bg text-theme-muted text-xs uppercase">
                    <tr>
                      <th className="text-left px-4 py-3">Médico</th>
                      <th className="text-right px-4 py-3">Citas</th>
                      <th className="text-left px-4 py-3">Estados</th>
                      <th className="text-right px-4 py-3">Ventas (recetado)</th>
                      <th className="text-right px-4 py-3">Cobros</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-theme-border">
                    {porMedico.map((r) => (
                      <tr key={r.medico} className="hover:bg-theme-bg">
                        <td className="px-4 py-3 font-medium text-theme-heading">{r.medico}</td>
                        <td className="px-4 py-3 text-right text-theme-muted">{r.citas}</td>
                        <td className="px-4 py-3">
                          <div className="flex flex-wrap gap-1">
                            {Object.entries(r.by_state).map(([state, count]) => (
                              <Badge key={state} variant={citaStateBadge(state)}>
                                {citaStateLabels[state] || state}: {count}
                              </Badge>
                            ))}
                            {r.citas === 0 && <span className="text-theme-muted">-</span>}
                          </div>
                        </td>
                        <td className="px-4 py-3 text-right text-theme-heading">{formatCurrency(r.ventas)}</td>
                        <td className="px-4 py-3 text-right font-medium text-theme-heading">{formatCurrency(r.cobros)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </Card.Body>
        </Card>
      ) : loading ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
          {Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-40 w-full" />)}
        </div>
      ) : report ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
          {/* Citas del día */}
          <Card>
            <Card.Body>
              <h3 className="font-heading text-xl text-theme-heading mb-1 flex items-center">
                <Calendar size={20} className="mr-2" /> Citas del día
              </h3>
              <p className="text-sm text-theme-muted mb-4">Total: <span className="font-semibold text-theme-heading">{report.citas.total}</span></p>
              {Object.keys(report.citas.by_state).length === 0 ? (
                <p className="text-sm text-theme-muted">Sin citas este día.</p>
              ) : (
                <div className="flex flex-wrap gap-2">
                  {Object.entries(report.citas.by_state).map(([state, count]) => (
                    <Badge key={state} variant={citaStateBadge(state)}>
                      {citaStateLabels[state] || state}: {count}
                    </Badge>
                  ))}
                </div>
              )}
            </Card.Body>
          </Card>

          {/* Ventas del día */}
          <Card>
            <Card.Body>
              <h3 className="font-heading text-xl text-theme-heading mb-4 flex items-center">
                <ShoppingCart size={20} className="mr-2" /> Ventas del día
              </h3>
              <div className="grid grid-cols-2 gap-3">
                <div className="p-3 bg-theme-bg rounded-xl">
                  <p className="text-xs text-theme-muted">Cantidad</p>
                  <p className="text-lg font-semibold text-theme-heading">{report.ventas.count}</p>
                </div>
                <div className="p-3 bg-theme-bg rounded-xl">
                  <p className="text-xs text-theme-muted">Total</p>
                  <p className="text-lg font-semibold text-theme-heading">{formatCurrency(report.ventas.total)}</p>
                </div>
                <div className="p-3 bg-theme-bg rounded-xl">
                  <p className="text-xs text-theme-muted">Pagado</p>
                  <p className="text-lg font-semibold text-theme-heading">{formatCurrency(report.ventas.total_paid)}</p>
                </div>
                <div className="p-3 bg-theme-bg rounded-xl">
                  <p className="text-xs text-theme-muted">Por cobrar</p>
                  <p className={`text-lg font-semibold ${report.ventas.total_due > 0 ? 'text-rose-600' : 'text-theme-heading'}`}>
                    {formatCurrency(report.ventas.total_due)}
                  </p>
                </div>
              </div>
            </Card.Body>
          </Card>

          {/* Cobros del día */}
          <Card>
            <Card.Body>
              <h3 className="font-heading text-xl text-theme-heading mb-1 flex items-center">
                <CreditCard size={20} className="mr-2" /> Cobros del día
              </h3>
              <p className="text-sm text-theme-muted mb-4">
                {report.pagos.count} cobros · Total: <span className="font-semibold text-theme-heading">{formatCurrency(report.pagos.total)}</span>
              </p>
              {Object.keys(report.pagos.by_method).length === 0 ? (
                <p className="text-sm text-theme-muted">Sin cobros este día.</p>
              ) : (
                <div className="space-y-2">
                  {Object.entries(report.pagos.by_method).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>

          {/* Movimientos de inventario */}
          <Card>
            <Card.Body>
              <h3 className="font-heading text-xl text-theme-heading mb-1 flex items-center">
                <Boxes size={20} className="mr-2" /> Inventario del día
              </h3>
              <p className="text-sm text-theme-muted mb-4">Movimientos: <span className="font-semibold text-theme-heading">{report.inventario.total}</span></p>
              {Object.keys(report.inventario.by_type).length === 0 ? (
                <p className="text-sm text-theme-muted">Sin movimientos este día.</p>
              ) : (
                <div className="flex flex-wrap gap-2">
                  {Object.entries(report.inventario.by_type).map(([type, count]) => (
                    <Badge key={type} variant="default">
                      {moveTypeLabels[type] || type}: {count}
                    </Badge>
                  ))}
                </div>
              )}
            </Card.Body>
          </Card>
        </div>
      ) : null}
    </div>
  );
};

export default DailyReport;
