/* eslint-disable */
import { createFileRoute, Link } from "@tanstack/react-router";
import { useState, useRef } from "react";
import {
  Mic,
  MicOff,
  Plus,
  Loader2,
  Sparkles,
  Camera,
  Volume2,
  Droplet,
  CheckCircle2,
  HelpCircle,
  Zap,
  Quote,
  Settings,
  Heart,
  Brain,
  Images,
  BellRing,
  Activity,
  ArrowRight,
} from "lucide-react";
import { Card, Screen } from "@/components/ui-kit";
import { svgs } from "@/assets/svgMap";
import { chatWithVoiceCompanion } from "@/lib/ai";
import { useUserProfile } from "@/lib/user-profile";
import { useUiSettings, t } from "@/lib/ui-settings";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Home · NeuroSaathi Senior Care" },
      {
        name: "description",
        content:
          "Senior-friendly 2x2 grid dashboard: large text, AI voice companion, camera yoga posture, family SOS, and health reminders.",
      },
      { property: "og:title", content: "Home · NeuroSaathi Senior Care" },
      {
        property: "og:description",
        content: "Senior-friendly large-text AI companion dashboard for elderly users.",
      },
    ],
  }),
  component: Home,
});

const DAILY_RIDDLE = {
  question: "J jitna aage badhega, utna hi peeche chhuta jayega. Batao woh kya hai?",
  answer: "👣 Kadam (Footsteps)",
};

const SUVICHAR = {
  text: "Man shant rakhne se har mushkil rasta aasan ho jata hai. Subah ki shuruaat ek muskaan aur swasthya ke saath karein.",
  author: "Santosh Mantras",
};

