"use client";
import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from "react";
import { useStore } from "@/lib/store";
import { inkFor } from "@/lib/logic";
import type { ApptStatus } from "@/lib/types";

/* ---------- Avisos (toast) y ventana modal ---------- */
interface UI { toast: (t: string) => void; open: (node: ReactNode) => void; close: () => void }
const UICtx = createContext<UI | null>(null);

export function UIProvider({ children }: { children: ReactNode }) {
  const [toasts, setToasts] = useState<{ id: number; t: string }[]>([]);
  const [modal, setModal] = useState<ReactNode>(null);
  const toast = useCallback((t: string) => {
    const id = Date.now() + Math.random();
    setToasts((x) => [...x, { id, t }]);
    setTimeout(() => setToasts((x) => x.filter((y) => y.id !== id)), 2800);
  }, []);
  const close = useCallback(() => setModal(null), []);
  useEffect(() => {
    const k = (e: KeyboardEvent) => e.key === "Escape" && setModal(null);
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, []);
  return (
    <UICtx.Provider value={{ toast, open: setModal, close }}>
      {children}
      {modal && (
        <div className="scrim" onClick={(e) => e.target === e.currentTarget && close()}>
          <div className="modal" role="dialog" aria-modal="true">{modal}</div>
        </div>
      )}
      <div className="toasts" aria-live="polite">{toasts.map((x) => <div key={x.id} className="toast">{x.t}</div>)}</div>
    </UICtx.Provider>
  );
}
export function useUI() {
  const v = useContext(UICtx);
  if (!v) throw new Error("useUI fuera de UIProvider");
  return v;
}

/* ---------- Marca de la clínica ---------- */
export function BrandStyle() {
  const { s } = useStore();
  const { color, color2 } = s.clinic;
  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty("--brand", color);
    r.setProperty("--brand-ink", inkFor(color));
    r.setProperty("--brand2", color2);
  }, [color, color2]);
  return null;
}

export function LogoMark({ size = 36, inverted = false }: { size?: number; inverted?: boolean }) {
  const { s } = useStore();
  const c = s.clinic;
  return (
    <div className="logo-mark" style={{ width: size, height: size, fontSize: size * 0.36, ...(inverted ? { background: "var(--brand-ink)", color: "var(--brand)" } : {}) }}>
      {c.logo ? <img src={c.logo} alt={`Logotipo de ${c.name}`} /> : c.short}
    </div>
  );
}

/* ---------- Piezas pequeñas ---------- */
export function Pill({ tone = "mut", children }: { tone?: "ok" | "warn" | "bad" | "info" | "mut"; children: ReactNode }) {
  return <span className={`pill p-${tone}`}>{children}</span>;
}

export const APPT_STATUS: Record<ApptStatus, [string, "ok" | "info" | "warn" | "mut" | "bad"]> = {
  confirmada: ["Confirmada", "ok"],
  recordatorio: ["Recordatorio enviado", "info"],
  pendiente: ["Sin confirmar", "warn"],
  atendida: ["Atendida", "mut"],
  cancelada: ["Cancelada", "bad"],
};
export function ApptPill({ status }: { status: ApptStatus }) {
  const [l, t] = APPT_STATUS[status];
  return <Pill tone={t}>{l}</Pill>;
}

export function Kpi({ value, label, color, panel = true }: { value: ReactNode; label: ReactNode; color?: string; panel?: boolean }) {
  return (
    <div className={`kpi${panel ? " panel" : ""}`}>
      <b style={color ? { color } : undefined}>{value}</b>
      <span>{label}</span>
    </div>
  );
}

export function PageHead({ eyebrow, title, sub, children }: { eyebrow: string; title: ReactNode; sub?: ReactNode; children?: ReactNode }) {
  return (
    <div className="head">
      <div>
        <div className="eyebrow">{eyebrow}</div>
        <h1>{title}</h1>
        {sub && <p className="muted" style={{ margin: ".3em 0 0", maxWidth: "64ch" }}>{sub}</p>}
      </div>
      {children && <div className="row">{children}</div>}
    </div>
  );
}

export function Tabs<T extends string>({ tabs, value, onChange }: { tabs: [T, string][]; value: T; onChange: (t: T) => void }) {
  return (
    <div className="tabs" role="tablist">
      {tabs.map(([k, l]) => (
        <button key={k} className="tab" role="tab" aria-selected={k === value} onClick={() => onChange(k)}>{l}</button>
      ))}
    </div>
  );
}

export function Note({ children, style }: { children: ReactNode; style?: React.CSSProperties }) {
  return <p className="note" style={style}>{children}</p>;
}

export function WaBubble({ text, reply }: { text: string; reply?: string }) {
  return (
    <div className="wa">
      <div className="b">{text}</div>
      {reply && <div className="r">{reply}</div>}
    </div>
  );
}
