import { createFileRoute } from "@tanstack/react-router";
import { useState, useEffect } from "react";
import {
  Brain,
  Images,
  Play,
  Puzzle,
  Search,
  Sparkles,
  Timer,
  CheckCircle,
  RotateCcw,
  Award,
  Zap,
  Grid3X3,
  Flame,
  Database,
  Layers,
} from "lucide-react";
import {
  ActionButton,
  Card,
  Pill,
  Screen,
  PageTitle,
  SectionHeading,
  ProgressBar,
} from "@/components/ui-kit";
import { SlidingPuzzleGame } from "@/components/games/sliding-puzzle";
import { StroopGame } from "@/components/games/stroop-test";
import { PatternRecallGame } from "@/components/games/pattern-recall";
import { OfflineSqlViewer } from "@/components/games/sql-storage-viewer";
import { offlineDB } from "@/lib/offline-db";

export const Route = createFileRoute("/activities")({
  head: () => ({
    meta: [
      { title: "Brain Games & Cognitive Training · NeuroSaathi" },
      {
        name: "description",
        content:
          "Playable 15-sliding tile puzzle, Stroop agility test, audio pattern recall, memory match and quiz games with 100% offline SQL persistence.",
      },
      { property: "og:title", content: "Brain Games & Cognitive Training · NeuroSaathi" },
      {
        property: "og:description",
        content: "Playable cognitive games with offline SQLite database storage.",
      },
    ],
  }),
  component: Activities,
});

const levels = ["Easy", "Medium", "Hard"] as const;

interface CardItem {
  id: number;
  emoji: string;
  name: string;
  flipped: boolean;
  matched: boolean;
}

const EMOJI_PAIRS = [
  { emoji: "🌸", name: "Lotus Flower" },
  { emoji: "🍎", name: "Fresh Apple" },
  { emoji: "🚗", name: "Vintage Car" },
  { emoji: "⭐", name: "Bright Star" },
  { emoji: "🐶", name: "Cute Puppy" },
  { emoji: "🏠", name: "Sweet Home" },
  { emoji: "🦚", name: "Peacock" },
  { emoji: "🥭", name: "Mango" },
];

