"use client";
import { useState } from "react";

// ─── Data ──────────────────────────────────────────────────────────────────

const TRIGGERS = [
  { id: "booking_created", label: "New Booking",  icon: "📅", grad: "from-emerald-500 to-teal-500",   ring: "ring-emerald-400", bg: "bg-emerald-50",  border: "border-emerald-200", text: "text-emerald-700" },
  { id: "no_show",         label: "No-Show",      icon: "😟", grad: "from-amber-500 to-orange-500",   ring: "ring-amber-400",   bg: "bg-amber-50",    border: "border-amber-200",   text: "text-amber-700"   },
  { id: "completed",       label: "After Visit",  icon: "✅", grad: "from-blue-500 to-sky-500",       ring: "ring-blue-400",    bg: "bg-blue-50",     border: "border-blue-200",    text: "text-blue-700"    },
  { id: "custom",          label: "Custom Goal",  icon: "⚡", grad: "from-violet-500 to-fuchsia-500", ring: "ring-violet-400",  bg: "bg-violet-50",   border: "border-violet-200",  text: "text-violet-700"  },
] as const;
type TriggerId = typeof TRIGGERS[number]["id"];

const CLINIC_ICONS: Record<string, string> = {
  "Medical Clinic":      "🏥",
  "Dental Clinic":       "🦷",
  "Beauty & Aesthetics": "💆",
  "Physiotherapy":       "🏃",
  "Mental Health":       "🧠",
  "Pediatrics":          "👶",
  "Ophthalmology":       "👁️",
  "Dermatology":         "🔬",
};

