"use client";
import { useEffect, useState } from "react";
import { Badge, Field, Select, TextInput, Toast, VitalsForm } from "../ui";
import { EMPTY_VITALS, Visit, Vitals, money, vitalsSummary } from "../_types";
import { createVisit, listVisits } from "../_api";
import { useHms } from "../layout";

const STATUS_TONE: Record<string, "warning" | "success" | "danger" | "info" | "secondary"> = {
  registered: "warning", prescribed: "success", cancelled: "danger", referred: "info",
};

const EMPTY_FORM = { patient_name: "", patient_phone: "", patient_gender: "male", patient_age: "", patient_address: "" };

export default function RegistrationPage() {
  const { organizationId } = useHms();
  const [visits, setVisits] = useState<Visit[]>([]);
  const [form, setForm] = useState(EMPTY_FORM);
  const [fee, setFee] = useState("");
  const [discount, setDiscount] = useState("");
  const [vitals, setVitals] = useState<Vitals>(EMPTY_VITALS());
  const [toast, setToast] = useState("");
  const [submitting, setSubmitting] = useState(false);

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

  const set = (k: keyof typeof EMPTY_FORM) => (v: string) => setForm((p) => ({ ...p, [k]: v }));
  const net = Math.max((parseFloat(fee) || 0) - (parseFloat(discount) || 0), 0);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.patient_name.trim()) return;
    setSubmitting(true);
    try {
      const visit = await createVisit({
        organization: organizationId, ...form,
        visiting_fee: fee || "0", discount: discount || "0", net_amount: String(net),
        vitals, status: "registered",
      });
      setVisits((prev) => [visit, ...prev]);
      setToast(`Registered — ${form.patient_name} added to the doctor panel.`);
      setTimeout(() => setToast(""), 2500);
      setForm(EMPTY_FORM); setFee(""); setDiscount(""); setVitals(EMPTY_VITALS());
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="row g-4">
      <div className="col-12 col-lg-5">
        <h5 className="mb-1">Registration</h5>
        <p className="text-muted small mb-3">Register a patient visit, record vitals, set fee &amp; discount</p>
        <Toast message={toast} tone="success" />
        <form onSubmit={submit} className="border rounded p-3">
          <div className="mb-3"><Field label="Patient name"><TextInput value={form.patient_name} onChange={(e) => set("patient_name")(e.target.value)} required /></Field></div>
          <div className="row g-2 mb-3">
            <div className="col-4"><Field label="Phone"><TextInput value={form.patient_phone} onChange={(e) => set("patient_phone")(e.target.value)} /></Field></div>
            <div className="col-4">
              <Field label="Sex">
                <Select value={form.patient_gender} onChange={(e) => set("patient_gender")(e.target.value)}>
                  <option value="male">Male</option><option value="female">Female</option><option value="other">Other</option>
                </Select>
              </Field>
            </div>
            <div className="col-4"><Field label="Age"><TextInput value={form.patient_age} onChange={(e) => set("patient_age")(e.target.value)} /></Field></div>
          </div>
          <div className="mb-3"><Field label="Address"><TextInput value={form.patient_address} onChange={(e) => set("patient_address")(e.target.value)} /></Field></div>
          <div className="row g-2 mb-3">
            <div className="col-6"><Field label="Visiting fee"><TextInput value={fee} onChange={(e) => setFee(e.target.value)} placeholder="0.00" /></Field></div>
            <div className="col-6"><Field label="Discount"><TextInput value={discount} onChange={(e) => setDiscount(e.target.value)} placeholder="0.00" /></Field></div>
          </div>
          <div className="border-top pt-3 mb-3">
            <div className="small fw-semibold mb-2">Vitals <span className="text-muted fw-normal">— recorded by nurse, optional</span></div>
            <VitalsForm vitals={vitals} onChange={setVitals} />
          </div>
          <div className="d-flex justify-content-between align-items-center bg-light rounded px-3 py-2 mb-3">
            <span className="small fw-semibold">Net payable</span>
            <span className="fw-bold">{money(net)}</span>
          </div>
          <button type="submit" disabled={submitting} className="btn btn-primary w-100">{submitting ? "Registering…" : "Register patient"}</button>
        </form>
      </div>

      <div className="col-12 col-lg-7">
        <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">Registered patients</h6>
            <Badge>{visits.length}</Badge>
          </div>
          <div className="table-responsive">
            <table className="table table-sm mb-0">
              <thead>
                <tr>
                  <th>Patient</th>
                  <th className="text-end">Fee</th>
                  <th className="text-end">Disc.</th>
                  <th className="text-end">Net</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {visits.map((r) => (
                  <tr key={r.id}>
                    <td>
                      <div className="fw-medium">{r.patient_name}</div>
                      <div className="text-muted small">{r.code} · {r.patient_phone || "no phone"}</div>
                      {vitalsSummary(r.vitals) && <div className="text-success small">{vitalsSummary(r.vitals)}</div>}
                    </td>
                    <td className="text-end">{money(r.visiting_fee)}</td>
                    <td className="text-end">{money(r.discount)}</td>
                    <td className="text-end fw-semibold">{money(r.net_amount)}</td>
                    <td><Badge tone={STATUS_TONE[r.status] || "secondary"}>{r.status}</Badge></td>
                  </tr>
                ))}
                {visits.length === 0 && <tr><td colSpan={5} className="text-center text-muted py-4">No registrations yet.</td></tr>}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
