"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { btn, input, Card, Badge } from "@/components/ui";
import { parseAssistedHints } from "@/lib/assist";
import { createWizardConference } from "./actions";

/* ── minimal typings for the Web Speech API ── */
type SpeechRecognitionLike = {
  lang: string; continuous: boolean; interimResults: boolean;
  onresult: ((e: { resultIndex: number; results: ArrayLike<{ 0: { transcript: string }; isFinal: boolean }> }) => void) | null;
  onend: (() => void) | null;
  onerror: ((e: { error: string }) => void) | null;
  start: () => void; stop: () => void;
};

const STEPS = ["Name it", "Tell us about it", "Conference dates", "Registration window", "Review & create"] as const;

const LOADER_LINES = [
  "🌐 Spinning up your public conference website…",
  "🎟️ Wiring the registration engine & QR tickets…",
  "🗓️ Preparing tracks, halls and the agenda builder…",
  "🎤 Setting up speaker pages & your directory…",
  "📺 Priming the live screen, polls and Q&A…",
  "🏅 Loading the certificate generator…",
  "✨ Polishing your workspace…",
];

const CATEGORY_LABELS: Record<string, string> = { TECH: "Tech", MEDICAL: "Medical", ACADEMIC: "Academic", GOVERNMENT: "Government", BUSINESS: "Business" };
const TYPE_LABELS: Record<string, string> = { PHYSICAL: "In-person", VIRTUAL: "Online", HYBRID: "Hybrid" };

