"use client";
import { useEffect, useState } from "react";
import {
  Plus, X, Stethoscope, Clock, DollarSign, Sparkles, Search,
  ChevronDown, Check, FileText, Shield, Trash2, Edit3,
} from "lucide-react";

interface Treatment {
  id: string; name: string; duration: number; price: number | null;
  prepInstructions: string | null; aftercareInstructions: string | null;
}

const TPL = [
  { name: "Botox - Forehead", duration: 30, price: 350, prep: "Avoid blood thinners 48h before. Clean skin.", aftercare: "Don't touch 4h. No exercise 24h. Results in 3-7 days." },
  { name: "Dermal Fillers - Lips", duration: 45, price: 500, prep: "No blood thinners 48h. No dental 2 weeks.", aftercare: "Ice for swelling. No heat 48h. Resolves 5-7 days." },
  { name: "Laser Hair Removal", duration: 30, price: 200, prep: "Shave 24h before. No waxing 4 weeks. No sun 2 weeks.", aftercare: "Aloe vera. SPF 50+ for 2 weeks. No hot showers 24h." },
  { name: "Chemical Peel", duration: 45, price: 250, prep: "Stop retinoids 5-7 days. No waxing 1 week.", aftercare: "Moisturize. SPF 50+. Don't pick skin." },
  { name: "Microneedling", duration: 60, price: 300, prep: "No retinoids 3 days. Clean skin.", aftercare: "Red 24-48h. No makeup 24h. SPF 50+." },
  { name: "HydraFacial", duration: 45, price: 200, prep: "No special prep.", aftercare: "Pink 1-2h. Makeup OK. Use SPF." },
  { name: "PRP Hair Treatment", duration: 60, price: 600, prep: "Hydrate 48h. No anti-inflammatories 3 days.", aftercare: "No wash 24h. Soreness normal. Results 3-6 months." },
  { name: "Consultation", duration: 20, price: 0, prep: "Bring concerns and medications list.", aftercare: "Follow your personalized plan." },
];

