import type { FC } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { Mail, Phone, Stethoscope, Briefcase, Save, Percent, Eye, CalendarDays, FileText, ShoppingCart, Users, ClipboardList, CreditCard, DollarSign } from 'lucide-react';
import Layout from '../components/Layout';
import { Card, Badge, EmptyState, PageHeader, Skeleton, MobileCard, Input, Button, Modal, toast } from '../components/ui';
import { odooApi, type Doctor, type DoctorHistory } from '../services/odoo';

const medicalTerms = ['doctor', 'dra', 'médico', 'medico', 'especialista', 'dermatólogo', 'dermatologo', 'skin', 'clínico', 'clinico'];

const isMedicalTitle = (jobTitle?: string) => {
  if (!jobTitle) return false;
  const normalized = jobTitle.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
  return medicalTerms.some((term) => normalized.includes(term));
};

const fmtNum = (n: number | null | undefined, decimals = 2) =>
  (n ?? 0).toLocaleString('es-MX', { maximumFractionDigits: decimals });

const fmtMoney = (n: number) =>
  (n || 0).toLocaleString('es-MX', { style: 'currency', currency: 'MXN', maximumFractionDigits: 0 });

const initials = (name: string) =>
  name.split(' ').filter(Boolean).slice(0, 2).map((w) => w[0]).join('').toUpperCase();

type BadgeVariant = 'default' | 'success' | 'info' | 'pending' | 'cancelled';

const CITA_STATE: Record<string, { label: string; variant: BadgeVariant }> = {
  pending: { label: 'Pendiente', variant: 'pending' },
  confirmed: { label: 'Confirmada', variant: 'info' },
  arrived: { label: 'Llegó', variant: 'info' },
  in_progress: { label: 'En progreso', variant: 'info' },
  done: { label: 'Completada', variant: 'success' },
  cancelled: { label: 'Cancelada', variant: 'cancelled' },
  no_show: { label: 'No show', variant: 'cancelled' },
};

const VISITA_STATE: Record<string, { label: string; variant: BadgeVariant }> = {
  en_curso: { label: 'En curso', variant: 'info' },
  completada: { label: 'Completada', variant: 'success' },
  cancelada: { label: 'Cancelada', variant: 'cancelled' },
};

const VENTA_STATE: Record<string, { label: string; variant: BadgeVariant }> = {
  draft: { label: 'Borrador', variant: 'default' },
  confirmed: { label: 'Confirmada', variant: 'info' },
  paid: { label: 'Pagada', variant: 'success' },
  partial: { label: 'Parcial', variant: 'pending' },
  cancelled: { label: 'Cancelada', variant: 'cancelled' },
};

const StateBadge: FC<{ map: Record<string, { label: string; variant: BadgeVariant }>; state: string }> = ({ map, state }) => {
  const meta = map[state] || { label: state, variant: 'default' as BadgeVariant };
  return <Badge variant={meta.variant}>{meta.label}</Badge>;
};

/** Badges de ventas 30d al estilo del sistema legacy:
 *  píldora verde "N ventas" + gris "N recomendaciones" y
 *  píldoras índigo apiladas: usd / m.n. / tarjeta m.n. */
const StatBadges: FC<{ d: Doctor }> = ({ d }) => (
  <div>
    <div className="flex flex-wrap items-center gap-2 mb-1.5">
      <span
        className="inline-flex items-center gap-1.5 rounded px-2 py-0.5 text-xs font-medium text-white"
        style={{ backgroundColor: '#00a65a' }}
      >
        <span className="font-bold">{d.ventas_30d ?? 0}</span> ventas
      </span>
    </div>
    <div className="space-y-0.5">
      <span className="block w-fit rounded px-1.5 py-0.5 text-[11px] text-white" style={{ backgroundColor: '#605ca8' }}>
        {d.total_30d_usd == null ? '—' : fmtNum(d.total_30d_usd)} usd
      </span>
      <span className="block w-fit rounded px-1.5 py-0.5 text-[11px] text-white" style={{ backgroundColor: '#605ca8' }}>
        {fmtNum(d.total_30d ?? 0, 0)} m.n.
      </span>
      <span className="block w-fit rounded px-1.5 py-0.5 text-[11px] text-white" style={{ backgroundColor: '#605ca8' }}>
        {fmtNum(d.card_30d ?? 0, 0)} tarjeta m.n.
      </span>
    </div>
  </div>
);

