import { useState, useEffect } from "react";
import {
  Brain,
  Sparkles,
  User,
  Heart,
  Volume2,
  ArrowRight,
  Check,
  Globe,
  Dumbbell,
  Clock,
  MessageSquareHeart,
} from "lucide-react";
import { getUserProfile, saveUserProfile, UserProfile } from "@/lib/user-profile";

export function OnboardingModal() {
  const [isOpen, setIsOpen] = useState(false);
  const [step, setStep] = useState(1);
  const [name, setName] = useState("");
  const [ageGroup, setAgeGroup] = useState<UserProfile["ageGroup"]>("senior");
  const [language, setLanguage] = useState<UserProfile["language"]>("Hinglish");
  const [primaryGoal, setPrimaryGoal] = useState<UserProfile["primaryGoal"]>("all");

  useEffect(() => {
    const profile = getUserProfile();
    if (!profile.hasCompletedOnboarding) {
      setIsOpen(true);
      if (profile.name && profile.name !== "Ayush") {
        setName(profile.name);
      }
    }

    const handleOpen = () => {
      const p = getUserProfile();
      setName(p.name);
      setAgeGroup(p.ageGroup);
      setLanguage(p.language);
      setPrimaryGoal(p.primaryGoal);
      setStep(1);
      setIsOpen(true);
    };

    window.addEventListener("neurosaathi_open_onboarding", handleOpen);
    return () => window.removeEventListener("neurosaathi_open_onboarding", handleOpen);
  }, []);

  const handleComplete = () => {
    const trimmedName = name.trim() || "Dost";
    saveUserProfile({
      name: trimmedName,
      ageGroup,
      language,
      primaryGoal,
      hasCompletedOnboarding: true,
    });
    setIsOpen(false);

    // Speak welcome greeting in Hindi/Hinglish
    if (typeof window !== "undefined" && "speechSynthesis" in window) {
      try {
        window.speechSynthesis.cancel();
        const welcomeText = `Namaste ${trimmedName} ji! NeuroSaathi mein aapka swagat hai. Main aapka AI saathi hoon.`;
        const utterance = new SpeechSynthesisUtterance(welcomeText);
        utterance.lang = "hi-IN";
        utterance.rate = 1.0;
        window.speechSynthesis.speak(utterance);
      } catch (e) {
        console.warn("Speech synthesis welcome error:", e);
      }
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md animate-in fade-in duration-300">
      <div className="relative w-full max-w-lg overflow-hidden rounded-3xl border border-zinc-800 bg-zinc-950 p-6 sm:p-8 shadow-2xl text-zinc-100">
        {/* Background glow */}
        <div className="pointer-events-none absolute -top-24 -left-24 h-56 w-56 rounded-full bg-emerald-500/15 blur-3xl" />
        <div className="pointer-events-none absolute -bottom-24 -right-24 h-56 w-56 rounded-full bg-cyan-500/15 blur-3xl" />

        {/* Progress Bar Header */}
        <div className="relative mb-6">
          <div className="flex items-center justify-between mb-2 text-xs font-semibold text-zinc-400">
            <span className="flex items-center gap-1.5 text-emerald-400">
              <Sparkles className="h-3.5 w-3.5" /> Swagat hai / Welcome
            </span>
            <span>Step {step} of 3</span>
          </div>
          <div className="h-1.5 w-full overflow-hidden rounded-full bg-zinc-900 border border-zinc-800">
            <div
              className="h-full bg-gradient-to-r from-emerald-400 to-teal-500 transition-all duration-300 rounded-full"
              style={{ width: `${(step / 3) * 100}%` }}
            />
          </div>
        </div>

        {/* Step 1: Name & Introduction */}
        {step === 1 && (
          <div className="space-y-5 animate-in slide-in-from-right-4 duration-300">
            <div className="flex items-center gap-3">
              <div className="grid h-12 w-12 place-items-center rounded-2xl bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">
                <Brain className="h-6 w-6" />
              </div>
              <div>
                <h2 className="font-display text-xl font-bold tracking-tight text-white">
                  Namaste! Aapka Shubh Naam?
                </h2>
                <p className="text-xs text-zinc-400">
                  AI NeuroSaathi aapko aage isi naam se aadar ke sath pukaarega.
                </p>
              </div>
            </div>

            <div className="space-y-2">
              <label className="text-xs font-semibold uppercase tracking-wider text-zinc-400">
                Aapka Naam (Your Name)
              </label>
              <div className="relative">
                <User className="absolute left-3.5 top-1/2 -translate-y-1/2 h-5 w-5 text-zinc-500" />
                <input
                  type="text"
                  placeholder="e.g. Ayush, Sharma ji, Ramesh..."
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && name.trim()) setStep(2);
                  }}
                  autoFocus
                  className="w-full rounded-2xl border border-zinc-800 bg-zinc-900/90 pl-11 pr-4 py-3.5 text-base font-semibold text-white placeholder:text-zinc-600 focus:border-emerald-500 focus:outline-none focus:ring-1 focus:ring-emerald-500"
                />
              </div>
            </div>

            <div className="space-y-2">
              <label className="text-xs font-semibold uppercase tracking-wider text-zinc-400">
                Aapki Umar / Role
              </label>
              <div className="grid grid-cols-2 gap-2.5">
                {[
                  { id: "senior", label: "Senior (60+ yrs)", sub: "Aadarniya Varishth" },
                  { id: "adult", label: "Adult (35-59 yrs)", sub: "Wellness Seeker" },
                  { id: "youth", label: "Youth / Caregiver", sub: "Parivaar ke sadasya" },
                  { id: "elder", label: "Elderly Companion", sub: "Daily Support" },
                ].map((item) => (
                  <button
                    key={item.id}
                    type="button"
                    onClick={() => setAgeGroup(item.id as UserProfile["ageGroup"])}
                    className={`press flex flex-col items-start p-3 rounded-2xl border text-left transition-all ${
                      ageGroup === item.id
                        ? "border-emerald-500 bg-emerald-500/15 text-white"
                        : "border-zinc-800 bg-zinc-900/50 text-zinc-400 hover:border-zinc-700 hover:text-zinc-200"
                    }`}
                  >
                    <span className="text-xs font-bold">{item.label}</span>
                    <span className="text-[10px] text-zinc-500">{item.sub}</span>
                  </button>
                ))}
              </div>
            </div>

            <button
              type="button"
              disabled={!name.trim()}
              onClick={() => setStep(2)}
              className="press flex w-full items-center justify-center gap-2 rounded-2xl bg-gradient-to-r from-emerald-500 to-teal-600 py-3.5 text-sm font-bold text-black shadow-lg hover:brightness-110 disabled:opacity-50 disabled:pointer-events-none transition-all"
            >
              Aage Badhein <ArrowRight className="h-4 w-4" />
            </button>
          </div>
        )}

        {/* Step 2: Language Preference */}
        {step === 2 && (
          <div className="space-y-5 animate-in slide-in-from-right-4 duration-300">
            <div className="flex items-center gap-3">
              <div className="grid h-12 w-12 place-items-center rounded-2xl bg-teal-500/20 text-teal-400 border border-teal-500/30">
                <Globe className="h-6 w-6" />
              </div>
              <div>
                <h2 className="font-display text-xl font-bold tracking-tight text-white">
                  Aapki Pasandida Bhasha?
                </h2>
                <p className="text-xs text-zinc-400">
                  NeuroSaathi aapse isi bhasha mein aawaz aur text mein baat karega.
                </p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-2.5">
              {[
                { id: "Hinglish", title: "Hinglish", desc: "Hindi + English (Saral Bolchal)" },
                { id: "Hindi", title: "हिंदी (Hindi)", desc: "Shuddh evam prem-poorvak" },
                { id: "English", title: "English", desc: "Clear & simple tone" },
                { id: "Marathi", title: "मराठी (Marathi)", desc: "Aplya bhashet" },
                { id: "Punjabi", title: "ਪੰਜਾਬੀ (Punjabi)", desc: "Dil khol ke gal baat" },
                { id: "Tamil", title: "தமிழ் (Tamil)", desc: "Vanakkam & uraiyadal" },
              ].map((l) => (
                <button
                  key={l.id}
                  type="button"
                  onClick={() => setLanguage(l.id as UserProfile["language"])}
                  className={`press flex flex-col p-3 rounded-2xl border text-left transition-all ${
                    language === l.id
                      ? "border-teal-500 bg-teal-500/15 text-white"
                      : "border-zinc-800 bg-zinc-900/50 text-zinc-400 hover:border-zinc-700 hover:text-zinc-200"
                  }`}
                >
                  <span className="text-sm font-bold flex items-center justify-between">
                    {l.title}
                    {language === l.id && <Check className="h-3.5 w-3.5 text-teal-400" />}
                  </span>
                  <span className="text-[10px] text-zinc-500 mt-0.5">{l.desc}</span>
                </button>
              ))}
            </div>

            <div className="flex gap-3">
              <button
                type="button"
                onClick={() => setStep(1)}
                className="press rounded-2xl border border-zinc-800 bg-zinc-900 px-5 py-3.5 text-xs font-semibold text-zinc-300 hover:bg-zinc-800"
              >
                Peeche
              </button>
              <button
                type="button"
                onClick={() => setStep(3)}
                className="press flex flex-1 items-center justify-center gap-2 rounded-2xl bg-gradient-to-r from-teal-500 to-emerald-500 py-3.5 text-sm font-bold text-black shadow-lg hover:brightness-110"
              >
                Aage Badhein <ArrowRight className="h-4 w-4" />
              </button>
            </div>
          </div>
        )}

        {/* Step 3: Goals & Interests */}
        {step === 3 && (
          <div className="space-y-5 animate-in slide-in-from-right-4 duration-300">
            <div className="flex items-center gap-3">
              <div className="grid h-12 w-12 place-items-center rounded-2xl bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">
                <Heart className="h-6 w-6" />
              </div>
              <div>
                <h2 className="font-display text-xl font-bold tracking-tight text-white">
                  Aapke Liye Sabse Zaroori?
                </h2>
                <p className="text-xs text-zinc-400">
                  Aapki suvidha ke anusaar dashboard customize ho jayega.
                </p>
              </div>
            </div>

            <div className="space-y-2">
              {[
                {
                  id: "all",
                  title: "Sabhi Suvidhayein (All in One)",
                  desc: "AI Baatchit, Yoga, Memory Games aur Dawai Reminders",
                  icon: Sparkles,
                },
                {
                  id: "companion",
                  title: "AI Saathi se Baatein (Voice Companion)",
                  desc: "Mann ki baat, dukh-sukh, rojmara ke sawaal-jawab",
                  icon: MessageSquareHeart,
                },
                {
                  id: "yoga",
                  title: "AI Yoga & Balance Coaching",
                  desc: "Camera se real-time posture aur shareer ka santulan",
                  icon: Dumbbell,
                },
                {
                  id: "reminders",
                  title: "Dawai aur Health Reminders",
                  desc: "Samay par dawai, pani aur doctor appointment",
                  icon: Clock,
                },
              ].map((g) => {
                const Icon = g.icon;
                return (
                  <button
                    key={g.id}
                    type="button"
                    onClick={() => setPrimaryGoal(g.id as UserProfile["primaryGoal"])}
                    className={`press flex w-full items-center gap-3 p-3.5 rounded-2xl border text-left transition-all ${
                      primaryGoal === g.id
                        ? "border-emerald-500 bg-emerald-500/15 text-white"
                        : "border-zinc-800 bg-zinc-900/50 text-zinc-400 hover:border-zinc-700 hover:text-zinc-200"
                    }`}
                  >
                    <div className="grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-zinc-800 text-emerald-400">
                      <Icon className="h-4 w-4" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-xs font-bold text-zinc-100">{g.title}</p>
                      <p className="text-[11px] text-zinc-400">{g.desc}</p>
                    </div>
                    {primaryGoal === g.id && <Check className="h-4 w-4 text-emerald-400" />}
                  </button>
                );
              })}
            </div>

            <div className="flex gap-3">
              <button
                type="button"
                onClick={() => setStep(2)}
                className="press rounded-2xl border border-zinc-800 bg-zinc-900 px-5 py-3.5 text-xs font-semibold text-zinc-300 hover:bg-zinc-800"
              >
                Peeche
              </button>
              <button
                type="button"
                onClick={handleComplete}
                className="press flex flex-1 items-center justify-center gap-2 rounded-2xl bg-gradient-to-r from-emerald-400 to-teal-500 py-3.5 text-sm font-bold text-black shadow-lg hover:brightness-110"
              >
                <Check className="h-4 w-4" /> Shuru Karein (Finish Setup)
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
