"use client";
import { useState } from "react";
import { useStore, uid, pushFeed, findPatient, currentDoctor, sponsorFor, patientBalance } from "@/lib/store";
import { allergyConflict, budgetSplit, fdate, mxn, addDays, nextPaidThru } from "@/lib/logic";
import { CLAIM_STEPS, type Appointment, type BudgetItem, type PayMethod } from "@/lib/types";
import { useUI, WaBubble, Pill } from "./ui";
import { ReceiptDoc, PrescriptionDoc, ReferralDoc, InsurerFormDoc } from "./docs";

/* ---------- Recordatorio de WhatsApp ---------- */
export function reminderText(s: ReturnType<typeof useStore>["s"], a: Appointment) {
  const p = findPatient(s, a.patientId)!;
  const sp = sponsorFor(s, "wa");
  return `Hola ${p.name.split(" ")[0]} 👋, te recordamos tu cita en ${s.clinic.name}:\n📅 ${fdate(a.date)} a las ${a.time}\n🦷 ${a.reason}\n📍 ${s.clinic.addr}\n\nResponde 1 para confirmar o 2 para reagendar.${sp ? `\n\n— ${sp.msg} (patrocinado)` : ""}`;
}

export function ReminderModal({ id }: { id: string }) {
  const { s, mutate } = useStore();
  const { close, toast } = useUI();
  const a = s.appointments.find((x) => x.id === id)!;
  const name = findPatient(s, a.patientId)!.name;
  return (
    <>
      <h2>Recordatorio por WhatsApp</h2>
      <WaBubble text={reminderText(s, a)} reply={a.status === "confirmada" ? "1" : undefined} />
      <p className="note">En producción se envía con WhatsApp Cloud API usando una plantilla aprobada por Meta, 24 h antes de la cita.</p>
      <div className="row">
        <button className="btn pri" onClick={() => { mutate((d) => { const x = d.appointments.find((y) => y.id === id)!; if (x.status === "pendiente") x.status = "recordatorio"; }); close(); toast("Recordatorio enviado a " + name); }}>Enviar ahora</button>
        <button className="btn" onClick={() => { mutate((d) => { d.appointments.find((y) => y.id === id)!.status = "confirmada"; pushFeed(d, `${name} confirmó por WhatsApp`, "ok"); }); close(); toast("El paciente confirmó la cita"); }}>Simular respuesta “1”</button>
        <button className="btn" onClick={close}>Cerrar</button>
      </div>
    </>
  );
}