const Medicos: FC = () => {
  const [employees, setEmployees] = useState<Doctor[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const load = async () => {
      try {
        setLoading(true);
        setError(null);
        const res = await odooApi.getDoctors();
        if (res.status === 'success') setEmployees(res.doctors);
      } catch (err) {
        setError('Error al cargar médicos');
        toast.error('Error al cargar médicos');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);

  const doctors = useMemo(() => {
    const medical = employees.filter((d) => isMedicalTitle(d.job_title));
    return medical.length > 0 ? medical : employees;
  }, [employees]);

  const [pctDraft, setPctDraft] = useState<Record<number, string>>({});
  const [savingPct, setSavingPct] = useState<number | null>(null);

  // Modal de detalle del médico
  const [selected, setSelected] = useState<Doctor | null>(null);
  const [modalTab, setModalTab] = useState<'info' | 'historial'>('info');
  const [hist, setHist] = useState<DoctorHistory | null>(null);
  const [histLoading, setHistLoading] = useState(false);
  const [histSection, setHistSection] = useState<'citas' | 'visitas' | 'ventas'>('citas');

  const openDoctor = (d: Doctor) => {
    setSelected(d);
    setModalTab('info');
    setHistSection('citas');
    setHist(null);
    setHistLoading(true);
    odooApi.getDoctorHistory(d.id)
      .then((res) => { if (res.status === 'success') setHist(res); })
      .catch((err) => { toast.error('No se pudo cargar el historial'); console.error(err); })
      .finally(() => setHistLoading(false));
  };

  const pctValue = (d: Doctor) => (pctDraft[d.id] ?? String(d.commission_pct ?? 0));

  const savePct = async (d: Doctor) => {
    const raw = pctDraft[d.id];
    const pct = parseFloat(raw ?? String(d.commission_pct ?? 0));
    if (Number.isNaN(pct) || pct < 0 || pct > 100) {
      toast.error('Porcentaje inválido (0-100)');
      return;
    }
    setSavingPct(d.id);
    try {
      await odooApi.updateDoctor(d.id, { commission_pct: pct });
      setEmployees((prev) => prev.map((e) => (e.id === d.id ? { ...e, commission_pct: pct } : e)));
      setPctDraft((prev) => { const n = { ...prev }; delete n[d.id]; return n; });
      toast.success(`Comisión de ${d.name}: ${pct}%`);
    } catch {
      toast.error('No se pudo guardar la comisión');
    } finally {
      setSavingPct(null);
    }
  };

  return (
    <Layout title="Médicos" subtitle="Equipo médico">
      <PageHeader title="Médicos" subtitle="Especialistas de la clínica" />

      <Card>
        <Card.Body>
          {error && <p className="text-rose-600 text-sm mb-4">{error}</p>}

          {loading ? (
            <Skeleton count={5} className="h-14 w-full" />
          ) : doctors.length === 0 ? (
            <EmptyState title="Sin médicos" subtitle="No se encontraron médicos en el equipo." icon={<Stethoscope size={28} />} />
          ) : (
            <>
              <div className="hidden sm:block overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-theme-bg">
                    <tr>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Nombre</th>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Puesto</th>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden md:table-cell">Teléfono</th>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden lg:table-cell">Email</th>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">% Comisión</th>
                      <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase" title="Ventas con líneas recetadas por el médico, últimos 30 días">Últimos 30 días</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {doctors.map((d) => (
                      <tr key={d.id} className="hover:bg-theme-bg cursor-pointer" onClick={() => openDoctor(d)} title="Ver detalle del médico">
                        <td className="p-3 text-sm font-medium text-theme-heading">{d.name}</td>
                        <td className="p-3">
                          <Badge variant="default" className="inline-flex items-center">
                            <Briefcase size={12} className="mr-1" />
                            {d.job_title || 'Sin puesto'}
                          </Badge>
                        </td>
                        <td className="p-3 text-sm text-theme-muted hidden md:table-cell">
                          <a href={`tel:${d.work_phone}`} className="hover:text-theme-heading">
                            <Phone size={14} className="inline mr-1 text-theme-muted" />
                            {d.work_phone || '-'}
                          </a>
                        </td>
                        <td className="p-3 text-sm text-theme-muted hidden lg:table-cell">
                          {d.work_email ? (
                            <a href={`mailto:${d.work_email}`} className="hover:text-theme-heading">
                              <Mail size={14} className="inline mr-1 text-theme-muted" />
                              {d.work_email}
                            </a>
                          ) : (
                            '-'
                          )}
                        </td>
                        <td className="p-3" onClick={(e) => e.stopPropagation()}>
                          <div className="flex items-center gap-2 max-w-[170px]">
                            <Percent size={14} className="text-theme-muted shrink-0" />
                            <Input
                              type="number"
                              min="0"
                              max="100"
                              step="0.5"
                              value={pctValue(d)}
                              onChange={(e) => setPctDraft((prev) => ({ ...prev, [d.id]: e.target.value }))}
                              className="max-w-[92px]"
                            />
                            <Button size="sm" variant="outline" loading={savingPct === d.id} onClick={() => savePct(d)} title="Guardar %">
                              <Save size={14} />
                            </Button>
                          </div>
                        </td>
                        <td className="p-3 align-top">
                          <StatBadges d={d} />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div className="sm:hidden space-y-3">
                {doctors.map((d) => (
                  <MobileCard
                    key={d.id}
                    title={d.name}
                    subtitle={
                      <Badge variant="default" className="inline-flex items-center">
                        <Briefcase size={12} className="mr-1" />
                        {d.job_title || 'Sin puesto'}
                      </Badge>
                    }
                    rows={[
                      { label: 'Teléfono', value: d.work_phone || '-' },
                      { label: 'Email', value: d.work_email || '-' },
                      { label: '% Comisión', value: `${d.commission_pct ?? 0}%` },
                      { label: 'Últimos 30 días', value: <StatBadges d={d} /> },
                    ]}
                    actions={
                      <Button variant="ghost" size="sm" onClick={() => openDoctor(d)} title="Ver detalle">
                        <Eye size={16} className="text-theme-muted" />
                      </Button>
                    }
                  />
                ))}
              </div>
            </>
          )}
        </Card.Body>
      </Card>

      {/* Modal detalle del médico */}
      <Modal isOpen={!!selected} onClose={() => setSelected(null)} title="" maxWidth="2xl">
        {selected && (
          <div>
            {/* Header */}
            <div className="flex flex-wrap items-center justify-between gap-4 mb-5">
              <div className="flex items-center gap-4 min-w-0">
                <span className="flex h-14 w-14 shrink-0 items-center justify-center rounded-full bg-brand-lilac text-base font-bold text-theme-heading">
                  {initials(selected.name)}
                </span>
                <div className="min-w-0">
                  <h3 className="font-heading text-2xl text-theme-heading truncate">{selected.name}</h3>
                  <Badge variant="default" className="inline-flex items-center mt-1">
                    <Briefcase size={12} className="mr-1" />
                    {selected.job_title || 'Sin puesto'}
                  </Badge>
                </div>
              </div>
              <div className="flex items-center gap-5">
                <div className="text-right">
                  <p className="text-xs font-medium text-theme-muted uppercase">Pacientes</p>
                  <p className="font-heading text-xl text-theme-heading">{fmtNum(selected.patient_count ?? 0, 0)}</p>
                </div>
                <div className="text-right">
                  <p className="text-xs font-medium text-theme-muted uppercase">Citas</p>
                  <p className="font-heading text-xl text-theme-heading">{histLoading || !hist ? '…' : fmtNum(hist.totales.citas_total, 0)}</p>
                </div>
                <div className="text-right">
                  <p className="text-xs font-medium text-theme-muted uppercase">Visitas</p>
                  <p className="font-heading text-xl text-theme-heading">{histLoading || !hist ? '…' : fmtNum(hist.totales.visitas_total, 0)}</p>
                </div>
              </div>
            </div>

            {/* Tabs */}
            <div className="flex flex-wrap gap-1.5 mb-4">
              {([{ key: 'info', label: 'Info' }, { key: 'historial', label: 'Historial' }] as const).map((t) => (
                <button
                  key={t.key}
                  type="button"
                  onClick={() => setModalTab(t.key)}
                  className={`px-4 py-2 text-sm font-medium rounded-full transition ${
                    modalTab === t.key ? 'bg-theme-accent text-theme-inverse' : 'bg-theme-accent-bg text-theme-heading hover:bg-theme-bg'
                  }`}
                >
                  {t.label}
                </button>
              ))}
            </div>

            {modalTab === 'info' ? (
              <div className="space-y-4">
                <div>
                  <p className="text-xs font-medium text-theme-muted uppercase mb-2">Resumen de actividad</p>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                    <div className="p-3 bg-theme-bg rounded-xl">
                      <p className="text-xs text-theme-muted flex items-center gap-1 mb-1"><Users size={12} /> Pacientes asignados</p>
                      <p className="font-heading text-xl text-theme-heading">{fmtNum(selected.patient_count ?? 0, 0)}</p>
                    </div>
                    <div className="p-3 bg-theme-bg rounded-xl" title="Ventas con líneas recetadas por el médico, últimos 30 días">
                      <p className="text-xs text-theme-muted flex items-center gap-1 mb-1"><ShoppingCart size={12} /> Ventas 30d</p>
                      <p className="font-heading text-xl text-theme-heading">{selected.ventas_30d ?? 0}</p>
                    </div>
                    <div className="p-3 bg-theme-bg rounded-xl" title="Subtotal de líneas recetadas, últimos 30 días">
                      <p className="text-xs text-theme-muted flex items-center gap-1 mb-1"><DollarSign size={12} /> Total 30d</p>
                      <p className="font-heading text-xl text-theme-heading">{fmtMoney(selected.total_30d ?? 0)}</p>
                    </div>
                    <div className="p-3 bg-theme-bg rounded-xl" title="Pagado con tarjeta (terminal física), últimos 30 días">
                      <p className="text-xs text-theme-muted flex items-center gap-1 mb-1"><CreditCard size={12} /> Tarjeta 30d</p>
                      <p className="font-heading text-xl text-theme-heading">{fmtMoney(selected.card_30d ?? 0)}</p>
                    </div>
                  </div>
                  <div className="mt-2">
                    <span
                      className="inline-flex items-center rounded px-1.5 py-0.5 text-[11px] text-white"
                      style={{ backgroundColor: '#605ca8' }}
                      title="Equivalente en USD al TC vigente"
                    >
                      {selected.total_30d_usd == null ? '—' : `≈ ${fmtNum(selected.total_30d_usd)}`} usd
                    </span>
                  </div>
                </div>

                <div>
                  <p className="text-xs font-medium text-theme-muted uppercase mb-2">Contacto</p>
                  <div className="p-4 bg-theme-bg rounded-xl grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div>
                      <p className="text-xs text-theme-muted flex items-center gap-1 mb-0.5"><Phone size={12} /> Teléfono</p>
                      <p className="text-sm font-medium text-theme-heading">{selected.work_phone || '—'}</p>
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-theme-muted flex items-center gap-1 mb-0.5"><Mail size={12} /> Email</p>
                      <p className="text-sm font-medium text-theme-heading truncate">{selected.work_email || '—'}</p>
                    </div>
                    <div>
                      <p className="text-xs text-theme-muted flex items-center gap-1 mb-0.5"><Percent size={12} /> Comisión</p>
                      <p className="text-sm font-medium text-theme-heading">{selected.commission_pct ?? 0}%</p>
                      <p className="text-[11px] text-theme-muted">Se edita inline en la tabla</p>
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div>
                {histLoading ? (
                  <Skeleton count={4} className="h-10 w-full" />
                ) : !hist ? (
                  <EmptyState title="Sin historial" subtitle="No se pudo cargar la actividad del médico." />
                ) : (
                  <>
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 mb-4">
                      <div className="p-2.5 bg-theme-bg rounded-xl">
                        <p className="text-[11px] text-theme-muted flex items-center gap-1 mb-0.5"><CalendarDays size={12} /> Citas totales</p>
                        <p className="font-heading text-base text-theme-heading">{fmtNum(hist.totales.citas_total, 0)}</p>
                      </div>
                      <div className="p-2.5 bg-theme-bg rounded-xl">
                        <p className="text-[11px] text-theme-muted flex items-center gap-1 mb-0.5"><ClipboardList size={12} /> Visitas totales</p>
                        <p className="font-heading text-base text-theme-heading">{fmtNum(hist.totales.visitas_total, 0)}</p>
                      </div>
                      <div className="p-2.5 bg-theme-bg rounded-xl">
                        <p className="text-[11px] text-theme-muted flex items-center gap-1 mb-0.5"><ShoppingCart size={12} /> Líneas recetadas</p>
                        <p className="font-heading text-base text-theme-heading">{fmtNum(hist.totales.ventas_total_lineas, 0)}</p>
                      </div>
                      <div className="p-2.5 bg-theme-bg rounded-xl">
                        <p className="text-[11px] text-theme-muted flex items-center gap-1 mb-0.5"><DollarSign size={12} /> Monto recetado</p>
                        <p className="font-heading text-base text-theme-heading">{fmtMoney(hist.totales.monto_total)}</p>
                      </div>
                    </div>
                    <div className="flex flex-wrap gap-1.5 mb-3">
                      {([
                        { key: 'citas', label: 'Citas', icon: <CalendarDays size={14} className="mr-1" /> },
                        { key: 'visitas', label: 'Visitas', icon: <FileText size={14} className="mr-1" /> },
                        { key: 'ventas', label: 'Ventas recetadas', icon: <ShoppingCart size={14} className="mr-1" /> },
                      ] as const).map((s) => (
                        <button
                          key={s.key}
                          type="button"
                          onClick={() => setHistSection(s.key)}
                          className={`px-3 py-1.5 text-xs font-medium rounded-full transition inline-flex items-center ${
                            histSection === s.key ? 'bg-theme-accent text-theme-inverse' : 'bg-theme-accent-bg text-theme-heading hover:bg-theme-bg'
                          }`}
                        >
                          {s.icon}{s.label}
                        </button>
                      ))}
                    </div>

                    {histSection === 'citas' && (
                      hist.citas.length === 0 ? (
                        <EmptyState title="Sin citas" subtitle="Este médico no tiene citas registradas." />
                      ) : (
                        <div className="overflow-x-auto max-h-[50vh] overflow-y-auto">
                          <table className="w-full text-sm">
                            <thead className="bg-theme-bg text-theme-muted text-xs uppercase">
                              <tr>
                                <th className="text-left px-3 py-2">Fecha</th>
                                <th className="text-left px-3 py-2">Hora</th>
                                <th className="text-left px-3 py-2">Paciente</th>
                                <th className="text-left px-3 py-2">Servicio</th>
                                <th className="text-left px-3 py-2">Estado</th>
                              </tr>
                            </thead>
                            <tbody className="divide-y divide-theme-border">
                              {hist.citas.map((c) => (
                                <tr key={c.id} className="hover:bg-theme-bg">
                                  <td className="px-3 py-2 text-theme-heading whitespace-nowrap">{c.date || '—'}</td>
                                  <td className="px-3 py-2 text-theme-muted">{c.time || '—'}</td>
                                  <td className="px-3 py-2 text-theme-heading">{c.patient}</td>
                                  <td className="px-3 py-2 text-theme-muted">{c.service}</td>
                                  <td className="px-3 py-2"><StateBadge map={CITA_STATE} state={c.state} /></td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      )
                    )}

                    {histSection === 'visitas' && (
                      hist.visitas.length === 0 ? (
                        <EmptyState title="Sin visitas" subtitle="Este médico no tiene visitas registradas." />
                      ) : (
                        <div className="overflow-x-auto max-h-[50vh] overflow-y-auto">
                          <table className="w-full text-sm">
                            <thead className="bg-theme-bg text-theme-muted text-xs uppercase">
                              <tr>
                                <th className="text-left px-3 py-2">Fecha</th>
                                <th className="text-left px-3 py-2">Paciente</th>
                                <th className="text-left px-3 py-2">Motivo</th>
                                <th className="text-left px-3 py-2">Estado</th>
                              </tr>
                            </thead>
                            <tbody className="divide-y divide-theme-border">
                              {hist.visitas.map((v) => (
                                <tr key={v.id} className="hover:bg-theme-bg">
                                  <td className="px-3 py-2 text-theme-heading whitespace-nowrap">{v.date_start || '—'}</td>
                                  <td className="px-3 py-2 text-theme-heading">{v.patient}</td>
                                  <td className="px-3 py-2 text-theme-muted">{v.motivo || '—'}</td>
                                  <td className="px-3 py-2"><StateBadge map={VISITA_STATE} state={v.state} /></td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      )
                    )}

                    {histSection === 'ventas' && (
                      hist.ventas.length === 0 ? (
                        <EmptyState title="Sin ventas recetadas" subtitle="Este médico no tiene líneas recetadas." />
                      ) : (
                        <div className="overflow-x-auto max-h-[50vh] overflow-y-auto">
                          <table className="w-full text-sm">
                            <thead className="bg-theme-bg text-theme-muted text-xs uppercase">
                              <tr>
                                <th className="text-left px-3 py-2">Folio</th>
                                <th className="text-left px-3 py-2">Fecha</th>
                                <th className="text-left px-3 py-2">Paciente</th>
                                <th className="text-left px-3 py-2">Servicio / Artículo</th>
                                <th className="text-right px-3 py-2">Subtotal</th>
                                <th className="text-left px-3 py-2">Estado</th>
                              </tr>
                            </thead>
                            <tbody className="divide-y divide-theme-border">
                              {hist.ventas.map((l) => (
                                <tr key={l.id} className="hover:bg-theme-bg">
                                  <td className="px-3 py-2 text-theme-heading whitespace-nowrap">{l.venta}</td>
                                  <td className="px-3 py-2 text-theme-muted whitespace-nowrap">{l.date || '—'}</td>
                                  <td className="px-3 py-2 text-theme-heading">{l.patient}</td>
                                  <td className="px-3 py-2 text-theme-muted">{l.item}</td>
                                  <td className="px-3 py-2 text-right text-theme-heading">{fmtMoney(l.subtotal)}</td>
                                  <td className="px-3 py-2"><StateBadge map={VENTA_STATE} state={l.state} /></td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      )
                    )}
                  </>
                )}
              </div>
            )}
          </div>
        )}
      </Modal>
    </Layout>
  );
};

export default Medicos;