export default function TreatmentsPage() {
  const [data, setData] = useState<Treatment[]>([]);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState<"add" | "tpl" | "edit" | null>(null);
  const [search, setSearch] = useState("");
  const [openId, setOpenId] = useState<string | null>(null);
  const [form, setForm] = useState({ name: "", duration: "30", price: "", prepInstructions: "", aftercareInstructions: "" });
  const [editId, setEditId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState<string | null>(null);
  const [toast, setToast] = useState<string | null>(null);

  const load = () => { fetch("/api/treatments").then(r => r.json()).then(setData).finally(() => setLoading(false)); };
  useEffect(() => { load(); }, []);
  const reset = () => { setForm({ name: "", duration: "30", price: "", prepInstructions: "", aftercareInstructions: "" }); setEditId(null); };

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(null), 3000); };

  const add = async (e: React.FormEvent) => {
    e.preventDefault(); setSaving(true);
    const payload = {
      name: form.name, duration: parseInt(form.duration),
      price: form.price ? parseFloat(form.price) : null,
      prepInstructions: form.prepInstructions || null,
      aftercareInstructions: form.aftercareInstructions || null,
    };

    if (editId) {
      await fetch(`/api/treatments/${editId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
      showToast(`${form.name} updated!`);
    } else {
      await fetch("/api/treatments", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
      showToast(`${form.name} added!`);
    }
    reset(); setModal(null); load(); setSaving(false);
  };

  const startEdit = (t: Treatment) => {
    setForm({
      name: t.name, duration: String(t.duration), price: t.price !== null ? String(t.price) : "",
      prepInstructions: t.prepInstructions || "", aftercareInstructions: t.aftercareInstructions || "",
    });
    setEditId(t.id);
    setModal("edit");
  };

  const handleDelete = async (t: Treatment) => {
    if (!confirm(`Delete "${t.name}"? This will deactivate it.`)) return;
    setDeleting(t.id);
    await fetch(`/api/treatments/${t.id}`, { method: "DELETE" });
    showToast(`${t.name} removed`);
    load(); setDeleting(null);
  };

  const addTpl = async (t: typeof TPL[0]) => {
    setSaving(true);
    await fetch("/api/treatments", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: t.name, duration: t.duration, price: t.price || null, prepInstructions: t.prep, aftercareInstructions: t.aftercare }),
    });
    showToast(`${t.name} added!`);
    load(); setSaving(false);
  };

  const filtered = data.filter(t => !search || t.name.toLowerCase().includes(search.toLowerCase()));
  const totalRevenue = data.reduce((sum, t) => sum + (t.price || 0), 0);

  return (
    <>
      {/* ── Toast ── */}
      {toast && (
        <div className="success-toast"><div className="toast-check"><Check size={12} className="text-white" /></div>{toast}</div>
      )}

      {/* ── Template Modal ── */}
      {modal === "tpl" && (
        <div className="modal-overlay" onClick={() => setModal(null)}>
          <div className="card p-6 w-full max-w-2xl max-h-[80vh] overflow-y-auto animate-scale-in" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-5">
              <div className="flex items-center gap-2.5">
                <div className="w-8 h-8 rounded-lg bg-primary-50 flex items-center justify-center">
                  <Sparkles size={16} className="text-primary-500" />
                </div>
                <div>
                  <h2 className="text-base font-bold">Treatment Templates</h2>
                  <p className="text-[11px] text-muted">Pre-built with prep & aftercare instructions</p>
                </div>
              </div>
              <button onClick={() => setModal(null)} className="p-1.5 hover:bg-gray-100 rounded-lg text-gray-400"><X size={18} /></button>
            </div>
            <div className="grid grid-cols-2 gap-3">
              {TPL.map((t, i) => {
                const exists = data.some(d => d.name === t.name);
                return (
                  <div key={i} onClick={() => !exists && !saving && addTpl(t)}
                    className={`flex items-center gap-3 p-4 rounded-xl border-2 transition-all ${
                      exists ? "border-gray-100 bg-gray-50/50 opacity-50 cursor-default"
                        : "border-gray-200 hover:border-primary-300 hover:bg-primary-50/30 cursor-pointer hover:shadow-md"
                    }`}>
                    <div className="w-10 h-10 rounded-xl bg-primary-50 flex items-center justify-center shrink-0">
                      <Stethoscope size={16} className="text-primary-600" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-dark truncate">{t.name}</p>
                      <p className="text-[11px] text-muted">{t.duration}min{t.price > 0 ? ` · $${t.price}` : " · Free"}</p>
                    </div>
                    {exists
                      ? <span className="text-[10px] text-emerald-500 font-semibold flex items-center gap-1"><Check size={12} /> Added</span>
                      : <Plus size={16} className="text-gray-300" />
                    }
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}

      {/* ── Add/Edit Modal ── */}
      {(modal === "add" || modal === "edit") && (
        <div className="modal-overlay" onClick={() => { setModal(null); reset(); }}>
          <div className="card p-6 w-full max-w-lg animate-scale-in" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-5">
              <div className="flex items-center gap-2.5">
                <div className="w-8 h-8 rounded-lg bg-primary-50 flex items-center justify-center">
                  {editId ? <Edit3 size={16} className="text-primary-600" /> : <Plus size={16} className="text-primary-600" />}
                </div>
                <h2 className="text-base font-bold">{editId ? "Edit Treatment" : "Add Treatment"}</h2>
              </div>
              <button onClick={() => { setModal(null); reset(); }} className="p-1.5 hover:bg-gray-100 rounded-lg text-gray-400"><X size={18} /></button>
            </div>
            <form onSubmit={add} className="space-y-4">
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5">Treatment Name *</label>
                <input type="text" value={form.name} onChange={e => setForm(p => ({ ...p, name: e.target.value }))}
                  placeholder="e.g. Botox - Forehead" required className="input" autoFocus />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">Duration (min)</label>
                  <div className="relative">
                    <Clock size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-300" />
                    <input type="number" value={form.duration} onChange={e => setForm(p => ({ ...p, duration: e.target.value }))} className="input pl-10" />
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">Price ($)</label>
                  <div className="relative">
                    <DollarSign size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-300" />
                    <input type="number" step="0.01" value={form.price} onChange={e => setForm(p => ({ ...p, price: e.target.value }))}
                      placeholder="0" className="input pl-10" />
                  </div>
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                  <span className="flex items-center gap-1.5"><FileText size={11} /> Prep Instructions</span>
                  <span className="text-gray-300 font-normal ml-1">— sent 3 days before appointment</span>
                </label>
                <textarea value={form.prepInstructions} onChange={e => setForm(p => ({ ...p, prepInstructions: e.target.value }))}
                  placeholder="e.g. Avoid blood thinners 48h before..." className="input" rows={2} />
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                  <span className="flex items-center gap-1.5"><Shield size={11} /> Aftercare Instructions</span>
                  <span className="text-gray-300 font-normal ml-1">— sent after treatment</span>
                </label>
                <textarea value={form.aftercareInstructions} onChange={e => setForm(p => ({ ...p, aftercareInstructions: e.target.value }))}
                  placeholder="e.g. Don't touch treated area for 4h..." className="input" rows={2} />
              </div>
              <div className="flex gap-2 pt-2">
                <button type="button" onClick={() => { setModal(null); reset(); }} className="btn-secondary flex-1">Cancel</button>
                <button type="submit" disabled={saving || !form.name} className="btn-primary flex-1">
                  {saving ? "Saving..." : editId ? "Save Changes" : "Add Treatment"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ═══════════════════════════════════════════ */}
      {/*                 PAGE CONTENT                */}
      {/* ═══════════════════════════════════════════ */}
      <div className="space-y-6 animate-fade-in">

        {/* ── Header ── */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <div className="flex items-center gap-3">
            <div className="w-10 sm:w-11 h-10 sm:h-11 rounded-xl bg-gradient-to-br from-primary-500 to-violet-600 flex items-center justify-center shadow-lg shadow-primary-500/20">
              <Stethoscope size={20} className="text-white" />
            </div>
            <div>
              <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-dark">Treatments</h1>
              <p className="text-xs sm:text-sm text-muted">{data.length} service{data.length !== 1 ? "s" : ""} offered</p>
            </div>
          </div>
          <div className="flex gap-2">
            <button onClick={() => setModal("tpl")} className="btn-secondary btn-sm"><Sparkles size={14} /> <span className="hidden sm:inline">Templates</span><span className="inline sm:hidden">Tpl</span></button>
            <button onClick={() => setModal("add")} className="btn-primary btn-sm"><Plus size={14} /> Add</button>
          </div>
        </div>

        {/* ── Summary Cards ── */}
        {data.length > 0 && (
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
            <div className="bg-primary-50 border border-primary-100 rounded-2xl p-4 flex items-center gap-3 transition-transform hover:scale-[1.02]">
              <div className="w-10 h-10 rounded-xl bg-primary-100 flex items-center justify-center">
                <Stethoscope size={18} className="text-primary-600" />
              </div>
              <div>
                <p className="text-2xl font-bold text-primary-700">{data.length}</p>
                <p className="text-[11px] text-primary-500 font-medium">Total Treatments</p>
              </div>
            </div>
            <div className="bg-emerald-50 border border-emerald-100 rounded-2xl p-4 flex items-center gap-3 transition-transform hover:scale-[1.02]">
              <div className="w-10 h-10 rounded-xl bg-emerald-100 flex items-center justify-center">
                <DollarSign size={18} className="text-emerald-600" />
              </div>
              <div>
                <p className="text-2xl font-bold text-emerald-700">
                  ${data.filter(t => t.price).length > 0 ? Math.round(totalRevenue / data.filter(t => t.price).length) : 0}
                </p>
                <p className="text-[11px] text-emerald-500 font-medium">Avg Price</p>
              </div>
            </div>
            <div className="bg-violet-50 border border-violet-100 rounded-2xl p-4 flex items-center gap-3 transition-transform hover:scale-[1.02]">
              <div className="w-10 h-10 rounded-xl bg-violet-100 flex items-center justify-center">
                <Clock size={18} className="text-violet-600" />
              </div>
              <div>
                <p className="text-2xl font-bold text-violet-700">
                  {data.length > 0 ? Math.round(data.reduce((s, t) => s + t.duration, 0) / data.length) : 0}m
                </p>
                <p className="text-[11px] text-violet-500 font-medium">Avg Duration</p>
              </div>
            </div>
          </div>
        )}

        {/* ── Search ── */}
        {data.length > 2 && (
          <div className="relative">
            <Search size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-gray-300" />
            <input type="text" value={search} onChange={e => setSearch(e.target.value)}
              placeholder="Search treatments..." className="input pl-10 py-2.5 text-sm" />
            {search && (
              <button onClick={() => setSearch("")} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-300 hover:text-gray-500">
                <X size={14} />
              </button>
            )}
          </div>
        )}

        {/* ── Treatment List ── */}
        {loading ? (
          <div className="flex flex-col items-center justify-center py-24 gap-3">
            <div className="w-8 h-8 border-[2.5px] border-primary-100 border-t-primary-500 rounded-full animate-spin" />
            <p className="text-xs text-gray-400">Loading treatments...</p>
          </div>
        ) : data.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-center">
            <div className="w-16 h-16 bg-primary-50 rounded-2xl flex items-center justify-center mb-4 animate-float">
              <Stethoscope size={28} className="text-primary-300" />
            </div>
            <h3 className="text-lg font-bold text-dark mb-1">No treatments yet</h3>
            <p className="text-sm text-gray-400 mb-6 max-w-sm">
              Add the services your clinic offers. Prep & aftercare instructions are sent automatically in WhatsApp reminders.
            </p>
            <div className="flex gap-3">
              <button onClick={() => setModal("tpl")} className="btn-secondary">
                <Sparkles size={14} /> Use Templates
              </button>
              <button onClick={() => setModal("add")} className="btn-primary">
                <Plus size={14} /> Add Custom
              </button>
            </div>
          </div>
        ) : (
          <div className="space-y-3">
            {filtered.map((t, i) => {
              const isOpen = openId === t.id;
              return (
                <div key={t.id}
                  className={`card card-flat overflow-hidden transition-opacity ${deleting === t.id ? "opacity-30" : ""}`}
                  style={{ animation: `fade-in 0.35s ease both`, animationDelay: `${i * 40}ms` }}>

                  {/* Main row */}
                  <div className="flex items-center gap-4 px-5 py-4 cursor-pointer hover:bg-gray-50/50 transition-colors group"
                    onClick={() => setOpenId(isOpen ? null : t.id)}>

                    {/* Icon */}
                    <div className="w-11 h-11 rounded-xl bg-gradient-to-br from-primary-50 to-primary-100 flex items-center justify-center shrink-0">
                      <Stethoscope size={18} className="text-primary-600" />
                    </div>

                    {/* Info */}
                    <div className="flex-1 min-w-0">
                      <p className="text-[15px] font-semibold text-dark">{t.name}</p>
                      <div className="flex items-center gap-4 mt-1">
                        <span className="flex items-center gap-1.5 text-[12px] text-gray-400">
                          <Clock size={12} /> {t.duration} min
                        </span>
                        {t.price !== null && t.price > 0 && (
                          <span className="text-[12px] font-bold text-dark">${t.price}</span>
                        )}
                        {t.price === 0 && (
                          <span className="text-[12px] text-emerald-500 font-medium">Free</span>
                        )}
                      </div>
                    </div>

                    {/* Badges + Actions + Arrow */}
                    <div className="flex items-center gap-2 shrink-0">
                      {t.prepInstructions && (
                        <span className="flex items-center gap-1 px-2 py-1 bg-blue-50 text-blue-600 text-[10px] font-semibold rounded-lg border border-blue-100">
                          <FileText size={10} /> Prep
                        </span>
                      )}
                      {t.aftercareInstructions && (
                        <span className="flex items-center gap-1 px-2 py-1 bg-emerald-50 text-emerald-600 text-[10px] font-semibold rounded-lg border border-emerald-100">
                          <Shield size={10} /> Aftercare
                        </span>
                      )}
                      {/* Edit/Delete — visible on hover */}
                      <div className="opacity-0 group-hover:opacity-100 transition-opacity flex gap-1 ml-1">
                        <button onClick={(e) => { e.stopPropagation(); startEdit(t); }}
                          className="p-1.5 rounded-lg text-gray-400 hover:text-primary-600 hover:bg-primary-50 transition-all" title="Edit">
                          <Edit3 size={14} />
                        </button>
                        <button onClick={(e) => { e.stopPropagation(); handleDelete(t); }}
                          className="p-1.5 rounded-lg text-gray-400 hover:text-red-500 hover:bg-red-50 transition-all" title="Delete">
                          <Trash2 size={14} />
                        </button>
                      </div>
                      <ChevronDown size={16}
                        className={`text-gray-300 transition-transform duration-300 ${isOpen ? "rotate-180" : ""}`} />
                    </div>
                  </div>

                  {/* Expanded details */}
                  {isOpen && (
                    <div className="px-5 pb-5 animate-fade-in">
                      <div className="grid grid-cols-2 gap-3 ml-0 sm:ml-[60px]">
                        <div className="bg-blue-50/50 rounded-xl p-4 border border-blue-100/50">
                          <div className="flex items-center gap-1.5 mb-2">
                            <FileText size={12} className="text-blue-500" />
                            <p className="text-[10px] font-bold text-blue-600 uppercase tracking-wider">Prep Instructions</p>
                          </div>
                          <p className="text-xs text-gray-600 leading-relaxed whitespace-pre-line">
                            {t.prepInstructions || "Not set — patients won't receive prep instructions."}
                          </p>
                        </div>
                        <div className="bg-emerald-50/50 rounded-xl p-4 border border-emerald-100/50">
                          <div className="flex items-center gap-1.5 mb-2">
                            <Shield size={12} className="text-emerald-500" />
                            <p className="text-[10px] font-bold text-emerald-600 uppercase tracking-wider">Aftercare Instructions</p>
                          </div>
                          <p className="text-xs text-gray-600 leading-relaxed whitespace-pre-line">
                            {t.aftercareInstructions || "Not set — patients won't receive aftercare instructions."}
                          </p>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </>
  );
}