/* ---------- Nueva cita ---------- */
export function ApptForm({ patientId, date, time, onSaved }: { patientId?: string; date: string; time?: string; onSaved?: (date: string) => void }) {
  const { s, mutate } = useStore();
  const { close, toast } = useUI();
  const [pid, setPid] = useState(patientId ?? s.patients[0].id);
  const [f, setF] = useState({ date, time: time ?? "10:00", dur: 60, doctorId: s.doctorId, reason: findPatient(s, pid)?.next[0]?.name ?? "Consulta y diagnóstico", wa: true });
  const save = () => {
    mutate((d) => { d.appointments.push({ id: uid(), patientId: pid, doctorId: f.doctorId, date: f.date, time: f.time, dur: f.dur, reason: f.reason || "Consulta", status: "pendiente", source: "recepcion" }); });
    close(); onSaved?.(f.date); toast("Cita agendada" + (f.wa ? " · recordatorio programado" : ""));
  };
  return (
    <>
      <h2>Nueva cita</h2>
      <div className="fgrid">
        <label className="f">Paciente<select value={pid} onChange={(e) => setPid(e.target.value)}>{s.patients.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</select></label>
        <label className="f">Doctor<select value={f.doctorId} onChange={(e) => setF({ ...f, doctorId: e.target.value })}>{s.doctors.map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}</select></label>
        <label className="f">Fecha<input type="date" value={f.date} onChange={(e) => setF({ ...f, date: e.target.value })} /></label>
        <label className="f">Hora<input type="time" value={f.time} onChange={(e) => setF({ ...f, time: e.target.value })} /></label>
        <label className="f">Duración (min)<select value={f.dur} onChange={(e) => setF({ ...f, dur: +e.target.value })}>{[30, 45, 60, 90, 120].map((n) => <option key={n}>{n}</option>)}</select></label>
      </div>
      <label className="f">Motivo<input value={f.reason} onChange={(e) => setF({ ...f, reason: e.target.value })} /></label>
      <label className="chk"><input type="checkbox" checked={f.wa} onChange={(e) => setF({ ...f, wa: e.target.checked })} /> Programar recordatorio por WhatsApp 24 h antes</label>
      <div className="row"><button className="btn pri" onClick={save}>Agendar</button><button className="btn" onClick={close}>Cancelar</button></div>
    </>
  );
}

/* ---------- Paciente nuevo ---------- */
export function NewPatientForm({ onCreated }: { onCreated: (id: string) => void }) {
  const { mutate } = useStore();
  const { close, toast } = useUI();
  const [f, setF] = useState({ name: "", tel: "", age: "", sex: "F" as "F" | "M", alergias: "Ninguna" });
  const save = () => {
    if (!f.name.trim()) return toast("Escribe el nombre del paciente");
    const id = uid();
    mutate((d) => {
      d.patients.push({ id, name: f.name.trim(), tel: f.tel, email: "", age: Number(f.age) || 0, sex: f.sex,
        hist: { motivo: "", diabetes: false, hiper: false, cardio: false, coag: false, embarazo: false, alergias: f.alergias, medact: "", ta: "", fc: "", explor: "", dx: "", consent: false },
        teeth: {}, procs: [], next: [], rx: [], studies: [], budgets: [], pays: [] });
    });
    close(); onCreated(id); toast("Paciente creado");
  };
  return (
    <>
      <h2>Nuevo paciente</h2>
      <div className="fgrid">
        <label className="f">Nombre completo<input value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} autoFocus /></label>
        <label className="f">Teléfono (WhatsApp)<input inputMode="tel" value={f.tel} onChange={(e) => setF({ ...f, tel: e.target.value })} /></label>
        <label className="f">Edad<input type="number" value={f.age} onChange={(e) => setF({ ...f, age: e.target.value })} /></label>
        <label className="f">Sexo<select value={f.sex} onChange={(e) => setF({ ...f, sex: e.target.value as "F" | "M" })}><option value="F">Femenino</option><option value="M">Masculino</option></select></label>
      </div>
      <label className="f">Alergias<input value={f.alergias} onChange={(e) => setF({ ...f, alergias: e.target.value })} /></label>
      <div className="row"><button className="btn pri" onClick={save}>Crear y abrir historia clínica</button><button className="btn" onClick={close}>Cancelar</button></div>
    </>
  );
}

/* ---------- Cobro ---------- */
export function ChargeForm({ patientId }: { patientId?: string }) {
  const { s, mutate, ctx } = useStore();
  const { open, toast } = useUI();
  const [pid, setPid] = useState(patientId ?? s.patients[0].id);
  const p = findPatient(s, pid)!;
  const due = patientBalance(p, ctx).due;
  const [f, setF] = useState({ amount: String(due || 500), method: "Efectivo" as PayMethod, concept: due ? "Abono a plan de tratamiento" : "Consulta y diagnóstico" });
  const save = () => {
    const amount = Number(f.amount);
    if (!(amount > 0)) return toast("Escribe un monto mayor a cero");
    const folio = s.folio + 1;
    mutate((d) => {
      d.folio = folio;
      d.patients.find((x) => x.id === pid)!.pays.push({ folio, date: d.today, amount, method: f.method, concept: f.concept || "Pago" });
      pushFeed(d, `${p.name} pagó ${mxn(amount)}`, "ok");
    });
    setTimeout(() => open(<ReceiptDoc folio={folio} />), 0);
  };
  return (
    <>
      <h2>Registrar cobro</h2>
      <label className="f">Paciente<select value={pid} onChange={(e) => setPid(e.target.value)}>{s.patients.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}</select></label>
      <div className="fgrid">
        <label className="f">Monto (MXN)<input type="number" min={1} step="0.01" value={f.amount} onChange={(e) => setF({ ...f, amount: e.target.value })} /></label>
        <label className="f">Forma de pago<select value={f.method} onChange={(e) => setF({ ...f, method: e.target.value as PayMethod })}>{["Efectivo", "Tarjeta", "Transferencia"].map((m) => <option key={m}>{m}</option>)}</select></label>
      </div>
      <label className="f">Concepto<input value={f.concept} onChange={(e) => setF({ ...f, concept: e.target.value })} /></label>
      <p className="muted" style={{ margin: 0, fontSize: ".85rem" }}>Saldo actual: <b className="mono">{mxn(due)}</b></p>
      <div className="row"><button className="btn pri" onClick={save}>Cobrar y emitir recibo</button></div>
    </>
  );
}