export function Home() {
  const profile = useUserProfile();
  const uiSettings = useUiSettings();
  const lang = uiSettings.language;

  const [listening, setListening] = useState(false);
  const [assistantResponse, setAssistantResponse] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [waterCount, setWaterCount] = useState<number>(5);
  const [medsTaken, setMedsTaken] = useState<boolean>(true);
  const [currentMood, setCurrentMood] = useState<string>("😊 Anand");
  const [showRiddleAnswer, setShowRiddleAnswer] = useState<boolean>(false);
  const [isPlayingQuote, setIsPlayingQuote] = useState<boolean>(false);

  const recognitionRef = useRef<any>(null);

  const speakTextInstant = (text: string) => {
    if (typeof window !== "undefined" && "speechSynthesis" in window) {
      window.speechSynthesis.cancel();
      const utter = new SpeechSynthesisUtterance(text);
      utter.lang = lang === "English" ? "en-IN" : "hi-IN";
      utter.rate = 0.95;
      utter.pitch = 1.05;
      utter.onend = () => setIsPlayingQuote(false);
      utter.onerror = () => setIsPlayingQuote(false);
      setIsPlayingQuote(true);
      window.speechSynthesis.speak(utter);
    }
  };

  const initRecognition = () => {
    if (!("webkitSpeechRecognition" in window) && !("SpeechRecognition" in window)) {
      alert("Aapka browser voice recognition support nahi karta. Please Chrome use karein.");
      return null;
    }
    const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
    const recognition = new SpeechRecognition();
    recognition.lang = lang === "English" ? "en-IN" : "hi-IN";
    recognition.continuous = false;
    recognition.interimResults = false;

    recognition.onstart = () => {
      setListening(true);
      setAssistantResponse(lang === "Hindi" ? "सुन रहा हूँ... बोलिए।" : "Sun raha hoon... Boliye.");
    };

    recognition.onresult = async (event: any) => {
      const transcript = event.results[0][0].transcript;
      setAssistantResponse(lang === "Hindi" ? `आपने कहा: "${transcript}"` : `Aapne kaha: "${transcript}"`);
      setListening(false);
      setIsLoading(true);

      try {
        const { text } = await chatWithVoiceCompanion({
          data: {
            message: transcript,
            userName: profile.name,
            language: lang,
            fastMode: true,
          },
        });
        setAssistantResponse(text);
        speakTextInstant(text);
      } catch (err) {
        setAssistantResponse(lang === "Hindi" ? "माफ़ कीजिए, समझ नहीं आया।" : "Maaf kijiye, samajh nahi aaya.");
      } finally {
        setIsLoading(false);
      }
    };

    recognition.onerror = () => {
      setListening(false);
      setAssistantResponse("Problem occurred, try again.");
    };

    recognition.onend = () => {
      setListening(false);
    };

    return recognition;
  };

  const toggleVoiceCompanion = () => {
    if (!listening) {
      if (!recognitionRef.current) {
        recognitionRef.current = initRecognition();
      }
      if (recognitionRef.current) {
        try {
          recognitionRef.current.start();
        } catch (e) {
          console.error(e);
        }
      }
    } else {
      if (recognitionRef.current) {
        recognitionRef.current.stop();
      }
      setListening(false);
    }
  };

  const todayStr = new Date().toLocaleDateString(lang === "English" ? "en-IN" : "hi-IN", {
    weekday: "long",
    day: "numeric",
    month: "long",
  });

  return (
    <Screen>
      {/* Personalized Greeting Header */}
      <section className="space-y-1.5">
        <div className="flex items-center justify-between">
          <p className="text-xs sm:text-sm font-extrabold uppercase tracking-wider text-emerald-600 dark:text-emerald-400">
            {todayStr}
          </p>
          <span className="flex items-center gap-1 text-[11px] font-extrabold px-3 py-1 rounded-full bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border border-emerald-500/30">
            <Zap className="h-3.5 w-3.5 text-emerald-500" /> 24/7 AI Active
          </span>
        </div>
        <h1 className="text-2xl sm:text-4xl font-display font-black leading-tight text-foreground flex items-center gap-2">
          {t("greeting_namaste", lang)}, {profile.name || "Aap"} ji{" "}
          <Sparkles className="h-6 w-6 text-emerald-500 animate-pulse" />
        </h1>
        <p className="text-xs sm:text-sm font-bold text-muted-foreground">
          {t("dashboard_subtitle", lang)}
        </p>
      </section>

      {/* --- 2×2 GRID DASHBOARD (EXACTLY MATCHING USER SPECIFICATION & IMAGE 2) --- */}
      <section className="space-y-3">
        <div className="flex items-center justify-between">
          <h2 className="text-base sm:text-lg font-black text-foreground flex items-center gap-2">
            ✨ {t("grid_title", lang)}
          </h2>
          <span className="text-xs font-extrabold text-emerald-600 dark:text-emerald-400 bg-emerald-500/15 px-2.5 py-0.5 rounded-full">
            2×2 Layout
          </span>
        </div>

        {/* The 2x2 Grid Layout */}
        <div className="grid grid-cols-2 gap-3 sm:gap-4">
          {/* Card 1: AI Voice Assistant */}
          <Link
            to="/companion"
            className="press group flex flex-col justify-between p-4 sm:p-5 rounded-3xl bg-card border-2 border-emerald-500/40 shadow-md hover:border-emerald-500 hover:shadow-xl transition-all min-h-[140px] sm:min-h-[160px] relative overflow-hidden"
          >
            <div className="flex items-center justify-between">
              <div className="grid h-12 w-12 sm:h-14 sm:w-14 place-items-center rounded-2xl bg-emerald-500 text-white font-extrabold shadow-md shadow-emerald-500/30 group-hover:scale-110 transition-transform">
                <Mic className="h-6 w-6 sm:h-7 sm:w-7 animate-pulse" />
              </div>
              <span className="text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-700 dark:text-emerald-300">
                1-Tap
              </span>
            </div>
            <div className="mt-3">
              <h3 className="font-display text-sm sm:text-base font-extrabold text-foreground group-hover:text-emerald-600 transition-colors">
                {t("tile_voice_title", lang)}
              </h3>
              <p className="text-[11px] sm:text-xs font-bold text-muted-foreground mt-0.5">
                {t("tile_voice_sub", lang)}
              </p>
            </div>
          </Link>

          {/* Card 2: AI Yoga Coach */}
          <Link
            to="/yoga"
            className="press group flex flex-col justify-between p-4 sm:p-5 rounded-3xl bg-card border-2 border-purple-500/40 shadow-md hover:border-purple-500 hover:shadow-xl transition-all min-h-[140px] sm:min-h-[160px] relative overflow-hidden"
          >
            <div className="flex items-center justify-between">
              <div className="grid h-12 w-12 sm:h-14 sm:w-14 place-items-center rounded-2xl bg-purple-600 text-white font-extrabold shadow-md shadow-purple-500/30 group-hover:scale-110 transition-transform">
                <Camera className="h-6 w-6 sm:h-7 sm:w-7" />
              </div>
              <span className="text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full bg-purple-500/20 text-purple-700 dark:text-purple-300">
                Vision
              </span>
            </div>
            <div className="mt-3">
              <h3 className="font-display text-sm sm:text-base font-extrabold text-foreground group-hover:text-purple-600 transition-colors">
                {t("tile_yoga_title", lang)}
              </h3>
              <p className="text-[11px] sm:text-xs font-bold text-muted-foreground mt-0.5">
                {t("tile_yoga_sub", lang)}
              </p>
            </div>
          </Link>

          {/* Card 3: Water Hydration Tracker */}
          <div className="press group flex flex-col justify-between p-4 sm:p-5 rounded-3xl bg-card border-2 border-cyan-500/40 shadow-md transition-all min-h-[140px] sm:min-h-[160px] relative">
            <div className="flex items-center justify-between">
              <div className="grid h-12 w-12 sm:h-14 sm:w-14 place-items-center rounded-2xl bg-cyan-500 text-white font-extrabold shadow-md shadow-cyan-500/30">
                <Droplet className="h-6 w-6 sm:h-7 sm:w-7" />
              </div>
              <button
                type="button"
                onClick={() => setWaterCount((p) => Math.min(12, p + 1))}
                className="press flex items-center gap-1 text-xs font-black px-2.5 py-1 rounded-xl bg-cyan-500 text-white shadow-xs hover:bg-cyan-600 active:scale-95"
              >
                <Plus className="h-3.5 w-3.5" /> +1
              </button>
            </div>
            <div className="mt-3">
              <h3 className="font-display text-sm sm:text-base font-extrabold text-foreground">
                {t("tile_water_title", lang)}
              </h3>
              <p className="text-[11px] sm:text-xs font-bold text-cyan-600 dark:text-cyan-400 mt-0.5">
                💧 {waterCount} / 8 Glasses
              </p>
            </div>
          </div>

          {/* Card 4: Subah Ki Dawai */}
          <Link
            to="/reminders"
            className="press group flex flex-col justify-between p-4 sm:p-5 rounded-3xl bg-card border-2 border-amber-500/40 shadow-md hover:border-amber-500 hover:shadow-xl transition-all min-h-[140px] sm:min-h-[160px] relative overflow-hidden"
          >
            <div className="flex items-center justify-between">
              <div className="grid h-12 w-12 sm:h-14 sm:w-14 place-items-center rounded-2xl bg-amber-500 text-white font-extrabold shadow-md shadow-amber-500/30 group-hover:scale-110 transition-transform">
                <BellRing className="h-6 w-6 sm:h-7 sm:w-7" />
              </div>
              <span className="text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-700 dark:text-emerald-300">
                {medsTaken ? "✅ Taken" : "⏳ Pending"}
              </span>
            </div>
            <div className="mt-3">
              <h3 className="font-display text-sm sm:text-base font-extrabold text-foreground group-hover:text-amber-600 transition-colors">
                {t("tile_meds_title", lang)}
              </h3>
              <p className="text-[11px] sm:text-xs font-bold text-muted-foreground mt-0.5">
                {medsTaken ? t("tile_meds_sub", lang) : "Click to view reminders"}
              </p>
            </div>
          </Link>

          {/* Card 5: Memories Album */}
          <Link
            to="/memory"
            className="press group flex flex-col justify-between p-4 sm:p-5 rounded-3xl bg-card border-2 border-blue-500/40 shadow-md hover:border-blue-500 hover:shadow-xl transition-all min-h-[140px] sm:min-h-[160px] relative overflow-hidden"
          >
            <div className="flex items-center justify-between">
              <div className="grid h-12 w-12 sm:h-14 sm:w-14 place-items-center rounded-2xl bg-blue-600 text-white font-extrabold shadow-md shadow-blue-500/30 group-hover:scale-110 transition-transform">
                <Images className="h-6 w-6 sm:h-7 sm:w-7" />
              </div>
              <span className="text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full bg-blue-500/20 text-blue-700 dark:text-blue-300">
                Photos
              </span>
            </div>
            <div className="mt-3">
              <h3 className="font-display text-sm sm:text-base font-extrabold text-foreground group-hover:text-blue-600 transition-colors">
                {t("tile_memories_title", lang)}
              </h3>
              <p className="text-[11px] sm:text-xs font-bold text-muted-foreground mt-0.5">
                {t("tile_memories_sub", lang)}
              </p>
            </div>
          </Link>

          {/* Card 6: Brain Games */}
          <Link
            to="/activities"
            className="press group flex flex-col justify-between p-4 sm:p-5 rounded-3xl bg-card border-2 border-indigo-500/40 shadow-md hover:border-indigo-500 hover:shadow-xl transition-all min-h-[140px] sm:min-h-[160px] relative overflow-hidden"
          >
            <div className="flex items-center justify-between">
              <div className="grid h-12 w-12 sm:h-14 sm:w-14 place-items-center rounded-2xl bg-indigo-600 text-white font-extrabold shadow-md shadow-indigo-500/30 group-hover:scale-110 transition-transform">
                <Brain className="h-6 w-6 sm:h-7 sm:w-7" />
              </div>
              <span className="text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full bg-indigo-500/20 text-indigo-700 dark:text-indigo-300">
                Games
              </span>
            </div>
            <div className="mt-3">
              <h3 className="font-display text-sm sm:text-base font-extrabold text-foreground group-hover:text-indigo-600 transition-colors">
                {t("tile_games_title", lang)}
              </h3>
              <p className="text-[11px] sm:text-xs font-bold text-muted-foreground mt-0.5">
                {t("tile_games_sub", lang)}
              </p>
            </div>
          </Link>

          {/* Card 7: Parivaar & SOS */}
          <Link
            to="/family"
            className="press group flex flex-col justify-between p-4 sm:p-5 rounded-3xl bg-card border-2 border-red-500/40 shadow-md hover:border-red-500 hover:shadow-xl transition-all min-h-[140px] sm:min-h-[160px] relative overflow-hidden"
          >
            <div className="flex items-center justify-between">
              <div className="grid h-12 w-12 sm:h-14 sm:w-14 place-items-center rounded-2xl bg-red-600 text-white font-extrabold shadow-md shadow-red-500/30 group-hover:scale-110 transition-transform">
                <Heart className="h-6 w-6 sm:h-7 sm:w-7 fill-white" />
              </div>
              <span className="text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full bg-red-500/20 text-red-700 dark:text-red-300">
                SOS 24/7
              </span>
            </div>
            <div className="mt-3">
              <h3 className="font-display text-sm sm:text-base font-extrabold text-foreground group-hover:text-red-600 transition-colors">
                {t("tile_family_title", lang)}
              </h3>
              <p className="text-[11px] sm:text-xs font-bold text-muted-foreground mt-0.5">
                {t("tile_family_sub", lang)}
              </p>
            </div>
          </Link>

          {/* Card 8: Settings & Custom Scale */}
          <Link
            to="/profile"
            className="press group flex flex-col justify-between p-4 sm:p-5 rounded-3xl bg-card border-2 border-emerald-500/50 shadow-md hover:border-emerald-500 hover:shadow-xl transition-all min-h-[140px] sm:min-h-[160px] relative overflow-hidden"
          >
            <div className="flex items-center justify-between">
              <div className="grid h-12 w-12 sm:h-14 sm:w-14 place-items-center rounded-2xl bg-emerald-600 text-white font-extrabold shadow-md shadow-emerald-500/30 group-hover:scale-110 transition-transform">
                <Settings className="h-6 w-6 sm:h-7 sm:w-7" />
              </div>
              <span className="text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-700 dark:text-emerald-300">
                Font & UI
              </span>
            </div>
            <div className="mt-3">
              <h3 className="font-display text-sm sm:text-base font-extrabold text-foreground group-hover:text-emerald-600 transition-colors">
                {t("tile_settings_title", lang)}
              </h3>
              <p className="text-[11px] sm:text-xs font-bold text-muted-foreground mt-0.5">
                {t("tile_settings_sub", lang)}
              </p>
            </div>
          </Link>
        </div>
      </section>

      {/* Senior Voice AI Mic Card */}
      <Card className="border-2 border-emerald-500/40 bg-card text-card-foreground shadow-lg p-5 sm:p-6 space-y-4 w-full">
        <div className="flex items-center justify-between gap-3">
          <div className="min-w-0 flex items-center gap-3.5">
            <div className="relative grid h-14 w-14 shrink-0 place-items-center rounded-2xl bg-gradient-to-tr from-emerald-500 to-teal-600 text-white font-extrabold shadow-md shadow-emerald-500/20">
              <Mic className="h-7 w-7" />
              <span className="absolute -top-1 -right-1 h-3.5 w-3.5 rounded-full bg-emerald-400 ring-2 ring-background animate-ping" />
            </div>
            <div className="min-w-0">
              <p className="font-display text-base sm:text-lg font-extrabold text-foreground leading-tight">
                {t("tile_voice_title", lang)}
              </p>
              <p className="text-xs sm:text-sm text-muted-foreground truncate font-semibold mt-1">
                {listening
                  ? "Sun raha hoon… boliye"
                  : isLoading
                    ? "NeuroSaathi soch raha hai..."
                    : `Mic par tap karein (${lang})`}
              </p>
            </div>
          </div>
          <button
            onClick={toggleVoiceCompanion}
            aria-label="Start voice companion"
            disabled={isLoading}
            className={`press grid h-13 w-13 shrink-0 place-items-center rounded-2xl text-white font-extrabold shadow-md transition-all duration-300 ${
              listening
                ? "bg-red-500 text-white animate-pulse ring-4 ring-red-500/30"
                : isLoading
                  ? "bg-muted text-muted-foreground"
                  : "bg-gradient-to-r from-emerald-500 to-teal-600 ring-2 ring-emerald-500/20"
            }`}
          >
            {isLoading ? (
              <Loader2 className="h-6 w-6 animate-spin text-emerald-500" />
            ) : listening ? (
              <MicOff className="h-6 w-6" />
            ) : (
              <Mic className="h-6 w-6" />
            )}
          </button>
        </div>
        {(assistantResponse || isLoading) && (
          <div className="rounded-2xl bg-muted/80 p-4 text-sm sm:text-base font-bold border border-border text-foreground flex items-center justify-between gap-3 shadow-inner">
            <span className="truncate">💬 {assistantResponse || "Jawab dhoondh raha hoon..."}</span>
            {assistantResponse && (
              <button
                type="button"
                onClick={() => speakTextInstant(assistantResponse)}
                className="text-emerald-700 dark:text-emerald-300 hover:underline text-xs sm:text-sm font-extrabold shrink-0 flex items-center gap-1.5 bg-emerald-500/15 px-3 py-1.5 rounded-xl border border-emerald-500/30"
              >
                <Volume2 className="h-4 w-4" /> Listen
              </button>
            )}
          </div>
        )}
      </Card>

      {/* Suvichar / Daily Affirmation */}
      <Card className="bg-gradient-to-r from-emerald-600/20 via-teal-600/20 to-emerald-500/20 border-2 border-emerald-500/40 p-5 sm:p-6 space-y-3 shadow-md w-full">
        <div className="flex items-center justify-between gap-2">
          <div className="flex items-center gap-2 text-emerald-700 dark:text-emerald-300 font-extrabold text-sm sm:text-base">
            <Quote className="h-5 w-5" /> Aaj Ka Shubh Vichar
          </div>
          <button
            type="button"
            onClick={() => speakTextInstant(SUVICHAR.text)}
            className="press flex items-center gap-2 text-xs sm:text-sm font-extrabold text-white bg-emerald-600 px-4 py-2 rounded-full shadow hover:bg-emerald-500 transition-all"
          >
            <Volume2 className="h-4.5 w-4.5" /> {isPlayingQuote ? "Suno..." : "Sunein (Listen)"}
          </button>
        </div>
        <p className="text-sm sm:text-base font-bold text-foreground italic leading-relaxed">
          "{SUVICHAR.text}"
        </p>
        <p className="text-xs sm:text-sm text-muted-foreground font-extrabold">— {SUVICHAR.author}</p>
      </Card>
    </Screen>
  );
}