const EXAMPLES: Record<TriggerId, Record<string, string[]>> = {
  booking_created: {
    "Medical Clinic":      ["Confirm the appointment, share a pre-visit checklist, and ask the patient to arrive 10 minutes early", "Welcome the patient, collect updated allergy info, and send directions to the clinic", "Confirm the booking, offer to reschedule if needed, and send prep instructions"],
    "Dental Clinic":       ["Confirm the teeth-cleaning, remind patient to avoid eating 1h before, and ask them to bring their insurance card", "Confirm the filling appointment, explain what to expect, and ask about any concerns", "Welcome a new dental patient, confirm their booking, and send first-visit prep instructions"],
    "Beauty & Aesthetics": ["Confirm the Botox appointment, send pre-treatment care instructions, and ask about allergies or medications", "Confirm the filler session, remind the client to avoid alcohol 24h before, and offer easy rescheduling", "Confirm the laser treatment booking, send sun-exposure warnings, and collect skin history"],
    "Physiotherapy":       ["Confirm the session, send parking instructions, and remind the patient what to wear", "Confirm the first physio appointment, explain what to bring, and ask about current pain level", "Confirm the follow-up session and send the home exercise reminder for that day"],
    "Mental Health":       ["Gently confirm the therapy session, reassure the patient, and share what to expect", "Confirm the appointment, send a calming pre-session note, and share the cancellation policy", "Welcome a new client, confirm their booking, and answer common first-session questions"],
    "Pediatrics":          ["Confirm the child's appointment, remind parents what to bring, and ask about current symptoms", "Confirm the vaccination appointment and reassure parents about what to expect afterward", "Confirm the check-up and ask parents to note any questions they want to raise with the doctor"],
    "Ophthalmology":       ["Confirm the eye exam, remind patient to bring glasses or contacts, and ask if they drive", "Confirm the dilation appointment, warn patient to bring sunglasses and arrange a driver", "Confirm the LASIK consultation and send the pre-assessment checklist"],
    "Dermatology":         ["Confirm the skin consultation, ask about medications, and send a photo guide of what to document", "Confirm the mole-removal appointment, send prep instructions, and remind to avoid sun exposure", "Confirm the acne treatment session and remind patient to stop retinoids 5 days before"],
  },
  no_show: {
    "Medical Clinic":      ["Reach out empathetically, ask why the patient missed, and offer one-tap rebooking", "Check if the patient is okay, express concern, and help them reschedule within 2 taps", "Follow up with a caring message, explain why the visit matters, and make rebooking easy"],
    "Dental Clinic":       ["Follow up on the missed cleaning, gently explain why regular visits matter, and offer the next slot", "Reach out warmly and ask if they'd like to reschedule or need any help", "Send an empathetic message, offer a same-week slot, and remind them about dental health"],
    "Beauty & Aesthetics": ["Follow up warmly, let the client know their slot is open again, and offer priority rebooking", "Ask if everything is okay and offer a small incentive to rebook", "Re-engage the client with a friendly message and make rebooking effortless with one reply"],
    "Physiotherapy":       ["Check in with the patient, ask if they're okay, and reschedule at a more convenient time", "Follow up on the missed session, ask about their pain level, and get them back on schedule", "Reach out with care, remind them of their recovery progress, and rebook the next session"],
    "Mental Health":       ["Send a gentle, non-judgmental check-in and offer easy flexible rebooking", "Reach out with warmth, ask if the patient needs support, and offer a flexible reschedule", "Follow up softly without pressure and leave the door open to return"],
    "Pediatrics":          ["Follow up with parents, ask if the child is okay, and help reschedule the missed check-up", "Reach out warmly after the missed vaccination and explain why it's important", "Check in with the family and offer flexible rescheduling"],
    "Ophthalmology":       ["Follow up on the missed eye exam, remind patient that vision health matters, and rebook quickly", "Reach out, offer the next available morning slot, and confirm in one reply", "Remind patient their eye health check is overdue and offer simple rebooking"],
    "Dermatology":         ["Follow up on the missed appointment, ask if they need to reschedule, and offer the next slot", "Remind the patient about their ongoing treatment plan and rebook within one reply", "Send a caring note after the missed skin check and explain the importance of follow-through"],
  },
  completed: {
    "Medical Clinic":      ["Check how the patient feels after their visit, share next steps, and book the follow-up", "Follow up 24h later, ask if they have questions, and remind them about their prescription", "Send a recovery check-in, collect feedback, and schedule the next appointment"],
    "Dental Clinic":       ["Check pain levels after the procedure, send aftercare tips, and remind about the next check-up", "Follow up after the filling or extraction, ask if swelling reduced, and share recovery guidance", "Send a post-cleaning care reminder, ask for a review, and book the next visit"],
    "Beauty & Aesthetics": ["Follow up 3 days after treatment, check results, send aftercare instructions, and ask for a review", "Check in 48h after the Botox session, ask about any bruising, and share post-treatment care tips", "Follow up after the filler, ask how the client feels, and offer a loyalty discount on the next visit"],
    "Physiotherapy":       ["Check the patient's pain score after the session, send the home exercise video, and confirm next visit", "Follow up on recovery, ask about new discomfort, and adjust the next session plan", "Send the post-session exercise plan, track completion, and encourage their recovery goal"],
    "Mental Health":       ["Send a gentle check-in the day after, share a coping tip, and remind about the next appointment", "Follow up with a brief mood check and offer a resource related to what was discussed", "Send a caring post-session note and offer a quick journaling prompt"],
    "Pediatrics":          ["Check on the child after their visit, ask parents about any reactions, and send care instructions", "Follow up after vaccinations, ask about side effects, and reassure parents", "Send a milestone update after the check-up and book the next visit"],
    "Ophthalmology":       ["Follow up after LASIK surgery with daily aftercare instructions for the first week", "Check vision recovery, answer common questions, and book the 1-week follow-up", "Ask if the new prescription feels comfortable and schedule the next annual exam"],
    "Dermatology":         ["Follow up after mole removal, check healing, and share wound care instructions", "Check in after acne treatment, ask about skin reaction, and share the daily skincare routine", "Follow up 3 days after the procedure and confirm the next session"],
  },
  custom: {
    "Medical Clinic":      ["Re-engage patients who haven't visited in 3 months with a personalised health check reminder", "Run a health awareness campaign and invite patients to book a free screening", "Send post-discharge instructions to recently hospitalised patients"],
    "Dental Clinic":       ["Re-engage patients overdue for their 6-month check-up with a friendly nudge and easy booking", "Run a whitening promotion and invite existing patients to book a consultation", "Send a back-to-school dental check-up campaign targeting parents"],
    "Beauty & Aesthetics": ["Re-engage clients who haven't booked in 2 months with a personalised special offer", "Run a seasonal promotion and invite clients to book (summer glow, winter hydration)", "Send a birthday-month special offer to clients with upcoming birthdays"],
    "Physiotherapy":       ["Send weekly home exercise reminders between sessions to keep patients on track", "Re-engage discharged patients after 3 months with a free check-in session offer", "Run a posture awareness campaign and invite office workers to book an assessment"],
    "Mental Health":       ["Send monthly wellness check-ins to previous patients to show continued support", "Run a stress-awareness campaign with helpful tips and a booking link", "Re-engage patients who cancelled twice with a gentle, pressure-free outreach"],
    "Pediatrics":          ["Send vaccine due-date reminders based on the child's birth date", "Re-engage families who haven't booked an annual check-up in over 12 months", "Run a back-to-school health check campaign targeting primary school children"],
    "Ophthalmology":       ["Send annual eye-exam reminders to patients whose last visit was over 12 months ago", "Run a blue-light awareness campaign for office workers and invite them to book", "Re-engage patients who picked up glasses 6 months ago to check their satisfaction"],
    "Dermatology":         ["Re-engage patients who finished acne treatment with a 3-month skin progress follow-up", "Send a summer skin-protection campaign with SPF tips and a mole-check booking link", "Run a monthly skin-care tip series ending with an invitation to book a consultation"],
  },
};