/* ---------- Receta ---------- */
export function RxForm({ patientId }: { patientId: string }) {
  const { s, mutate } = useStore();
  const { open, toast, close } = useUI();
  const p = findPatient(s, patientId)!;
  const [sel, setSel] = useState(s.meds[0]);
  const [rows, setRows] = useState<{ name: string; ind: string }[]>([]);
  const [notes, setNotes] = useState("");
  const save = () => {
    if (!rows.length) return toast("Agrega al menos un medicamento");
    const id = uid();
    mutate((d) => { d.patients.find((x) => x.id === patientId)!.rx.push({ id, date: d.today, doctorId: d.doctorId, meds: rows.map((r) => ({ ...r, ind: r.ind || "Según indicación" })), notes }); });
    setTimeout(() => open(<PrescriptionDoc patientId={patientId} rxId={id} />), 0);
  };
  const hasAllergy = p.hist.alergias && p.hist.alergias !== "Ninguna";
  return (
    <>
      <h2>Nueva receta · {p.name}</h2>
      <p className="muted" style={{ margin: 0, fontSize: ".85rem" }}>La firma {currentDoctor(s).name}.</p>
      {hasAllergy && <Pill tone="bad">Alergia registrada: {p.hist.alergias}</Pill>}
      {rows.map((r, i) => (
        <div key={i} className="panel" style={{ padding: 10 }}>
          <div className="spread"><b>{r.name}</b><button className="btn sm" onClick={() => setRows(rows.filter((_, k) => k !== i))}>Quitar</button></div>
          {allergyConflict(p.hist.alergias, r.name) && <div style={{ margin: "6px 0" }}><Pill tone="bad">Posible alergia: revisa antes de recetar</Pill></div>}
          <label className="f" style={{ marginTop: 6 }}>Dosis, frecuencia y duración<input placeholder="Ej. 1 cada 8 h por 5 días" value={r.ind} onChange={(e) => setRows(rows.map((x, k) => (k === i ? { ...x, ind: e.target.value } : x)))} /></label>
        </div>
      ))}
      <div className="row">
        <select value={sel} onChange={(e) => setSel(e.target.value)} style={{ maxWidth: 300 }} aria-label="Medicamento">{s.meds.map((m) => <option key={m}>{m}</option>)}</select>
        <button className="btn" onClick={() => setRows([...rows, { name: sel, ind: "" }])}>Agregar medicamento</button>
      </div>
      <label className="f">Indicaciones generales<textarea value={notes} onChange={(e) => setNotes(e.target.value)} /></label>
      <p className="note">La dosis y la duración las escribe el dentista. El sistema solo avisa si un medicamento puede chocar con una alergia registrada.</p>
      <div className="row"><button className="btn pri" onClick={save}>Guardar y ver receta</button><button className="btn" onClick={close}>Cancelar</button></div>
    </>
  );
}

/* ---------- Presupuesto ---------- */
export function BudgetForm({ patientId }: { patientId: string }) {
  const { s, mutate } = useStore();
  const { close, toast } = useUI();
  const [items, setItems] = useState<BudgetItem[]>([]);
  const [tooth, setTooth] = useState("");
  const [svc, setSvc] = useState(s.services[0].name);
  const total = items.reduce((a, i) => a + Number(i.price), 0);
  return (
    <>
      <h2>Nuevo presupuesto · {findPatient(s, patientId)!.name}</h2>
      {items.length ? items.map((i, k) => (
        <div key={k} className="spread" style={{ background: "var(--sunk)", padding: "6px 10px", borderRadius: 7 }}>
          <span><span className="mono">{i.tooth || "—"}</span> {i.name}</span>
          <span className="row"><input type="number" aria-label="Precio" value={i.price} onChange={(e) => setItems(items.map((x, j) => (j === k ? { ...x, price: Number(e.target.value) || 0 } : x)))} style={{ width: 110 }} />
            <button className="btn sm" aria-label="Quitar" onClick={() => setItems(items.filter((_, j) => j !== k))}>×</button></span>
        </div>
      )) : <p className="empty">Agrega tratamientos.</p>}
      <div className="row">
        <input placeholder="Pieza" aria-label="Pieza" value={tooth} onChange={(e) => setTooth(e.target.value)} style={{ width: 80 }} />
        <select value={svc} onChange={(e) => setSvc(e.target.value)} style={{ maxWidth: 280 }} aria-label="Servicio">{s.services.map((c) => <option key={c.id}>{c.name}</option>)}</select>
        <button className="btn" onClick={() => setItems([...items, { tooth, name: svc, price: s.services.find((c) => c.name === svc)!.price }])}>Agregar</button>
      </div>
      <div className="spread"><b>Total a precio particular</b><b className="mono">{mxn(total)}</b></div>
      <p className="muted" style={{ margin: 0, fontSize: ".85rem" }}>El descuento de membresía y lo que cubre la aseguradora se calculan al guardar.</p>
      <div className="row">
        <button className="btn pri" onClick={() => { if (!items.length) return toast("Agrega al menos un tratamiento"); mutate((d) => { d.patients.find((x) => x.id === patientId)!.budgets.push({ id: uid(), date: d.today, status: "pendiente", items }); }); close(); toast("Presupuesto guardado"); }}>Guardar presupuesto</button>
        <button className="btn" onClick={close}>Cancelar</button>
      </div>
    </>
  );
}

