"use client";
import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useStore, findPatient } from "@/lib/store";
import { addDays, fdate } from "@/lib/logic";
import { ApptPill, PageHead, useUI, Kpi } from "@/components/ui";
import { ApptForm, ReminderModal } from "@/components/modals";

const HOURS = ["09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "16:00", "17:00", "18:00", "19:00"];

export default function AgendaPage() {
  const { s, mutate } = useStore();
  const { open, toast } = useUI();
  const router = useRouter();
  const [day, setDay] = useState(s.today);
  const [doc, setDoc] = useState<string>("todos");

  const days = Array.from({ length: 10 }, (_, i) => addDays(s.today, i - 1));
  const list = s.appointments
    .filter((a) => a.date === day && (doc === "todos" || a.doctorId === doc))
    .sort((a, b) => a.time.localeCompare(b.time));
  const pending = s.appointments.filter((a) => a.date >= s.today && a.date <= addDays(s.today, 1) && a.status === "pendiente");
  const tomorrow = s.appointments.filter((a) => a.date === addDays(s.today, 1));

  const attend = (id: string, pid: string) => {
    mutate((d) => { d.appointments.find((a) => a.id === id)!.status = "atendida"; });
    toast("Consulta iniciada: registra lo atendido en el odontograma");
    router.push(`/pacientes/${pid}?tab=odonto`);
  };

  return (
    <>
      <PageHead eyebrow="Agenda" title={fdate(day, { weekday: "long", day: "numeric", month: "long" })}>
        <select aria-label="Doctor" value={doc} onChange={(e) => setDoc(e.target.value)} style={{ maxWidth: 220 }}>
          <option value="todos">Todos los doctores</option>
          {s.doctors.map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}
        </select>
        <button className="btn" disabled={!pending.length}
          onClick={() => { mutate((d) => d.appointments.forEach((a) => { if (pending.some((p) => p.id === a.id)) a.status = "recordatorio"; })); toast(`${pending.length} recordatorios enviados`); }}>
          Enviar recordatorios ({pending.length})
        </button>
        <button className="btn pri" onClick={() => open(<ApptForm date={day} onSaved={setDay} />)}>Nueva cita</button>
      </PageHead>

      <div className="days">
        {days.map((d) => {
          const x = new Date(d + "T12:00:00Z");
          const n = s.appointments.filter((a) => a.date === d).length;
          return (
            <button key={d} className="day" aria-pressed={d === day} onClick={() => setDay(d)}>
              <small>{x.toLocaleDateString("es-MX", { weekday: "short", timeZone: "UTC" })}</small>
              <b>{x.getUTCDate()}</b>
              <small>{n ? `${n} cita${n > 1 ? "s" : ""}` : "—"}</small>
            </button>
          );
        })}
      </div>

      <div className="grid agrid">
        <section className="panel">
          <div className="slots">
            {HOURS.map((h) => {
              const a = list.find((x) => x.time.slice(0, 2) === h.slice(0, 2));
              if (!a)
                return (
                  <div key={h} className="slot"><time>{h}</time>
                    <button className="btn ghost sm free" style={{ justifySelf: "start" }} onClick={() => open(<ApptForm date={day} time={h} onSaved={setDay} />)}>+ Libre</button>
                  </div>
                );
              const p = findPatient(s, a.patientId)!;
              const dr = s.doctors.find((d) => d.id === a.doctorId);
              return (
                <div key={h} className="slot"><time>{a.time}</time>
                  <div className="appt">
                    <div>
                      <b>{p.name}</b>
                      <div className="muted" style={{ fontSize: ".88rem" }}>{a.reason} · {a.dur} min · {dr?.name.split(" ").slice(0, 2).join(" ")}</div>
                      <div className="row" style={{ marginTop: 4 }}><ApptPill status={a.status} />{a.source === "formulario" && <span className="pill p-mut">Formulario en línea</span>}{a.source === "whatsapp" && <span className="pill p-mut">WhatsApp</span>}</div>
                    </div>
                    <div className="row">
                      <button className="btn sm" onClick={() => open(<ReminderModal id={a.id} />)}>WhatsApp</button>
                      <Link className="btn sm" href={`/pacientes/${p.id}`}>Ficha</Link>
                      {a.status !== "atendida" && a.status !== "cancelada" && <button className="btn sm pri" onClick={() => attend(a.id, p.id)}>Atender</button>}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </section>
        <aside className="grid" style={{ alignContent: "start" }}>
          <Kpi value={list.length} label={`citas este día · ${list.filter((a) => a.status === "confirmada").length} confirmadas`} />
          <div className="panel">
            <h3>Mañana</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 8 }}>
              {tomorrow.length ? tomorrow.map((a) => (
                <div key={a.id} className="spread"><span><span className="mono">{a.time}</span> {findPatient(s, a.patientId)!.name}</span><ApptPill status={a.status} /></div>
              )) : <span className="muted">Sin citas</span>}
            </div>
          </div>
          <div className="panel">
            <h3>Recordatorio automático</h3>
            <p className="muted" style={{ fontSize: ".88rem", margin: ".4em 0 0" }}>Se envía 24 h antes por WhatsApp. El paciente responde 1 para confirmar o 2 para reagendar, y la cita cambia de estado sola.</p>
          </div>
        </aside>
      </div>
    </>
  );
}