// ─── Component ─────────────────────────────────────────────────────────────

export default function GenerateFlowModal({
  onLoad,
  onClose,
  initialTemplateType,
  clinicType = "Medical Clinic",
}: {
  onLoad: (nodes: any[], edges: any[], name: string) => void;
  onClose: () => void;
  initialTemplateType?: string;
  clinicType?: string;
}) {
  const defaultTrigger = (TRIGGERS.find(t => t.id === initialTemplateType)?.id ?? "booking_created") as TriggerId;

  const [goal,     setGoal]     = useState("");
  const [language, setLanguage] = useState("English");
  const [loading,  setLoading]  = useState(false);
  const [error,    setError]    = useState("");

  const trig     = TRIGGERS.find(t => t.id === defaultTrigger)!;
  const examples = EXAMPLES[defaultTrigger]?.[clinicType] ?? EXAMPLES[defaultTrigger]?.["Medical Clinic"] ?? [];
  const clinicIcon = CLINIC_ICONS[clinicType] ?? "🏥";

  async function generate() {
    if (!goal.trim()) return;
    setLoading(true);
    setError("");
    try {
      const res = await fetch("/api/chatbot-canvas/generate-flow", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ goal: goal.trim(), clinicType, language, templateType: defaultTrigger }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error);
      onLoad(json.nodes, json.edges, json.suggestedName || goal);
    } catch (e: any) {
      setError(e.message || "Generation failed — please try again.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
      <div
        className="bg-white rounded-3xl shadow-2xl flex flex-col overflow-hidden modal-enter"
        style={{ width: 520, maxHeight: "88vh" }}
      >

        {/* ── Header ── */}
        <div className={`bg-gradient-to-r ${trig.grad} px-6 py-5 shrink-0`}>
          <div className="flex items-start gap-3">
            <div className="w-12 h-12 rounded-2xl bg-white/20 flex items-center justify-center text-2xl shrink-0">
              🪄
            </div>
            <div className="flex-1">
              <h2 className="text-white font-bold text-[16px]">AI Flow Generator</h2>
              {/* Show exactly what we know — trigger + clinic */}
              <div className="flex items-center gap-2 mt-1.5 flex-wrap">
                <span className="flex items-center gap-1 bg-white/20 rounded-full px-2.5 py-1 text-white text-[11px] font-bold">
                  {trig.icon} {trig.label}
                </span>
                <span className="text-white/50 text-[11px]">·</span>
                <span className="flex items-center gap-1 bg-white/20 rounded-full px-2.5 py-1 text-white text-[11px] font-bold">
                  {clinicIcon} {clinicType}
                </span>
              </div>
            </div>
            <button onClick={onClose} className="text-white/60 hover:text-white text-xl leading-none p-1 mt-0.5">✕</button>
          </div>
        </div>

        {/* ── Body ── */}
        <div className="flex-1 overflow-y-auto p-5 space-y-4">

          {/* Examples */}
          <div>
            <p className={`text-[10px] font-black uppercase tracking-widest mb-2.5 ${trig.text}`}>
              💡 Pick an example goal or write your own
            </p>
            <div className="space-y-2">
              {examples.map((ex) => {
                const selected = goal === ex;
                return (
                  <button
                    key={ex}
                    onClick={() => { setGoal(ex); setError(""); }}
                    className={`w-full text-left px-4 py-3 rounded-2xl border-2 text-[12px] leading-relaxed transition-all duration-150 ${
                      selected
                        ? `${trig.bg} ${trig.border} ${trig.text} font-semibold ring-2 ${trig.ring}`
                        : "bg-gray-50 border-gray-100 text-gray-600 hover:bg-gray-100 hover:border-gray-200"
                    }`}
                  >
                    <span className={`mr-2 ${selected ? "" : "text-gray-300"}`}>→</span>
                    {ex}
                    {selected && <span className="ml-2 text-base">✓</span>}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Divider */}
          <div className="flex items-center gap-3">
            <div className="flex-1 h-px bg-gray-100" />
            <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider">or write your own</span>
            <div className="flex-1 h-px bg-gray-100" />
          </div>

          {/* Custom goal */}
          <div className="relative">
            <textarea
              rows={3}
              className="w-full border-2 border-gray-100 rounded-2xl px-4 py-3 text-[12px] text-gray-800 placeholder:text-gray-300 focus:outline-none focus:border-violet-300 transition resize-none leading-relaxed"
              value={goal}
              onChange={e => { setGoal(e.target.value); setError(""); }}
              placeholder="Describe exactly what you want this flow to do…"
            />
            {goal && (
              <button
                onClick={() => setGoal("")}
                className="absolute top-2.5 right-2.5 w-5 h-5 rounded-full bg-gray-100 hover:bg-gray-200 text-gray-400 text-[10px] flex items-center justify-center transition"
              >✕</button>
            )}
          </div>

          {/* Language */}
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-[11px] font-bold text-gray-400">Language:</span>
            {["English", "Arabic", "English + Arabic", "French"].map(l => (
              <button
                key={l}
                onClick={() => setLanguage(l)}
                className={`px-3 py-1.5 rounded-full text-[10px] font-bold border-2 transition ${
                  language === l
                    ? `${trig.bg} ${trig.border} ${trig.text}`
                    : "bg-gray-50 border-gray-100 text-gray-500 hover:border-gray-200"
                }`}
              >
                {l}
              </button>
            ))}
          </div>

          {/* Error */}
          {error && (
            <div className="flex items-center gap-2 px-3 py-2.5 bg-red-50 border border-red-100 rounded-xl text-[11px] text-red-600">
              ❌ {error}
            </div>
          )}

          {/* Loading */}
          {loading && (
            <div className={`flex items-center gap-4 px-4 py-4 rounded-2xl border ${trig.bg} ${trig.border}`}>
              <div className={`w-10 h-10 rounded-xl bg-gradient-to-br ${trig.grad} flex items-center justify-center text-lg shrink-0 animate-pulse shadow`}>
                🪄
              </div>
              <div className="flex-1">
                <p className={`text-[12px] font-bold ${trig.text}`}>Building your flow…</p>
                <p className="text-[10px] text-gray-400 mt-0.5">Usually takes 10–15 seconds</p>
              </div>
              <span className="w-4 h-4 rounded-full border-2 border-violet-400 border-t-transparent animate-spin shrink-0" />
            </div>
          )}

        </div>

        {/* ── Footer ── */}
        <div className="px-5 py-4 border-t border-gray-100 flex gap-3 shrink-0">
          <button
            onClick={onClose}
            className="px-5 py-3 rounded-2xl text-[12px] font-semibold text-gray-500 border border-gray-200 hover:bg-gray-50 transition"
          >
            Cancel
          </button>
          <button
            disabled={!goal.trim() || loading}
            onClick={generate}
            className={`flex-1 py-3 rounded-2xl text-[13px] font-bold text-white transition shadow-lg flex items-center justify-center gap-2 ${
              goal.trim() && !loading
                ? `bg-gradient-to-r ${trig.grad} hover:opacity-90`
                : "bg-gray-200 text-gray-400 cursor-not-allowed shadow-none"
            }`}
          >
            {loading ? "Generating…" : <><span>✨</span> Generate Flow</>}
          </button>
        </div>

      </div>
    </div>
  );
}