/* ---------- Trámite con aseguradora ---------- */
export function ClaimModal({ id }: { id: string }) {
  const { s, mutate, ctx } = useStore();
  const { close, open } = useUI();
  const c = s.claims.find((x) => x.id === id)!;
  const p = findPatient(s, c.patientId)!;
  const ins = s.insurers.find((i) => i.id === c.insurerId)!;
  const b = p.budgets.find((x) => x.id === c.budgetId)!;
  const split = budgetSplit(p, b, ctx);
  const ok = c.docs.filter(Boolean).length;
  return (
    <>
      <h2>Trámite {ins.name} · {p.name}</h2>
      <div className="muted">Póliza <span className="mono">{p.ins?.policy || "por capturar"}</span> · Titular {p.ins?.holder}</div>
      <div className="row">{CLAIM_STEPS.map((st, i) => <Pill key={st} tone={i < c.step ? "ok" : i === c.step ? "info" : "mut"}>{st}</Pill>)}</div>
      <div className="spread panel" style={{ background: "var(--sunk)", padding: 10 }}>
        <span>Paga {ins.name}: <b className="mono">{mxn(split.insPay)}</b></span><span>Paga el paciente: <b className="mono">{mxn(split.patPay)}</b></span>
      </div>
      <h3>Requisitos ({ok}/{ins.reqs.length})</h3>
      {ins.reqs.map((r, i) => (
        <label key={i} className="chk"><input type="checkbox" checked={!!c.docs[i]} onChange={(e) => mutate((d) => { d.claims.find((x) => x.id === id)!.docs[i] = e.target.checked; })} /> {r}</label>
      ))}
      <h3>Formatos prellenados</h3>
      <div className="row">{ins.forms.map((f, i) => <button key={f} className="btn sm" onClick={() => open(<InsurerFormDoc claimId={id} formIndex={i} onBack={() => open(<ClaimModal id={id} />)} />)}>{f}</button>)}</div>
      {ok < ins.reqs.length && <p className="note">Faltan {ins.reqs.length - ok} documentos. Los trámites incompletos suelen ser rechazados.</p>}
      <div className="row">
        {c.step < CLAIM_STEPS.length - 1 && (
          <button className="btn pri" onClick={() => mutate((d) => { const x = d.claims.find((y) => y.id === id)!; x.step++; pushFeed(d, `Trámite ${ins.name} de ${p.name}: ${CLAIM_STEPS[x.step]}`, x.step === 5 ? "ok" : "info"); })}>Marcar: {CLAIM_STEPS[c.step + 1]}</button>
        )}
        <button className="btn" onClick={close}>Cerrar</button>
      </div>
    </>
  );
}

