"use client";
import { useEffect, useState } from "react";
import { Badge } from "../ui";
import { Prescription, Visit, money, vitalsSummary } from "../_types";
import { listPrescriptions, listVisits } from "../_api";
import { useHms } from "../layout";
import PrescribeWorkspace from "../components/PrescribeWorkspace";
import PrintView from "../components/PrintView";

export default function DoctorPanelPage() {
  const { organizationId, userId, doctor } = useHms();
  const [visits, setVisits] = useState<Visit[]>([]);
  const [activeVisit, setActiveVisit] = useState<Visit | null>(null);
  const [filter, setFilter] = useState<"registered" | "prescribed" | "referred">("registered");
  const [printing, setPrinting] = useState<{ rx: Prescription; visit: Visit } | null>(null);
  const [viewingId, setViewingId] = useState<number | null>(null);

  useEffect(() => {
    listVisits(organizationId).then(setVisits);
  }, [organizationId]);

  const onVisitUpdated = (v: Visit) => setVisits((prev) => prev.map((x) => (x.id === v.id ? v : x)));

  const viewPrescription = async (v: Visit) => {
    setViewingId(v.id);
    try {
      const rxList = await listPrescriptions(organizationId, { visit: v.id });
      if (rxList[0]) setPrinting({ rx: rxList[0], visit: v });
    } finally {
      setViewingId(null);
    }
  };

  const queue = visits.filter((v) => v.status === "registered");
  const prescribedList = visits.filter((v) => v.status === "prescribed");
  const referredList = visits.filter((v) => v.status === "referred");
  const shown = filter === "registered" ? queue : filter === "prescribed" ? prescribedList : referredList;

  return (
    <div>
      <div className="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
        <div>
          <h5 className="mb-1">Doctor Panel</h5>
          <p className="text-muted small mb-0">Queue, prescribed and referred patients</p>
        </div>
        <span className="badge text-bg-primary">Dr. {doctor.name || "—"}</span>
      </div>

      <div className="row g-2 mb-3">
        {[
          { id: "registered" as const, label: "Queue", count: queue.length, tone: "warning" },
          { id: "prescribed" as const, label: "Prescribed", count: prescribedList.length, tone: "success" },
          { id: "referred" as const, label: "Referred", count: referredList.length, tone: "info" },
        ].map((s) => (
          <div className="col-4" key={s.id}>
            <button onClick={() => setFilter(s.id)} className={`btn w-100 ${filter === s.id ? `btn-outline-${s.tone}` : "btn-outline-secondary"}`}>
              <div className="fs-4 fw-bold">{s.count}</div>
              <div className="small text-uppercase">{s.label}</div>
            </button>
          </div>
        ))}
      </div>

      <div className="border rounded overflow-hidden">
        <div className="px-3 py-2 border-bottom bg-light d-flex justify-content-between align-items-center">
          <h6 className="mb-0 small text-capitalize">{filter === "registered" ? "Waiting" : filter}</h6>
          <Badge>{shown.length}</Badge>
        </div>
        <table className="table table-sm mb-0">
          <thead>
            <tr><th>Patient</th><th className="text-end">Fee</th><th className="text-end"></th></tr>
          </thead>
          <tbody>
            {shown.map((v) => (
              <tr key={v.id}>
                <td>
                  <div className="fw-medium">{v.patient_name} <span className="text-muted fw-normal">({v.patient_gender}, {v.patient_age ?? "—"}y)</span></div>
                  <div className="text-muted small">{v.code}</div>
                  {v.status === "referred" && v.referred_to_name && <div className="text-info small">→ {v.referred_to_name}</div>}
                  {vitalsSummary(v.vitals) && <div className="text-success small">{vitalsSummary(v.vitals)}</div>}
                </td>
                <td className="text-end">{money(v.net_amount)}</td>
                <td className="text-end text-nowrap">
                  {filter === "prescribed" && (
                    <button onClick={() => viewPrescription(v)} disabled={viewingId === v.id} className="btn btn-outline-primary btn-sm me-1">
                      {viewingId === v.id ? "Loading…" : "View"}
                    </button>
                  )}
                  <button onClick={() => setActiveVisit(v)} className="btn btn-primary btn-sm">
                    {filter === "registered" ? "Prescribe" : "Open"}
                  </button>
                </td>
              </tr>
            ))}
            {shown.length === 0 && <tr><td colSpan={3} className="text-center text-muted py-4">Nothing here.</td></tr>}
          </tbody>
        </table>
      </div>

      {activeVisit && (
        <PrescribeWorkspace
          visit={activeVisit} organizationId={organizationId} doctorId={userId} doctor={doctor}
          onClose={() => setActiveVisit(null)}
          onPrint={(rx, visit) => setPrinting({ rx, visit })}
          onVisitUpdated={(v) => { onVisitUpdated(v); setActiveVisit(null); }}
        />
      )}
      {printing && <PrintView rx={printing.rx} visit={printing.visit} doctor={doctor} onClose={() => setPrinting(null)} />}
    </div>
  );
}