export function ConferenceWizard({ userName }: { userName: string }) {
  const router = useRouter();
  const [step, setStep] = useState(0);
  const [title, setTitle] = useState("");
  const [about, setAbout] = useState("");
  const [startAt, setStartAt] = useState("");
  const [endAt, setEndAt] = useState("");
  const [regOpensAt, setRegOpensAt] = useState("");
  const [regClosesAt, setRegClosesAt] = useState("");
  const [error, setError] = useState("");

  // Voice input
  const [speechSupported, setSpeechSupported] = useState(false);
  const [listening, setListening] = useState(false);
  const recRef = useRef<SpeechRecognitionLike | null>(null);
  const aboutRef = useRef(about);
  aboutRef.current = about;

  useEffect(() => {
    const w = window as unknown as { SpeechRecognition?: new () => SpeechRecognitionLike; webkitSpeechRecognition?: new () => SpeechRecognitionLike };
    setSpeechSupported(Boolean(w.SpeechRecognition || w.webkitSpeechRecognition));
  }, []);

  const toggleListening = () => {
    if (listening) {
      recRef.current?.stop();
      return;
    }
    const w = window as unknown as { SpeechRecognition?: new () => SpeechRecognitionLike; webkitSpeechRecognition?: new () => SpeechRecognitionLike };
    const Ctor = w.SpeechRecognition || w.webkitSpeechRecognition;
    if (!Ctor) return;
    const rec = new Ctor();
    rec.lang = "en-IN";
    rec.continuous = true;
    rec.interimResults = true;
    let committed = aboutRef.current ? aboutRef.current.replace(/\s+$/, "") + " " : "";
    rec.onresult = (e) => {
      let interim = "";
      for (let i = e.resultIndex; i < e.results.length; i++) {
        const r = e.results[i];
        if (r.isFinal) committed += r[0].transcript.trim() + " ";
        else interim += r[0].transcript;
      }
      setAbout((committed + interim).replace(/\s+/g, " "));
    };
    rec.onend = () => setListening(false);
    rec.onerror = (e) => {
      setListening(false);
      if (e.error === "not-allowed") setError("Microphone access was blocked — type instead, or allow the mic and retry.");
    };
    recRef.current = rec;
    setError("");
    rec.start();
    setListening(true);
  };
  useEffect(() => () => recRef.current?.stop(), []);

  // Live assisted detections
  const hints = useMemo(() => parseAssistedHints(about), [about]);
  const detectedChips = [
    hints.category && `🏷 ${CATEGORY_LABELS[hints.category] ?? hints.category}`,
    hints.type && `🖥 ${TYPE_LABELS[hints.type] ?? hints.type}`,
    (hints.city || hints.state) && `📍 ${[hints.city, hints.state].filter(Boolean).join(", ")}`,
    hints.capacity && `👥 ~${hints.capacity} attendees`,
  ].filter(Boolean) as string[];

  // Creation loader
  const [creating, setCreating] = useState(false);
  const [loaderLine, setLoaderLine] = useState(0);
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    if (!creating) return;
    const lineTimer = setInterval(() => setLoaderLine((l) => (l + 1) % LOADER_LINES.length), 1100);
    const progTimer = setInterval(() => setProgress((p) => Math.min(p + Math.random() * 9 + 3, 96)), 320);
    return () => { clearInterval(lineTimer); clearInterval(progTimer); };
  }, [creating]);

  const validateStep = (): string => {
    if (step === 0 && title.trim().length < 3) return "Give your conference a name (at least 3 characters).";
    if (step === 2) {
      if (!startAt || !endAt) return "Pick both dates.";
      if (new Date(endAt) < new Date(startAt)) return "The end date must be on or after the start date.";
    }
    if (step === 3) {
      if (regOpensAt && regClosesAt && new Date(regClosesAt) < new Date(regOpensAt)) return "Registration must close after it opens.";
      if (regClosesAt && endAt && new Date(regClosesAt) > new Date(`${endAt}T23:59:59`)) return "Registration usually closes by the conference end date.";
    }
    return "";
  };

  const next = () => {
    const v = validateStep();
    if (v) { setError(v); return; }
    setError("");
    recRef.current?.stop();
    setStep((s) => Math.min(s + 1, STEPS.length - 1));
  };
  const back = () => { setError(""); setStep((s) => Math.max(s - 1, 0)); };

  const create = async () => {
    setError("");
    recRef.current?.stop();
    setCreating(true);
    setProgress(6);
    const minShow = new Promise((r) => setTimeout(r, 3200));
    const result = await createWizardConference({ title, about, startAt, endAt, regOpensAt, regClosesAt });
    await minShow;
    if (result.ok) {
      setProgress(100);
      setTimeout(() => router.push(`/dashboard/c/${result.id}?welcome=1`), 450);
    } else {
      setCreating(false);
      setProgress(0);
      setError(result.error);
    }
  };

  const fmt = (d: string) => (d ? new Date(d).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" }) : "—");

  /* ── Creation loader overlay ── */
  if (creating) {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-gradient-to-br from-indigo-500/95 via-violet-600/95 to-fuchsia-600/95 backdrop-blur-xl">
        <div className="w-full max-w-md px-6 text-center">
          <div className="relative mx-auto h-28 w-28">
            <span className="absolute inset-0 animate-ping rounded-3xl bg-white/20" style={{ animationDuration: "1.8s" }} />
            <span className="absolute inset-2 animate-pulse rounded-3xl bg-white/15" />
            <span className="absolute inset-0 flex items-center justify-center rounded-3xl text-6xl" style={{ animation: "spin 7s linear infinite" }}>✨</span>
          </div>
          <h2 className="mt-8 text-2xl font-extrabold text-white">Creating “{title.trim()}”</h2>
          <p className="mt-1 text-sm text-white/70">Hold on, {userName.split(" ")[0]} — this takes just a moment.</p>
          <div className="mt-6 h-2 overflow-hidden rounded-full bg-white/20">
            <div className="h-full rounded-full bg-white transition-all duration-300" style={{ width: `${progress}%` }} />
          </div>
          <p className="mt-4 min-h-6 text-sm font-medium text-white/90 transition-opacity">{LOADER_LINES[loaderLine]}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-2xl">
      {/* Progress */}
      <div className="mb-8">
        <div className="flex items-center justify-between text-[11px] font-semibold uppercase tracking-wider text-zinc-500">
          <span>Step {step + 1} of {STEPS.length}</span>
          <span>{STEPS[step]}</span>
        </div>
        <div className="mt-2 flex gap-1.5">
          {STEPS.map((_, i) => (
            <span key={i} className={`h-1.5 flex-1 rounded-full transition-all duration-500 ${i <= step ? "bg-gradient-to-r from-indigo-500 to-violet-500" : "bg-white/60"}`} />
          ))}
        </div>
      </div>

      <Card className="fx-pop-in p-6 sm:p-8" key={step}>
        {step === 0 && (
          <div>
            <h2 className="text-xl font-extrabold text-zinc-100">What's your conference called? ✨</h2>
            <p className="mt-1 text-sm text-zinc-500">Don't overthink it — you can rename it anytime.</p>
            <input
              autoFocus
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && next()}
              placeholder="India AI Conference 2027"
              className={`${input} mt-5 !py-4 !text-lg font-semibold`}
              maxLength={140}
            />
          </div>
        )}

        {step === 1 && (
          <div>
            <h2 className="text-xl font-extrabold text-zinc-100">Tell us about it 🎙️</h2>
            <p className="mt-1 text-sm text-zinc-500">
              {speechSupported
                ? "Tap the mic and just talk — the theme, who it's for, where it happens, expected attendees. Or type if you prefer. I'll pick out the details."
                : "Describe it in a few sentences — the theme, who it's for, where it happens. I'll pick out the details."}
            </p>
            <div className="relative mt-5">
              <textarea
                value={about}
                onChange={(e) => setAbout(e.target.value)}
                rows={7}
                placeholder="e.g. A two-day hybrid tech conference in Jaipur for AI startups and researchers. We expect around 500 attendees, with keynotes, workshops and an expo…"
                className={`${input} !pr-16 leading-relaxed`}
              />
              {speechSupported && (
                <button
                  type="button"
                  onClick={toggleListening}
                  title={listening ? "Stop listening" : "Speak"}
                  className={`absolute right-3 top-3 flex h-11 w-11 items-center justify-center rounded-full text-xl shadow-lg transition ${
                    listening ? "animate-pulse bg-red-500 text-white shadow-red-500/40" : "bg-gradient-to-br from-indigo-500 to-violet-500 text-white shadow-indigo-500/40 hover:brightness-110"
                  }`}
                >
                  {listening ? "⏹" : "🎙️"}
                </button>
              )}
            </div>
            {listening && (
              <p className="mt-2 flex items-center gap-2 text-sm font-medium text-red-500">
                <span className="relative flex h-2.5 w-2.5"><span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-red-400" /><span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-red-500" /></span>
                Listening… speak naturally, tap ⏹ when done.
              </p>
            )}
            {detectedChips.length > 0 && (
              <div className="mt-4 rounded-xl bg-indigo-500/5 px-4 py-3">
                <div className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">✨ Detected from your description</div>
                <div className="mt-1.5 flex flex-wrap gap-1.5">
                  {detectedChips.map((c) => <Badge key={c} className="bg-white/70 text-indigo-700">{c}</Badge>)}
                </div>
              </div>
            )}
            <p className="mt-3 text-xs text-zinc-600">Optional — but the more you share, the more I can pre-fill for you.</p>
          </div>
        )}

        {step === 2 && (
          <div>
            <h2 className="text-xl font-extrabold text-zinc-100">When is it happening? 📅</h2>
            <p className="mt-1 text-sm text-zinc-500">One-day event? Use the same date for both.</p>
            <div className="mt-5 grid gap-4 sm:grid-cols-2">
              <label className="block">
                <span className="mb-1.5 block text-xs font-semibold text-zinc-400">Starts *</span>
                <input type="date" value={startAt} onChange={(e) => { setStartAt(e.target.value); if (!endAt) setEndAt(e.target.value); }} className={`${input} !py-3`} />
              </label>
              <label className="block">
                <span className="mb-1.5 block text-xs font-semibold text-zinc-400">Ends *</span>
                <input type="date" value={endAt} min={startAt || undefined} onChange={(e) => setEndAt(e.target.value)} className={`${input} !py-3`} />
              </label>
            </div>
          </div>
        )}

        {step === 3 && (
          <div>
            <h2 className="text-xl font-extrabold text-zinc-100">When can people register? 🎟️</h2>
            <p className="mt-1 text-sm text-zinc-500">Leave blank to open registration today and close it when the conference ends.</p>
            <div className="mt-5 grid gap-4 sm:grid-cols-2">
              <label className="block">
                <span className="mb-1.5 block text-xs font-semibold text-zinc-400">Registration opens</span>
                <input type="date" value={regOpensAt} onChange={(e) => setRegOpensAt(e.target.value)} className={`${input} !py-3`} />
              </label>
              <label className="block">
                <span className="mb-1.5 block text-xs font-semibold text-zinc-400">Registration closes</span>
                <input type="date" value={regClosesAt} min={regOpensAt || undefined} max={endAt || undefined} onChange={(e) => setRegClosesAt(e.target.value)} className={`${input} !py-3`} />
              </label>
            </div>
          </div>
        )}

        {step === 4 && (
          <div>
            <h2 className="text-xl font-extrabold text-zinc-100">Ready to launch? 🚀</h2>
            <p className="mt-1 text-sm text-zinc-500">Here's what I'll set up — everything stays editable in the conference console.</p>
            <div className="mt-5 space-y-2.5 text-sm">
              <div className="flex justify-between gap-4 rounded-xl bg-white/50 px-4 py-2.5"><span className="text-zinc-500">Conference</span><b className="text-right text-zinc-100">{title.trim()}</b></div>
              <div className="flex justify-between gap-4 rounded-xl bg-white/50 px-4 py-2.5"><span className="text-zinc-500">Dates</span><b className="text-zinc-100">{fmt(startAt)} → {fmt(endAt)}</b></div>
              <div className="flex justify-between gap-4 rounded-xl bg-white/50 px-4 py-2.5"><span className="text-zinc-500">Registration</span><b className="text-zinc-100">{regOpensAt ? fmt(regOpensAt) : "Today"} → {regClosesAt ? fmt(regClosesAt) : "conference end"}</b></div>
              {detectedChips.length > 0 && (
                <div className="rounded-xl bg-indigo-500/5 px-4 py-2.5">
                  <span className="text-zinc-500">✨ Auto-filled from your description:</span>
                  <div className="mt-1.5 flex flex-wrap gap-1.5">{detectedChips.map((c) => <Badge key={c} className="bg-white/70 text-indigo-700">{c}</Badge>)}</div>
                </div>
              )}
              <div className="rounded-xl bg-emerald-500/10 px-4 py-2.5 text-xs text-emerald-700">
                Included: public website (private draft) · free General Pass · Main Track & Hall · agenda builder · check-in · certificates.
              </div>
            </div>
          </div>
        )}

        {error && <p className="mt-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{error}</p>}

        <div className="mt-7 flex items-center justify-between">
          <button type="button" onClick={back} disabled={step === 0} className={`${btn.ghost} disabled:invisible`}>← Back</button>
          {step < STEPS.length - 1 ? (
            <button type="button" onClick={next} className={`${btn.primary} px-7`}>
              {step === 1 && !about.trim() ? "Skip for now →" : "Continue →"}
            </button>
          ) : (
            <button type="button" onClick={create} className={`${btn.primary} px-7 !py-3`}>✨ Create my conference</button>
          )}
        </div>
      </Card>
    </div>
  );
}