/* ---------- Orden de estudio ---------- */
export function ReferralForm({ labId, patientId }: { labId?: string; patientId?: string }) {
  const { s, mutate } = useStore();
  const { open, close, toast } = useUI();
  const [pid, setPid] = useState(patientId ?? s.patients[0].id);
  const [lid, setLid] = useState(labId ?? s.labs[0].id);
  const lab = s.labs.find((l) => l.id === lid)!;
  const [picked, setPicked] = useState<string[]>([lab.studies[0].name]);
  const p = findPatient(s, pid)!;
  const [reason, setReason] = useState(p.hist.dx || p.hist.motivo || "");
  const save = () => {
    if (!picked.length) return toast("Elige al menos un estudio");
    const id = uid();
    mutate((d) => { d.referrals.push({ id, patientId: pid, labId: lid, doctorId: d.doctorId, date: d.today, studies: picked, reason, step: 0 }); pushFeed(d, `Orden de estudio para ${p.name}`); });
    setTimeout(() => open(<ReferralDoc id={id} />), 0);
  };
  return (
    <>
      <h2>Orden de estudio</h2>
      <div className="fgrid">
        <label className="f">Paciente<select value={pid} onChange={(e) => setPid(e.target.value)}>{s.patients.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}</select></label>
        <label className="f">Laboratorio<select value={lid} onChange={(e) => { setLid(e.target.value); setPicked([s.labs.find((l) => l.id === e.target.value)!.studies[0].name]); }}>{s.labs.map((l) => <option key={l.id} value={l.id}>{l.name}</option>)}</select></label>
      </div>
      <div className="eyebrow">Estudios · {lab.disc}% de descuento por convenio</div>
      {lab.studies.map((st) => (
        <label key={st.name} className="chk">
          <input type="checkbox" checked={picked.includes(st.name)} onChange={(e) => setPicked(e.target.checked ? [...picked, st.name] : picked.filter((x) => x !== st.name))} />
          {st.name} <span className="mono muted">{mxn(st.price * (1 - lab.disc / 100))}</span>
        </label>
      ))}
      <label className="f">Motivo o diagnóstico presuntivo<input value={reason} onChange={(e) => setReason(e.target.value)} /></label>
      <div className="row"><button className="btn pri" onClick={save}>Generar orden</button><button className="btn" onClick={close}>Cancelar</button></div>
    </>
  );
}

/* ---------- Membresías ---------- */
export function EnrollForm({ patientId }: { patientId?: string }) {
  const { s, mutate } = useStore();
  const { open, close } = useUI();
  const candidates = s.patients.filter((p) => !p.mem);
  const [pid, setPid] = useState(patientId ?? candidates[0]?.id ?? "");
  const [plan, setPlan] = useState(s.membershipPlans[0].id);
  const [auto, setAuto] = useState(true);
  if (!candidates.length) return <><h2>Inscribir a membresía</h2><p>Todos los pacientes ya tienen membresía.</p><button className="btn" onClick={close}>Cerrar</button></>;
  const save = () => {
    const folio = s.folio + 1;
    mutate((d) => {
      const m = d.membershipPlans.find((x) => x.id === plan)!;
      const p = d.patients.find((x) => x.id === pid)!;
      p.mem = { planId: m.id, since: d.today, paidThru: addDays(d.today, 30), used: {} };
      d.folio = folio;
      p.pays.push({ folio, date: d.today, amount: m.price, method: "Tarjeta", concept: `Membresía ${m.name} · 1er mes`, membership: true });
      pushFeed(d, `${p.name} se inscribió a ${m.name}`, "ok");
    });
    setTimeout(() => open(<ReceiptDoc folio={folio} />), 0);
  };
  return (
    <>
      <h2>Inscribir a membresía</h2>
      <label className="f">Paciente<select value={pid} onChange={(e) => setPid(e.target.value)}>{candidates.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}</select></label>
      {s.membershipPlans.map((m) => (
        <label key={m.id} className="panel chk" style={{ padding: 10 }}>
          <input type="radio" name="plan" checked={plan === m.id} onChange={() => setPlan(m.id)} />
          <span><b>{m.name}</b> · <span className="mono">{mxn(m.price)}/mes</span><br /><small className="muted">{m.disc}% de descuento · {m.extra}</small></span>
        </label>
      ))}
      <label className="chk"><input type="checkbox" checked={auto} onChange={(e) => setAuto(e.target.checked)} /> Cargo automático mensual a tarjeta</label>
      <div className="row"><button className="btn pri" onClick={save}>Inscribir y cobrar primer mes</button><button className="btn" onClick={close}>Cancelar</button></div>
    </>
  );
}

export function useMembershipPayment() {
  const { s, mutate } = useStore();
  const { open } = useUI();
  return (patientId: string) => {
    const folio = s.folio + 1;
    mutate((d) => {
      const p = d.patients.find((x) => x.id === patientId)!;
      const m = d.membershipPlans.find((x) => x.id === p.mem!.planId)!;
      p.mem!.paidThru = nextPaidThru(p.mem!.paidThru, d.today);
      d.folio = folio;
      p.pays.push({ folio, date: d.today, amount: m.price, method: "Tarjeta", concept: `Mensualidad ${m.name}`, membership: true });
      pushFeed(d, `${p.name} pagó su mensualidad de ${m.name}`, "ok");
    });
    setTimeout(() => open(<ReceiptDoc folio={folio} />), 0);
  };
}