function Activities() {
  const [level, setLevel] = useState<(typeof levels)[number]>("Medium");
  const [activeGame, setActiveGame] = useState<string | null>(null);

  // Memory Match State
  const [cards, setCards] = useState<CardItem[]>([]);
  const [selectedCards, setSelectedCards] = useState<number[]>([]);
  const [matches, setMatches] = useState(0);
  const [moves, setMoves] = useState(0);
  const [gameWon, setGameWon] = useState(false);
  const [gameTimer, setGameTimer] = useState(0);

  // Daily Quiz State
  const [quizIdx, setQuizIdx] = useState(0);
  const [quizScore, setQuizScore] = useState(0);
  const [quizAnswered, setQuizAnswered] = useState<number | null>(null);
  const [quizFinished, setQuizFinished] = useState(false);

  const quizQuestions = [
    {
      q: "Agar aaj Somwar (Monday) hai, to 3 din baad kaun sa din hoga?",
      options: [
        "Budhwar (Wednesday)",
        "Guruwar (Thursday)",
        "Shukrawar (Friday)",
        "Mangalwar (Tuesday)",
      ],
      ans: 1,
      explanation: "Monday + 3 din = Thursday (Guruwar)",
    },
    {
      q: "Agar aapke paas 12 phal the aur aapne 4 padosi ko diye aur 3 khaye, kitne bache?",
      options: ["4", "5", "6", "7"],
      ans: 1,
      explanation: "12 - 4 - 3 = 5 phal bache.",
    },
    {
      q: "Inme se kaun sa Bharat ka rashtriya phool (National Flower) hai?",
      options: ["Gulab (Rose)", "Kamal (Lotus)", "Genda (Marigold)", "Surajmukhi (Sunflower)"],
      ans: 1,
      explanation: "Kamal (Lotus) Bharat ka rashtriya phool hai.",
    },
    {
      q: "Suraj kis disha se ugta hai (rises)?",
      options: ["West (Paschim)", "North (Uttar)", "East (Purva)", "South (Dakshin)"],
      ans: 2,
      explanation: "Suraj hamesha Purva (East) se ugta hai.",
    },
    {
      q: "Ek dukan mein 1 biscuit packet ₹10 ka hai. 4 packet khareedne par ₹5 discount milta hai. Kul kitne rupaye lagenge?",
      options: ["₹40", "₹35", "₹30", "₹45"],
      ans: 1,
      explanation: "4 × 10 = 40, 40 - 5 = ₹35",
    },
  ];

  // Start Memory Match
  const startMemoryMatch = () => {
    const pairCount = level === "Easy" ? 4 : level === "Medium" ? 6 : 8;
    const selected = EMOJI_PAIRS.slice(0, pairCount);
    const deck = [...selected, ...selected]
      .sort(() => Math.random() - 0.5)
      .map((item, i) => ({
        id: i,
        emoji: item.emoji,
        name: item.name,
        flipped: false,
        matched: false,
      }));
    setCards(deck);
    setSelectedCards([]);
    setMatches(0);
    setMoves(0);
    setGameWon(false);
    setGameTimer(0);
    setActiveGame("Memory Match");
  };

  useEffect(() => {
    let interval: ReturnType<typeof setInterval> | undefined;
    if (activeGame === "Memory Match" && !gameWon) {
      interval = setInterval(() => setGameTimer((t) => t + 1), 1000);
    }
    return () => clearInterval(interval);
  }, [activeGame, gameWon]);

  const handleCardClick = async (id: number) => {
    if (cards[id].flipped || cards[id].matched || selectedCards.length >= 2) return;
    const newCards = [...cards];
    newCards[id].flipped = true;
    setCards(newCards);
    const newSelected = [...selectedCards, id];
    setSelectedCards(newSelected);

    if (newSelected.length === 2) {
      const nextMoves = moves + 1;
      setMoves(nextMoves);
      const [firstId, secondId] = newSelected;
      if (newCards[firstId].emoji === newCards[secondId].emoji) {
        newCards[firstId].matched = true;
        newCards[secondId].matched = true;
        setCards(newCards);
        setSelectedCards([]);
        const totalMatches = matches + 1;
        setMatches(totalMatches);
        const targetMatches = level === "Easy" ? 4 : level === "Medium" ? 6 : 8;

        if (totalMatches === targetMatches) {
          setGameWon(true);
          const score = Math.max(100, 800 - nextMoves * 15 - gameTimer * 2);
          await offlineDB.saveGameScore({
            game_type: "memory_match",
            game_name: `Memory Match (${level})`,
            score,
            moves: nextMoves,
            time_seconds: gameTimer,
            difficulty: level,
            stars: nextMoves <= targetMatches * 2 ? 3 : 2,
          });
        }
      } else {
        setTimeout(() => {
          newCards[firstId].flipped = false;
          newCards[secondId].flipped = false;
          setCards([...newCards]);
          setSelectedCards([]);
        }, 800);
      }
    }
  };

  return (
    <Screen>
      <PageTitle
        title="Brain Games & Puzzles"
        subtitle="Dimaag ko tej rakhne ke liye offline playable cognitive games"
      />

      {/* Game 1: Sliding Tile Puzzle */}
      {activeGame === "Sliding Puzzle" ? (
        <SlidingPuzzleGame onBack={() => setActiveGame(null)} difficulty={level} />
      ) : activeGame === "Stroop Test" ? (
        /* Game 2: Stroop Color Agility Test */
        <StroopGame onBack={() => setActiveGame(null)} />
      ) : activeGame === "Pattern Recall" ? (
        /* Game 3: Pattern & Audio Sequence Recall */
        <PatternRecallGame onBack={() => setActiveGame(null)} />
      ) : activeGame === "Memory Match" ? (
        /* Game 4: Memory Match */
        <Card className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="font-display text-lg font-semibold">Memory Match ({level})</h2>
              <p className="text-xs text-muted-foreground">Pairs match karein · Moves: {moves}</p>
            </div>
            <div className="flex items-center gap-2">
              <Pill tone="primary">
                <Timer className="h-3 w-3" /> {gameTimer}s
              </Pill>
              <button
                onClick={() => setActiveGame(null)}
                className="press rounded-xl border border-border px-3 py-1.5 text-xs font-semibold"
              >
                Exit
              </button>
            </div>
          </div>

          {gameWon ? (
            <div className="py-8 text-center space-y-3 animate-in zoom-in-95 duration-300">
              <div className="mx-auto grid h-16 w-16 place-items-center rounded-3xl bg-success/20 text-success">
                <Award className="h-8 w-8" />
              </div>
              <h3 className="font-display text-xl font-bold text-success">
                Shabaash! Game Complete 🎉
              </h3>
              <p className="text-sm text-muted-foreground">
                Aapne {moves} moves aur {gameTimer} seconds mein complete kiya.
              </p>
              <p className="text-xs font-semibold text-emerald-600 dark:text-emerald-400">
                ✓ Recorded in Offline Database
              </p>
              <div className="flex justify-center gap-2 pt-2">
                <ActionButton onClick={startMemoryMatch} icon={RotateCcw}>
                  Play again
                </ActionButton>
                <ActionButton variant="outline" onClick={() => setActiveGame(null)}>
                  All Games
                </ActionButton>
              </div>
            </div>
          ) : (
            <div
              className={`grid gap-2.5 ${
                cards.length <= 8
                  ? "grid-cols-4"
                  : cards.length <= 12
                    ? "grid-cols-4"
                    : "grid-cols-4"
              }`}
            >
              {cards.map((c) => (
                <button
                  key={c.id}
                  onClick={() => handleCardClick(c.id)}
                  className={`press aspect-square rounded-2xl text-2xl font-bold transition-all duration-200 grid place-items-center ${
                    c.flipped || c.matched
                      ? "bg-card border-2 border-primary text-foreground shadow-sm"
                      : "gradient-primary text-primary-foreground shadow-lift hover:opacity-95"
                  }`}
                >
                  {c.flipped || c.matched ? c.emoji : "?"}
                </button>
              ))}
            </div>
          )}
        </Card>
      ) : activeGame === "Daily Quiz" ? (
        /* Game 5: Daily Quiz */
        <Card className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="font-display text-lg font-semibold">
              Daily Quiz ({quizIdx + 1}/{quizQuestions.length})
            </h2>
            <button
              onClick={() => setActiveGame(null)}
              className="press rounded-xl border border-border px-3 py-1.5 text-xs font-semibold"
            >
              Exit
            </button>
          </div>

          {quizFinished ? (
            <div className="py-8 text-center space-y-3 animate-in zoom-in-95 duration-300">
              <div className="mx-auto grid h-16 w-16 place-items-center rounded-3xl bg-success/20 text-success">
                <Award className="h-8 w-8" />
              </div>
              <h3 className="font-display text-xl font-bold">Quiz Complete!</h3>
              <p className="text-sm text-muted-foreground">
                Score: <strong className="text-primary">{quizScore}</strong> /{" "}
                {quizQuestions.length}
              </p>
              <p className="text-xs font-semibold text-emerald-600 dark:text-emerald-400">
                ✓ Saved to Offline SQLite Storage
              </p>
              <ActionButton
                onClick={() => {
                  setQuizIdx(0);
                  setQuizScore(0);
                  setQuizFinished(false);
                  setQuizAnswered(null);
                }}
                icon={RotateCcw}
                className="mx-auto mt-2"
              >
                Restart Quiz
              </ActionButton>
            </div>
          ) : (
            <div className="space-y-4">
              <p className="font-display text-base font-medium">{quizQuestions[quizIdx].q}</p>
              <div className="space-y-2">
                {quizQuestions[quizIdx].options.map((opt, idx) => (
                  <button
                    key={opt}
                    onClick={async () => {
                      if (quizAnswered !== null) return;
                      setQuizAnswered(idx);
                      const isCorrect = idx === quizQuestions[quizIdx].ans;
                      const nextScore = isCorrect ? quizScore + 1 : quizScore;
                      if (isCorrect) {
                        setQuizScore(nextScore);
                      }
                      setTimeout(async () => {
                        if (quizIdx + 1 < quizQuestions.length) {
                          setQuizIdx((i) => i + 1);
                          setQuizAnswered(null);
                        } else {
                          setQuizFinished(true);
                          await offlineDB.saveGameScore({
                            game_type: "daily_quiz",
                            game_name: "Daily Logic Quiz",
                            score: nextScore * 100,
                            moves: quizQuestions.length,
                            time_seconds: 45,
                            difficulty: level,
                            stars: nextScore >= 4 ? 3 : nextScore >= 3 ? 2 : 1,
                          });
                        }
                      }, 1100);
                    }}
                    className={`press w-full text-left rounded-2xl p-3.5 text-sm font-semibold border transition-all ${
                      quizAnswered === null
                        ? "border-border bg-card hover:border-primary"
                        : idx === quizQuestions[quizIdx].ans
                          ? "border-success bg-success/15 text-success"
                          : quizAnswered === idx
                            ? "border-destructive bg-destructive/15 text-destructive"
                            : "border-border bg-card opacity-60"
                    }`}
                  >
                    {opt}
                  </button>
                ))}
              </div>
            </div>
          )}
        </Card>
      ) : (
        /* Main Games Hub View */
        <>
          {/* Difficulty Switcher */}
          <div className="glass-card flex gap-1.5 p-1.5 mb-4">
            {levels.map((l) => (
              <button
                key={l}
                onClick={() => setLevel(l)}
                className={`press min-h-[42px] flex-1 rounded-xl text-sm font-semibold transition-all ${
                  level === l
                    ? "gradient-primary text-primary-foreground shadow-sm"
                    : "text-muted-foreground"
                }`}
              >
                {l}
              </button>
            ))}
          </div>

          {/* Featured 15-Puzzle Card */}
          <Card className="gradient-primary border-0 text-primary-foreground mb-4">
            <div className="flex items-start gap-3">
              <div className="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-white/20">
                <Grid3X3 className="h-6 w-6 text-white" />
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <span className="text-[10px] font-bold uppercase tracking-wider bg-white/20 px-2 py-0.5 rounded-full">
                    Classic Brain Teaser
                  </span>
                </div>
                <h3 className="font-display text-lg font-bold mt-1">15-Tile Sliding Puzzle</h3>
                <p className="text-xs opacity-90">
                  Tiles ko slide karke order 1 to {level === "Hard" ? "15" : "8"} mein arrange
                  karein.
                </p>
              </div>
            </div>
            <ActionButton
              variant="soft"
              icon={Play}
              className="mt-4 w-full bg-white/20 hover:bg-white/30 text-white border-0"
              onClick={() => setActiveGame("Sliding Puzzle")}
            >
              Play Sliding Puzzle ({level})
            </ActionButton>
          </Card>

          {/* Cognitive Games Grid */}
          <div className="space-y-3">
            <SectionHeading title={`All Cognitive Brain Games · ${level}`} />

            <div className="grid grid-cols-1 md:grid-cols-2 gap-3.5">
              {/* Game 1: Stroop Test */}
              <Card className="p-4">
                <div className="flex items-start gap-3">
                  <div className="grid h-11 w-11 shrink-0 place-items-center rounded-2xl bg-amber-500/15 text-amber-600 dark:text-amber-400">
                    <Zap className="h-5 w-5" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="font-display text-[15px] font-semibold">Stroop Color Agility</p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      Shabd ke bajaye uske font rang par dhyan dein (Quick reflexes)
                    </p>
                    <div className="mt-2 flex gap-1.5">
                      <Pill tone="primary">
                        <Timer className="h-3 w-3" /> 2 min
                      </Pill>
                      <Pill>Neuro-Agility</Pill>
                    </div>
                  </div>
                  <button
                    onClick={() => setActiveGame("Stroop Test")}
                    aria-label="Start Stroop Test"
                    className="press grid h-11 w-11 shrink-0 place-items-center rounded-full bg-secondary text-primary"
                  >
                    <Play className="h-[18px] w-[18px]" />
                  </button>
                </div>
              </Card>

              {/* Game 2: Audio-Visual Pattern Recall */}
              <Card className="p-4">
                <div className="flex items-start gap-3">
                  <div className="grid h-11 w-11 shrink-0 place-items-center rounded-2xl bg-primary/12 text-primary">
                    <Sparkles className="h-5 w-5" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="font-display text-[15px] font-semibold">
                      Pattern & Sound Sequence
                    </p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      Glowing lights aur musical tones ka sequence yaad karein
                    </p>
                    <div className="mt-2 flex gap-1.5">
                      <Pill tone="primary">
                        <Timer className="h-3 w-3" /> 4 min
                      </Pill>
                      <Pill>Audio-Visual</Pill>
                    </div>
                  </div>
                  <button
                    onClick={() => setActiveGame("Pattern Recall")}
                    aria-label="Start Pattern Recall"
                    className="press grid h-11 w-11 shrink-0 place-items-center rounded-full bg-secondary text-primary"
                  >
                    <Play className="h-[18px] w-[18px]" />
                  </button>
                </div>
              </Card>

              {/* Game 3: Memory Match Pairs */}
              <Card className="p-4">
                <div className="flex items-start gap-3">
                  <div className="grid h-11 w-11 shrink-0 place-items-center rounded-2xl bg-emerald-500/15 text-emerald-600 dark:text-emerald-400">
                    <Brain className="h-5 w-5" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="font-display text-[15px] font-semibold">Memory Match Cards</p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      Pairs yaad karke match karein · Combo score booster
                    </p>
                    <div className="mt-2 flex gap-1.5">
                      <Pill tone="primary">
                        <Timer className="h-3 w-3" /> 5 min
                      </Pill>
                      <Pill>{level}</Pill>
                    </div>
                  </div>
                  <button
                    onClick={startMemoryMatch}
                    aria-label="Start Memory Match"
                    className="press grid h-11 w-11 shrink-0 place-items-center rounded-full bg-secondary text-primary"
                  >
                    <Play className="h-[18px] w-[18px]" />
                  </button>
                </div>
              </Card>

              {/* Game 4: Daily Logic & Teasers Quiz */}
              <Card className="p-4">
                <div className="flex items-start gap-3">
                  <div className="grid h-11 w-11 shrink-0 place-items-center rounded-2xl bg-accent/20 text-accent">
                    <Puzzle className="h-5 w-5" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="font-display text-[15px] font-semibold">
                      Daily Brain Teaser & Logic Quiz
                    </p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      Rozana 5 rochak paheliyan aur ganitiya sawal
                    </p>
                    <div className="mt-2 flex gap-1.5">
                      <Pill tone="accent">5 Questions</Pill>
                      <Pill>Reasoning</Pill>
                    </div>
                  </div>
                  <button
                    onClick={() => {
                      setQuizIdx(0);
                      setQuizScore(0);
                      setQuizFinished(false);
                      setQuizAnswered(null);
                      setActiveGame("Daily Quiz");
                    }}
                    aria-label="Start Daily Quiz"
                    className="press grid h-11 w-11 shrink-0 place-items-center rounded-full bg-secondary text-primary"
                  >
                    <Play className="h-[18px] w-[18px]" />
                  </button>
                </div>
              </Card>
            </div>
          </div>

          {/* Live Offline SQL Database Inspector */}
          <div className="mt-6">
            <SectionHeading title="Offline SQLite Database Storage" />
            <div className="mt-3">
              <OfflineSqlViewer />
            </div>
          </div>
        </>
      )}
    </Screen>
  );
}
