/* WORKLOAD PANEL — carga laboral de profesionales por dia
   Se renderiza como tab dentro de AdminView.
   Filtra por planta segun el prefijo del admin. */

const WL_STATUS = {
  confirmed:   { bg: 'bg-mint-50',  text: 'text-mint-700',  ring: 'ring-mint-200',  label: 'Confirmada' },
  completed:   { bg: 'bg-slate-50', text: 'text-slate-600', ring: 'ring-slate-200', label: 'Atendida' },
  cancelled:   { bg: 'bg-rose-50',  text: 'text-rose-700',  ring: 'ring-rose-200',  label: 'Cancelada' },
  no_show:     { bg: 'bg-amber-50', text: 'text-amber-700', ring: 'ring-amber-200', label: 'No asistio' },
  in_progress: { bg: 'bg-sky-50',   text: 'text-sky-700',   ring: 'ring-sky-200',   label: 'En consulta' },
};

function WorkloadPanel({ user }) {
  const [date, setDate]         = React.useState(new Date().toISOString().slice(0, 10));
  const [data, setData]         = React.useState(null);
  const [loading, setLoading]   = React.useState(true);
  const [expanded, setExpanded] = React.useState(null);

  function load(d) {
    setLoading(true);
    window.apiFetch(`/api/admin/workload?date=${d}`)
      .then(r => r.ok ? r.json() : null)
      .then(res => { if (res) setData(res); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }

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

  function shiftDate(days) {
    const d = new Date(date + 'T12:00:00');
    d.setDate(d.getDate() + days);
    const nd = d.toISOString().slice(0, 10);
    setDate(nd);
    load(nd);
  }

  const isToday = date === new Date().toISOString().slice(0, 10);
  const dateLabel = new Date(date + 'T12:00:00').toLocaleDateString('es-GT', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

  return (
    <div>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h2 className="text-[20px] font-semibold tracking-tight text-midnight-900">
            Carga laboral {data?.plant ? `(${data.plant})` : ''}
          </h2>
          <p className="text-[13px] text-slate-500 mt-0.5">Citas por profesional. Solo tu planta.</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => shiftDate(-1)}
            className="h-8 w-8 rounded-lg ring-1 ring-line bg-white hover:bg-paper grid place-items-center text-slate-500">
            <I.chevL className="h-3.5 w-3.5"/>
          </button>
          <div className="text-center min-w-[170px]">
            <div className="text-[12.5px] font-semibold text-midnight-900 capitalize">{dateLabel}</div>
            {!isToday && (
              <button onClick={() => { const t = new Date().toISOString().slice(0,10); setDate(t); load(t); }}
                className="text-[10.5px] text-mint-700 font-medium hover:text-mint-800">Hoy</button>
            )}
          </div>
          <button onClick={() => shiftDate(1)}
            className="h-8 w-8 rounded-lg ring-1 ring-line bg-white hover:bg-paper grid place-items-center text-slate-500">
            <I.chevR className="h-3.5 w-3.5"/>
          </button>
        </div>
      </div>

      {/* KPIs */}
      {data && (
        <div className="grid grid-cols-4 gap-3 mb-6">
          {[
            { l: 'Profesionales', v: data.totals.professionals, h: 'con agenda' },
            { l: 'Citas totales', v: data.totals.total_appointments, h: 'agendadas' },
            { l: 'Atendidas', v: data.totals.completed, h: 'completadas', color: 'text-mint-600' },
            { l: 'Pendientes', v: data.totals.pending, h: 'por atender', color: 'text-amber-600' },
          ].map((k, i) => (
            <div key={i} className="bg-white rounded-xl ring-1 ring-line p-4">
              <div className="text-[11px] text-slate-500">{k.l}</div>
              <div className={`text-[20px] font-semibold tnum mt-1 ${k.color || 'text-midnight-900'}`}>{k.v}</div>
              <div className="text-[10.5px] text-slate-400">{k.h}</div>
            </div>
          ))}
        </div>
      )}

      {loading && <div className="py-12 text-center text-[13px] text-slate-400">Cargando...</div>}

      {!loading && data && data.workload.length === 0 && (
        <div className="bg-white rounded-xl ring-1 ring-line p-8 text-center">
          <div className="text-[14px] font-semibold text-midnight-900">Sin profesionales con agenda</div>
          <div className="text-[12.5px] text-slate-500 mt-1">Prueba con otra fecha.</div>
        </div>
      )}

      {!loading && data && data.workload.length > 0 && (
        <div className="space-y-3">
          {data.workload.map(w => {
            const p = w.professional;
            const ini = p.initials || p.full_name.split(' ').map(n => n[0]).slice(0, 2).join('').toUpperCase();
            const isOpen = expanded === p.id;
            const pct = w.stats.total > 0 ? Math.round((w.stats.completed / w.stats.total) * 100) : 0;

            return (
              <div key={p.id} className="bg-white rounded-xl ring-1 ring-line overflow-hidden">
                {/* Row */}
                <div className="px-5 py-3.5 flex items-center gap-4 cursor-pointer hover:bg-paper/50 transition"
                  onClick={() => setExpanded(isOpen ? null : p.id)}>
                  <div className="h-10 w-10 rounded-lg bg-gradient-to-br from-midnight-700 to-midnight-900 text-white grid place-items-center text-[12px] font-semibold shrink-0">
                    {ini}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-[13.5px] font-semibold text-midnight-900">{p.full_name}</span>
                      <Badge tone="midnight">{p.specialty?.name || p.sub_specialty || ''}</Badge>
                    </div>
                    <div className="text-[11.5px] text-slate-500 mt-0.5">
                      {w.dayOff
                        ? <span className="text-slate-400 italic">No atiende este dia en tu planta</span>
                        : <>{p.room || ''}{w.schedule ? ` | ${w.schedule.start?.slice(0,5)} - ${w.schedule.end?.slice(0,5)}` : ''}</>
                      }
                    </div>
                  </div>

                  <div className="flex items-center gap-4 shrink-0 text-center">
                    <div>
                      <div className="text-[16px] font-bold tnum text-midnight-900">{w.stats.total}</div>
                      <div className="text-[9.5px] text-slate-400">total</div>
                    </div>
                    <div>
                      <div className="text-[16px] font-bold tnum text-mint-600">{w.stats.completed}</div>
                      <div className="text-[9.5px] text-slate-400">atendidas</div>
                    </div>
                    <div>
                      <div className="text-[16px] font-bold tnum text-amber-600">{w.stats.confirmed}</div>
                      <div className="text-[9.5px] text-slate-400">pendientes</div>
                    </div>
                    {w.stats.no_show > 0 && (
                      <div>
                        <div className="text-[16px] font-bold tnum text-rose-600">{w.stats.no_show}</div>
                        <div className="text-[9.5px] text-slate-400">no-show</div>
                      </div>
                    )}
                  </div>

                  <div className="w-[80px] shrink-0">
                    <div className="flex items-center justify-between text-[10px] mb-1">
                      <span className="text-slate-400">Progreso</span>
                      <span className="font-semibold tnum text-midnight-900">{pct}%</span>
                    </div>
                    <div className="h-1.5 rounded-full bg-slate-100 overflow-hidden">
                      <div className="h-full rounded-full bg-mint-400 transition-all" style={{ width: `${pct}%` }}/>
                    </div>
                  </div>

                  <svg viewBox="0 0 24 24" className={`h-4 w-4 text-slate-400 shrink-0 transition ${isOpen ? 'rotate-90' : ''}`} fill="none">
                    <path d="M9 5l7 7-7 7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </div>

                {/* Expanded */}
                {isOpen && (
                  <div className="border-t border-line">
                    {w.appointments.length === 0 && (
                      <div className="px-5 py-5 text-center text-[12px] text-slate-400">Sin citas agendadas</div>
                    )}
                    {w.appointments.map((a, i) => {
                      const time = new Date(a.start_at).toLocaleTimeString('es-GT', { hour: '2-digit', minute: '2-digit', hour12: false });
                      const pName = a.employee?.full_name || a.beneficiary?.name || 'Paciente';
                      const pCode = a.employee?.code || (a.beneficiary ? `Benef. (${a.beneficiary.relation})` : '');
                      const st = WL_STATUS[a.status] || WL_STATUS.confirmed;
                      const isBenef = !!a.beneficiary?.name && !a.employee;

                      return (
                        <div key={a.id} className={`px-5 py-2.5 flex items-center gap-3 text-[12.5px] ${i < w.appointments.length - 1 ? 'border-b border-line' : ''} hover:bg-paper/40`}>
                          <span className="font-mono tnum text-slate-500 w-11 shrink-0">{time}</span>
                          <span className="font-medium text-midnight-900 flex-1 min-w-0 truncate">{pName}</span>
                          {pCode && <span className="text-[11px] text-slate-400 tnum shrink-0">{pCode}</span>}
                          {isBenef && <span className="text-[9.5px] font-medium text-amber-600 bg-amber-50 ring-1 ring-amber-200 rounded-full px-1.5 py-0.5 shrink-0">Benef.</span>}
                          <span className="text-[11px] text-slate-500 shrink-0">{a.mode === 'telemedicina' ? 'Telemed' : 'Presencial'}</span>
                          <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium ring-1 ring-inset shrink-0 ${st.bg} ${st.text} ${st.ring}`}>
                            {st.label}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

window.WorkloadPanel = WorkloadPanel;
