import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Share2 } from 'lucide-react';
import { Card, EmptyState, Skeleton, toast } from '../ui';
import { ExportButton } from '../ui/ExportButton';
import { exportToExcel } from '../../lib/exporter';
import { odooApi, type RecomendacionRow } from '../../services/odoo';

const RecomendacionesReport: FC = () => {
  const [recomendaciones, setRecomendaciones] = useState<RecomendacionRow[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getRecomendaciones();
      if (res.status === 'success') {
        setRecomendaciones(res.recomendaciones);
        setTotal(res.total);
      }
    } catch (err) {
      toast.error('Error al cargar recomendaciones');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const [exporting, setExporting] = useState(false);
  const exportar = async () => {
    try {
      setExporting(true);
      await exportToExcel({
        filename: `recomendaciones-${new Date().toISOString().split('T')[0]}`,
        sheetName: 'Recomendaciones',
        title: 'Pacientes por recomendación',
        subtitle: `${total} pacientes recomendados`,
        columns: [
          { header: '#', key: 'rank', format: 'number' },
          { header: 'Recomendador', key: 'recomendador' },
          { header: 'Pacientes', key: 'pacientes', format: 'number' },
        ],
        rows: recomendaciones.map((r, i) => ({ ...r, rank: i + 1 })),
        totals: { recomendador: '', pacientes: total },
      });
      toast.success('Excel descargado');
    } catch (err) {
      toast.error('Error al exportar');
      console.error(err);
    } finally {
      setExporting(false);
    }
  };

  return (
    <Card>
      <Card.Body>
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-heading text-xl text-theme-heading">Pacientes por recomendación</h3>
          <div className="flex items-center gap-3">
            <p className="text-sm text-theme-muted">{total} pacientes recomendados</p>
            <ExportButton onClick={exportar} loading={exporting} />
          </div>
        </div>

        {loading ? (
          <Skeleton count={6} className="h-12 w-full" />
        ) : recomendaciones.length === 0 ? (
          <EmptyState
            title="Sin recomendaciones"
            subtitle="Ningún paciente tiene capturado el campo “Recomendado por”."
            icon={<Share2 size={28} />}
          />
        ) : (
          <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">#</th>
                  <th className="text-left px-4 py-3">Recomendador</th>
                  <th className="text-right px-4 py-3">Pacientes</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-theme-border">
                {recomendaciones.map((r, i) => (
                  <tr key={r.recomendador} className="hover:bg-theme-bg">
                    <td className="px-4 py-3 text-theme-muted">{i + 1}</td>
                    <td className="px-4 py-3 font-medium text-theme-heading">{r.recomendador}</td>
                    <td className="px-4 py-3 text-right text-theme-muted">{r.pacientes}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card.Body>
    </Card>
  );
};

export default RecomendacionesReport;
