"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { Medicine, Vitals } from "./_types";

export function Badge({ tone = "secondary", children }: { tone?: "warning" | "success" | "danger" | "info" | "secondary"; children: React.ReactNode }) {
  return <span className={`badge text-bg-${tone}`}>{children}</span>;
}

export function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
  return (
    <label className="form-label w-100 mb-2">
      <span className="d-block small fw-semibold mb-1">{label}</span>
      {children}
      {hint && <span className="d-block text-muted small mt-1">{hint}</span>}
    </label>
  );
}

export function TextInput(props: React.InputHTMLAttributes<HTMLInputElement>) {
  return <input {...props} className={"form-control form-control-sm " + (props.className || "")} />;
}
export function TextArea(props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
  return <textarea {...props} className={"form-control form-control-sm " + (props.className || "")} />;
}
export function Select(props: React.SelectHTMLAttributes<HTMLSelectElement>) {
  return <select {...props} className={"form-select form-select-sm " + (props.className || "")} />;
}

export function Toast({ message, tone }: { message: string; tone: "success" | "error" }) {
  if (!message) return null;
  return <div className={`alert alert-${tone === "success" ? "success" : "danger"} py-2 px-3 small`}>{message}</div>;
}

/* --------------------------- Search & select --------------------------- */
export function SearchSelect({ catalog, placeholder, onSelect, exclude = [], allowCustom = false }: {
  catalog: string[]; placeholder?: string; onSelect: (v: string) => void; exclude?: string[]; allowCustom?: boolean;
}) {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const boxRef = useRef<HTMLDivElement>(null);

  const results = useMemo(() => {
    const q = query.trim().toLowerCase();
    const pool = catalog.filter((c) => !exclude.includes(c));
    if (!q) return pool.slice(0, 6);
    return pool.filter((c) => c.toLowerCase().includes(q)).slice(0, 8);
  }, [query, catalog, exclude]);

  useEffect(() => {
    const onDocClick = (e: MouseEvent) => { if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false); };
    document.addEventListener("mousedown", onDocClick);
    return () => document.removeEventListener("mousedown", onDocClick);
  }, []);

  const commitCustom = () => {
    const v = query.trim();
    if (!v) return;
    onSelect(v);
    setQuery("");
    setOpen(false);
  };

  return (
    <div className="position-relative" ref={boxRef}>
      <TextInput
        value={query} placeholder={placeholder}
        onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
        onFocus={() => setOpen(true)}
        onKeyDown={(e) => { if (allowCustom && e.key === "Enter") { e.preventDefault(); commitCustom(); } }}
      />
      {open && (results.length > 0 || (allowCustom && query.trim())) && (
        <div className="position-absolute w-100 bg-white border rounded shadow-sm mt-1" style={{ zIndex: 20, maxHeight: 220, overflowY: "auto" }}>
          {results.map((r) => (
            <button key={r} type="button"
              onMouseDown={(e) => { e.preventDefault(); onSelect(r); setQuery(""); setOpen(false); }}
              className="dropdown-item small py-1">
              {r}
            </button>
          ))}
          {allowCustom && query.trim() && !results.includes(query.trim()) && (
            <button type="button" onMouseDown={(e) => { e.preventDefault(); commitCustom(); }}
              className="dropdown-item small py-1 fw-semibold text-primary">
              + Add &quot;{query.trim()}&quot;
            </button>
          )}
          {results.length === 0 && !allowCustom && <div className="px-3 py-2 small text-muted">No matches.</div>}
        </div>
      )}
    </div>
  );
}

