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

export function OnboardingScreen() {
  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");
  const [emergencyPhone, setEmergencyPhone] = useState("");
  const [emergencyName, setEmergencyName] = useState("");

  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);
      setEmergencyName(p.emergencyContactName || "");
      setEmergencyPhone(p.emergencyContactPhone || "");
      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,
      emergencyContactName: emergencyName.trim(),
      emergencyContactPhone: emergencyPhone.trim(),
      hasCompletedOnboarding: true,
    });
    setIsOpen(false);

    // Voice welcome greeting
    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 = 0.95;
        window.speechSynthesis.speak(utterance);
      } catch (e) {
        console.warn("Speech synthesis error:", e);
      }
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[100] flex flex-col justify-between bg-background text-foreground overflow-y-auto no-scrollbar animate-rise">
      {/* Background Animated Ambient Mesh */}
      <div className="pointer-events-none fixed inset-0 z-0">
        <div className="absolute top-[-10%] left-[-10%] h-[50vw] w-[50vw] rounded-full bg-emerald-500/10 blur-[100px] animate-pulse" />
        <div
          className="absolute bottom-[-10%] right-[-10%] h-[50vw] w-[50vw] rounded-full bg-cyan-500/10 blur-[100px] animate-pulse"
          style={{ animationDelay: "1s" }}
        />
      </div>

      <div className="relative z-10 mx-auto w-full max-w-md md:max-w-xl px-4 py-6 sm:py-10 flex-1 flex flex-col justify-between min-h-screen">
        {/* Top Header & Sleek Progress Bar */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <div className="grid h-10 w-10 place-items-center rounded-2xl bg-gradient-to-tr from-emerald-500 to-teal-600 text-white font-bold shadow-md shadow-emerald-500/20">
                <Brain className="h-5.5 w-5.5" />
              </div>
              <div>
                <h1 className="font-display text-base font-bold tracking-tight text-foreground">
                  NeuroSaathi
                </h1>
                <p className="text-[11px] text-emerald-600 dark:text-emerald-400 font-semibold">
                  Personal Setup Wizard
                </p>
              </div>
            </div>

            <div className="flex items-center gap-1.5 px-3 py-1 rounded-full bg-emerald-500/10 border border-emerald-500/20 text-emerald-700 dark:text-emerald-300 text-xs font-bold">
              <Sparkles className="h-3.5 w-3.5" /> Step {step} of 4
            </div>
          </div>

          {/* Progress Indicator */}
          <div className="h-2 w-full overflow-hidden rounded-full bg-muted/80 border border-border/60">
            <div
              className="h-full bg-gradient-to-r from-emerald-500 via-teal-500 to-cyan-500 transition-all duration-500 rounded-full"
              style={{ width: `${(step / 4) * 100}%` }}
            />
          </div>
        </div>

        {/* STEP 1: Name & Age Group */}
        {step === 1 && (
          <div className="my-auto py-6 space-y-6 animate-rise">
            <div className="space-y-2 text-left">
              <span className="inline-flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-emerald-600 dark:text-emerald-400">
                <User className="h-4 w-4" /> Sawaal 1 / Question 1
              </span>
              <h2 className="font-display text-2xl sm:text-3xl font-bold tracking-tight text-foreground">
                Namaste! Aapka Shubh Naam Kya Hai?
              </h2>
              <p className="text-xs sm:text-sm text-muted-foreground leading-relaxed">
                AI NeuroSaathi aapko daily conversational guidance aur reminders mein isi naam se
                aadar ke sath pukaarega.
              </p>
            </div>

            <div className="space-y-3">
              <label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                Aapka Naam (Your Name)
              </label>
              <div className="relative">
                <User className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-emerald-600 dark:text-emerald-400" />
                <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-border bg-card/90 pl-12 pr-4 py-3.5 " +
                    "text-base font-bold text-foreground placeholder:text-muted-foreground/60 " +
                    "focus:border-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/30 shadow-sm transition-all"
                  }
                />
              </div>

              {name.trim() ? (
                <div className="p-3 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-xs font-semibold text-emerald-700 dark:text-emerald-300 flex items-center gap-2 animate-rise">
                  <Check className="h-4 w-4 shrink-0 text-emerald-500" />
                  <span>"Namaste {name.trim()} ji! Aapka NeuroSaathi tayyar ho raha hai."</span>
                </div>
              ) : null}
            </div>

            <div className="space-y-3">
              <label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                Aapka Age Group / Role
              </label>
              <div className="grid grid-cols-2 gap-2.5">
                {[
                  { id: "senior", label: "Senior (60+ yrs)", sub: "Varishth Naagrik" },
                  { id: "adult", label: "Adult (35-59 yrs)", sub: "Wellness Seeker" },
                  { id: "youth", label: "Youth / Caregiver", sub: "Parivaar 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-foreground font-bold shadow-sm"
                        : "border-border bg-card/60 text-muted-foreground hover:border-emerald-500/30 hover:text-foreground"
                    }`}
                  >
                    <span className="text-xs font-bold">{item.label}</span>
                    <span className="text-[10px] text-muted-foreground mt-0.5">{item.sub}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* STEP 2: Language Preference */}
        {step === 2 && (
          <div className="my-auto py-6 space-y-6 animate-rise">
            <div className="space-y-2 text-left">
              <span className="inline-flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-teal-600 dark:text-teal-400">
                <Globe className="h-4 w-4" /> Sawaal 2 / Question 2
              </span>
              <h2 className="font-display text-2xl sm:text-3xl font-bold tracking-tight text-foreground">
                Aapki Pasandida Bhasha Kon Si Hai?
              </h2>
              <p className="text-xs sm:text-sm text-muted-foreground leading-relaxed">
                NeuroSaathi Voice Assistant aur interface aapse isi bhasha mein aawaz aur text se
                baat karega.
              </p>
            </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 voice" },
                { 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-foreground font-bold shadow-sm"
                      : "border-border bg-card/60 text-muted-foreground hover:border-teal-500/30 hover:text-foreground"
                  }`}
                >
                  <span className="text-xs font-bold flex items-center justify-between">
                    {l.title}
                    {language === l.id && <Check className="h-3.5 w-3.5 text-teal-500" />}
                  </span>
                  <span className="text-[10px] text-muted-foreground mt-0.5">{l.desc}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* STEP 3: Primary Goal */}
        {step === 3 && (
          <div className="my-auto py-6 space-y-6 animate-rise">
            <div className="space-y-2 text-left">
              <span className="inline-flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-emerald-600 dark:text-emerald-400">
                <Heart className="h-4 w-4" /> Sawaal 3 / Question 3
              </span>
              <h2 className="font-display text-2xl sm:text-3xl font-bold tracking-tight text-foreground">
                Aapke Liye Sabse Zaroori Suvidha Kya Hai?
              </h2>
              <p className="text-xs sm:text-sm text-muted-foreground leading-relaxed">
                Aapki zaroorat ke anusaar aapka homepage aur daily recommendations tayyar ho
                jayenge.
              </p>
            </div>

            <div className="space-y-2.5">
              {[
                {
                  id: "all",
                  title: "Sabhi Suvidhayein (All in One)",
                  desc: "AI Voice, Yoga Coach, Brain Games aur Dawai Reminders",
                  icon: Sparkles,
                },
                {
                  id: "companion",
                  title: "AI Voice Companion (Saathi)",
                  desc: "24/7 Mann ki baat, dukh-sukh, daily baatchit",
                  icon: MessageSquareHeart,
                },
                {
                  id: "yoga",
                  title: "AI Yoga & Balance Coach",
                  desc: "Camera se posture correction aur body stretch",
                  icon: Dumbbell,
                },
                {
                  id: "reminders",
                  title: "Dawai aur Health Reminders",
                  desc: "Samay par dawai, pani aur walk alarms",
                  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-foreground font-bold shadow-sm"
                        : "border-border bg-card/60 text-muted-foreground hover:border-emerald-500/30 hover:text-foreground"
                    }`}
                  >
                    <div className="grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/20">
                      <Icon className="h-4.5 w-4.5" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-xs font-bold text-foreground">{g.title}</p>
                      <p className="text-[11px] text-muted-foreground mt-0.5">{g.desc}</p>
                    </div>
                    {primaryGoal === g.id && (
                      <Check className="h-4 w-4 text-emerald-500 shrink-0" />
                    )}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {/* STEP 4: Emergency & Safety Setup */}
        {step === 4 && (
          <div className="my-auto py-6 space-y-6 animate-rise">
            <div className="space-y-2 text-left">
              <span className="inline-flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-rose-600 dark:text-rose-400">
                <ShieldAlert className="h-4 w-4" /> Sawaal 4 / Question 4
              </span>
              <h2 className="font-display text-2xl sm:text-3xl font-bold tracking-tight text-foreground">
                Emergency Contact (Parivaar SOS)
              </h2>
              <p className="text-xs sm:text-sm text-muted-foreground leading-relaxed">
                Emergency ke waqt 1-Tap SOS Alert send karne ke liye apne kisi family member ya
                caregiver ka contact save karein (optional).
              </p>
            </div>

            <div className="space-y-3">
              <div className="space-y-1.5">
                <label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                  Caregiver / Parivaar Sadasya Ka Naam
                </label>
                <div className="relative">
                  <User className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <input
                    type="text"
                    placeholder="e.g. Beta Rahul, Doctor Uncle..."
                    value={emergencyName}
                    onChange={(e) => setEmergencyName(e.target.value)}
                    className="w-full rounded-2xl border border-border bg-card/90 pl-10 pr-3.5 py-2.5 text-xs font-bold text-foreground placeholder:text-muted-foreground/60 focus:border-emerald-500 focus:outline-none"
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                  Phone Number
                </label>
                <div className="relative">
                  <Phone className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <input
                    type="tel"
                    placeholder="e.g. +91 9876543210"
                    value={emergencyPhone}
                    onChange={(e) => setEmergencyPhone(e.target.value)}
                    className="w-full rounded-2xl border border-border bg-card/90 pl-10 pr-3.5 py-2.5 text-xs font-bold text-foreground placeholder:text-muted-foreground/60 focus:border-emerald-500 focus:outline-none"
                  />
                </div>
              </div>
            </div>

            <div className="p-3 rounded-2xl bg-cyan-500/10 border border-cyan-500/20 text-xs font-semibold text-cyan-700 dark:text-cyan-300 flex items-center gap-2">
              <Droplet className="h-4 w-4 text-cyan-500 shrink-0" />
              <span>
                Daily Hydration goal (8 glasses) and morning medicine reminders standard enable ho
                gaye hain.
              </span>
            </div>
          </div>
        )}

        {/* Bottom Navigation Buttons Bar */}
        <div className="pt-4 border-t border-border/80 flex items-center justify-between gap-3">
          {step > 1 ? (
            <button
              type="button"
              onClick={() => setStep((s) => s - 1)}
              className="press flex items-center gap-1.5 px-4 py-2.5 rounded-2xl border border-border bg-card text-xs font-bold text-foreground hover:bg-muted"
            >
              <ArrowLeft className="h-4 w-4" /> Peeche (Back)
            </button>
          ) : (
            <div />
          )}

          {step < 4 ? (
            <button
              type="button"
              disabled={step === 1 && !name.trim()}
              onClick={() => setStep((s) => s + 1)}
              className="press flex items-center gap-2 px-5 py-2.5 rounded-2xl bg-gradient-to-r from-emerald-500 to-teal-600 text-xs font-bold text-white shadow-md shadow-emerald-500/20 hover:brightness-110 disabled:opacity-50 disabled:pointer-events-none"
            >
              Aage Badhein <ArrowRight className="h-4 w-4" />
            </button>
          ) : (
            <button
              type="button"
              onClick={handleComplete}
              className="press flex items-center gap-2 px-6 py-2.5 rounded-2xl bg-gradient-to-r from-emerald-500 via-teal-500 to-cyan-500 text-xs font-bold text-white shadow-lg shadow-emerald-500/30 hover:brightness-110"
            >
              <Check className="h-4 w-4" /> Shuru Karein (Finish Setup)
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