/* Medicine-specific search: filters on name + generic, richer dropdown row */
export function MedicineSearchSelect({ catalog, onSelect, placeholder }: {
  catalog: Medicine[]; onSelect: (label: string) => void; placeholder?: string;
}) {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const boxRef = useRef<HTMLDivElement>(null);

  const label = (m: Medicine) => (m.generic ? `${m.name} (${m.generic})` : m.name);

  const results = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return catalog.slice(0, 6);
    return catalog.filter((m) => `${m.name} ${m.generic}`.toLowerCase().includes(q)).slice(0, 8);
  }, [query, catalog]);

  useEffect(() => {
    const onDocClick = (e: MouseEvent) => { if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false); };
    document.addEventListener("mousedown", onDocClick);
    return () => document.removeEventListener("mousedown", onDocClick);
  }, []);

  return (
    <div className="position-relative" ref={boxRef}>
      <TextInput value={query} placeholder={placeholder || "Search & select a medicine to add…"}
        onChange={(e) => { setQuery(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} />
      {open && results.length > 0 && (
        <div className="position-absolute w-100 bg-white border rounded shadow-sm mt-1" style={{ zIndex: 20, maxHeight: 240, overflowY: "auto" }}>
          {results.map((m) => (
            <button key={m.id} type="button"
              onMouseDown={(e) => { e.preventDefault(); onSelect(label(m)); setQuery(""); setOpen(false); }}
              className="dropdown-item py-1">
              <div className="small fw-semibold">{m.name}</div>
              <div className="small text-muted">{m.generic}</div>
            </button>
          ))}
        </div>
      )}
      {open && results.length === 0 && (
        <div className="position-absolute w-100 bg-white border rounded shadow-sm mt-1 px-3 py-2 small text-muted" style={{ zIndex: 20 }}>
          No matches — add it in the medicine library below.
        </div>
      )}
    </div>
  );
}

export function SuggestTags({ catalog, values, onChange, placeholder, tone = "primary" }: {
  catalog: string[]; values: string[]; onChange: (v: string[]) => void; placeholder?: string; tone?: "primary" | "danger";
}) {
  const add = (v: string) => { if (!values.includes(v)) onChange([...values, v]); };
  const remove = (v: string) => onChange(values.filter((x) => x !== v));
  return (
    <div>
      <SearchSelect catalog={catalog} placeholder={placeholder} onSelect={add} exclude={values} allowCustom />
      {values.length > 0 && (
        <div className="d-flex flex-wrap gap-2 mt-2">
          {values.map((v) => (
            <span key={v} className={`badge text-bg-${tone === "danger" ? "danger" : "light"} border d-inline-flex align-items-center gap-1`}>
              {v}
              <button type="button" onClick={() => remove(v)} className="btn-close btn-close-sm" style={{ fontSize: "0.55rem" }} aria-label="Remove" />
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

/* Free-text repeatable list (no catalog) — for Provisional / Differential diagnosis */
export function QuickAddList({ values, onChange, placeholder }: {
  values: string[]; onChange: (v: string[]) => void; placeholder?: string;
}) {
  const [draft, setDraft] = useState("");
  const commit = () => {
    const v = draft.trim();
    if (!v) return;
    onChange([...values, v]);
    setDraft("");
  };
  const remove = (idx: number) => onChange(values.filter((_, i) => i !== idx));
  return (
    <div>
      <TextInput
        value={draft} placeholder={placeholder}
        onChange={(e) => setDraft(e.target.value)}
        onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commit(); } }}
      />
      {values.length > 0 && (
        <ul className="list-unstyled mt-2 mb-0">
          {values.map((v, idx) => (
            <li key={idx} className="d-flex align-items-center justify-content-between small bg-light rounded px-2 py-1 mb-1">
              <span>{v}</span>
              <button onClick={() => remove(idx)} className="btn-close btn-close-sm" aria-label="Remove" />
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

/* -------------------------------- Vitals -------------------------------- */
export function VitalsForm({ vitals, onChange }: { vitals: Vitals; onChange: (v: Vitals) => void }) {
  const set = (k: keyof Vitals) => (v: string) => onChange({ ...vitals, [k]: v });
  const cells: { k: keyof Vitals; label: string; ph: string }[] = [
    { k: "bp", label: "BP (mmHg)", ph: "120/80" }, { k: "pulse", label: "Pulse (/min)", ph: "78" },
    { k: "temp", label: "Temp (°F)", ph: "98.6" }, { k: "spo2", label: "SpO2 (%)", ph: "98" },
    { k: "weight", label: "Weight (kg)", ph: "70" }, { k: "height", label: "Height (cm)", ph: "170" },
    { k: "rr", label: "Resp. rate", ph: "16" },
  ];
  return (
    <div className="row g-2">
      {cells.map((c) => (
        <div className="col-6 col-md-3" key={c.k}>
          <span className="d-block small text-muted mb-1">{c.label}</span>
          <input value={vitals[c.k]} placeholder={c.ph} onChange={(e) => set(c.k)(e.target.value)} className="form-control form-control-sm" />
        </div>
      ))}
    </div>
  );
}
