import React, { useEffect, useState } from "react"
import { useLocation } from "react-router-dom"
import HandleNavigate from "../../utils/HandleNavigate/HandleNavigate"
import Navbar from "../../components/Navbar/Navbar.jsx"
import Background from "../../assets/backgrounds/Background.jsx"
import Footer from "../../components/Footer/Footer.jsx"
import useRequireAuth from "../../hooks/useRequireAuth.jsx"
import ButtonGreen from "../../components/Buttons/ButtonGreen.jsx"
import {
  FaFilter,
  FaCalendarAlt,
  FaArrowUp,
  FaArrowDown,
  FaSortAlphaDown,
  FaSortAlphaUp,
  FaQuestionCircle,
  FaCheckCircle,
  FaCircle,
} from "react-icons/fa"
import SearchBox from "../../components/Search/SearchBox.jsx"
import PopUp from "../../components/PopUp/PopUp.jsx"
import { motion } from "framer-motion"

const deckTypes = [
  { label: "Luck", color: "var(--color-luck)" },
  { label: "Question", color: "var(--color-question)" },
  { label: "Joker", color: "var(--color-fun)" },
]

const origins = ["Mind", "Vállalati", "Saját"]

const sortOptions = [
  { value: "date-asc", label: "📅↑" },
  { value: "date-desc", label: "📅↓" },
  { value: "abc-asc", label: "A→Z" },
  { value: "abc-desc", label: "Z→A" },
]

const ChooseDeck = () => {
  const location = useLocation()
  const locationUsername = location.state?.username ?? null

  // always call hook (hooks must be called unconditionally) and use as fallback
  const [authUsername] = useRequireAuth({ key: "username", redirectTo: "/" })

  // prefer passed username (from navigate state) over authenticated username
  const username = locationUsername ?? authUsername

  const { goPlayerSetup } = HandleNavigate()

  const [selectedType, setSelectedType] = useState("All")
  const [selectedOrigin, setSelectedOrigin] = useState("Mind")
  const [sortBy, setSortBy] = useState("date-desc")
  const [search, setSearch] = useState("")
  const [showSortHelp, setShowSortHelp] = useState(false)
  const [allDecks, setAllDecks] = useState([])
  const [loading, setLoading] = useState(false)
  const [selectedDeckIds, setSelectedDeckIds] = useState([])

  // Load all decks once
  useEffect(() => {
    let mounted = true
    const load = async () => {
      setLoading(true)
      try {
        const result = await import("../../api/deckApi.js").then((m) => m.getDecksPage(0, 99))
        if (!mounted) return

        console.log("Loaded decks:", result)

        const mapped = (result.decks || []).map((d) => ({
          id: d.id,
          name: d.name,
          type: d.type === 2 ? "Question" : d.type === 1 ? "Joker" : "Luck",
          created: d.creationdate ? new Date(d.creationdate).toLocaleDateString() : "",
          origin: d.ctype === 2 ? "Vállalati" : d.ctype === 0 ? "Mind" : "Saját",
          raw: d,
        }))

        console.log("Mapped decks:", mapped)
        setAllDecks(mapped)
      } catch (err) {
        console.error("Failed to load decks", err)
      } finally {
        setLoading(false)
      }
    }
    load()
    return () => {
      mounted = false
    }
  }, [])

  // Filter logic
  let filteredDecks = allDecks.filter((deck) => {
    const typeMatch = selectedType === "All" || deck.type === selectedType
    const originMatch = selectedOrigin === "Mind" || deck.origin === selectedOrigin
    const searchMatch = !search || deck.name.toLowerCase().includes(search.toLowerCase())
    return typeMatch && originMatch && searchMatch
  })

  // Sort logic
  filteredDecks = [...filteredDecks].sort((a, b) => {
    if (sortBy === "date-asc") {
      return a.created.localeCompare(b.created)
    } else if (sortBy === "date-desc") {
      return b.created.localeCompare(a.created)
    } else if (sortBy === "abc-asc") {
      return a.name.localeCompare(b.name)
    } else if (sortBy === "abc-desc") {
      return b.name.localeCompare(a.name)
    }
    return 0
  })

  // Toggle deck selection
  const toggleDeckSelection = (deckId) => {
    setSelectedDeckIds((prev) => {
      if (prev.includes(deckId)) {
        return prev.filter((id) => id !== deckId)
      } else {
        return [...prev, deckId]
      }
    })
  }

  // Handle continue button
  const handleContinue = () => {
    if (selectedDeckIds.length === 0) {
      alert("Kérlek válassz ki legalább egy paklit!")
      return
    }
    console.log("Kiválasztott pakli ID-k:", selectedDeckIds)
    goPlayerSetup({ deckIds: selectedDeckIds })
  }

  return (
    <div className="flex flex-col min-h-screen overflow-y-auto relative">
      <div className="fixed top-0 left-0 w-full h-full -z-10">
        <Background />
      </div>

      <div className="fixed top-0 left-0 right-0 z-30">
        <Navbar />
      </div>

      <main className="flex-grow text-white px-4 sm:px-6 pt-20 sm:pt-24 pb-16 sm:pb-20">
        <motion.section
          className="max-w-6xl mx-auto"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.7 }}
        >
          {/* Title */}
          <motion.h1
            className="text-3xl sm:text-4xl lg:text-5xl font-extrabold text-green-300 mb-4 sm:mb-6 text-center tracking-wide drop-shadow-lg"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.1 }}
          >
            Válassz Paklikat a Játékhoz
          </motion.h1>

          <motion.p
            className="text-sm sm:text-base lg:text-lg leading-relaxed text-zinc-200 mb-6 sm:mb-10 text-center max-w-3xl mx-auto"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.2 }}
          >
            Válaszd ki azokat a paklikat, amelyekkel játszani szeretnél. Több paklit is kiválaszthatsz
            egyszerre.
          </motion.p>

          {/* Filters */}
          <div className="flex flex-col gap-3 mb-6 sm:mb-10 bg-[color:var(--color-surface)]/80 backdrop-blur-lg rounded-xl sm:rounded-2xl px-4 sm:px-6 py-3 sm:py-4 shadow-lg">
            <div className="flex gap-2 items-center w-full flex-wrap">
              <SearchBox
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                width={240}
                placeholder="Keresés..."
                className="mr-4"
              />
              <FaFilter style={{ color: "var(--color-success)" }} className="mr-1 sm:mr-2 text-sm sm:text-base" />
              <span className="text-[color:var(--color-text)] font-semibold mr-1 sm:mr-2 text-xs sm:text-sm">Típus:</span>
              <button
                className={`px-2 sm:px-3 py-1 rounded-lg font-medium transition-all duration-200 text-xs sm:text-sm ${
                  selectedType === "All"
                    ? "bg-[color:var(--color-surface-selected)] text-[color:var(--color-text)] border border-[color:var(--color-surface)]"
                    : "text-[color:var(--color-text)] bg-[color:var(--color-success)]/10 hover:bg-[color:var(--color-success)]/30"
                }`}
                onClick={() => setSelectedType("All")}
              >
                Mind
              </button>
              {deckTypes.map((type) => (
                <button
                  key={type.label}
                  className={`px-2 sm:px-3 py-1 rounded-lg font-medium transition-all duration-200 ml-1 text-xs sm:text-sm ${
                    selectedType === type.label
                      ? "text-[color:var(--color-text-inverse)] border border-[color:var(--color-surface)]"
                      : "text-[color:var(--color-text)] bg-[color:var(--color-success)]/10 hover:bg-[color:var(--color-success)]/30"
                  }`}
                  style={selectedType === type.label ? { background: type.color } : undefined}
                  onClick={() => setSelectedType(type.label)}
                >
                  {type.label === "Luck" ? "Szerencse" : type.label === "Question" ? "Kérdés" : "Joker"}
                </button>
              ))}
              <span className="text-[color:var(--color-text)] font-semibold mr-1 sm:mr-2 ml-1 sm:ml-2 text-xs sm:text-sm">Eredet:</span>
              <select
                className="px-2 sm:px-3 py-1 rounded-lg bg-[color:var(--color-success)]/10 hover:bg-[color:var(--color-success)]/30 text-[color:var(--color-text)] border-none focus:ring-2 focus:ring-[color:var(--color-success)] outline-none text-xs sm:text-sm"
                value={selectedOrigin}
                onChange={(e) => setSelectedOrigin(e.target.value)}
              >
                {origins.map((origin) => (
                  <option
                    key={origin}
                    value={origin}
                    style={{ backgroundColor: "var(--color-surface)", color: "var(--color-text)" }}
                  >
                    {origin}
                  </option>
                ))}
              </select>
              <span className="text-[color:var(--color-text)] font-semibold mr-1 sm:mr-2 ml-1 sm:ml-2 flex items-center gap-1 text-xs sm:text-sm">
                Rendezés:
                <button
                  type="button"
                  className="ml-1 text-[color:var(--color-success)] hover:text-[color:var(--color-text)] focus:outline-none"
                  onClick={() => setShowSortHelp(true)}
                  aria-label="Rendezési magyarázat"
                  style={{ fontSize: 18, lineHeight: 1 }}
                >
                  <FaQuestionCircle />
                </button>
              </span>
              <select
                className="px-2 sm:px-3 py-1 rounded-lg bg-[color:var(--color-success)]/10 hover:bg-[color:var(--color-success)]/30 text-[color:var(--color-text)] border-none focus:ring-2 focus:ring-[color:var(--color-success)] outline-none text-xs sm:text-sm"
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
              >
                {sortOptions.map((opt) => (
                  <option
                    key={opt.value}
                    value={opt.value}
                    style={{ backgroundColor: "var(--color-surface)", color: "var(--color-text)" }}
                  >
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {showSortHelp && (
            <PopUp onClose={() => setShowSortHelp(false)}>
              <h2 className="text-lg font-bold mb-4">Rendezési lehetőségek</h2>
              <ul className="space-y-2 text-[color:var(--color-night)]">
                <li>
                  <span className="font-bold">📅↑</span> – Dátum szerint növekvő
                </li>
                <li>
                  <span className="font-bold">📅↓</span> – Dátum szerint csökkenő
                </li>
                <li>
                  <span className="font-bold">A→Z</span> – Név szerint növekvő
                </li>
                <li>
                  <span className="font-bold">Z→A</span> – Név szerint csökkenő
                </li>
              </ul>
              <button
                className="mt-6 px-4 py-2 rounded-lg bg-[color:var(--color-success)] text-[color:var(--color-text-inverse)] font-semibold hover:bg-[color:var(--color-success)]/80"
                onClick={() => setShowSortHelp(false)}
              >
                Bezárás
              </button>
            </PopUp>
          )}

          {/* Selection Info */}
          <div className="mb-4 sm:mb-6 text-center">
            <span className="text-[color:var(--color-text)] text-base sm:text-lg font-semibold">
              Kiválasztva: {selectedDeckIds.length} pakli
            </span>
          </div>

          {/* Decks Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 sm:gap-6 lg:gap-8 mt-6 sm:mt-8">
            {loading && (
              <div className="col-span-full text-center text-[color:var(--color-text-muted]">Betöltés...</div>
            )}
            {!loading && filteredDecks.length === 0 && (
              <div className="col-span-full text-center text-[color:var(--color-text-muted]">
                Nincsenek elérhető paklik.
              </div>
            )}
            {!loading &&
              filteredDecks.map((deck) => {
                const deckType = deckTypes.find((t) => t.label === deck.type)
                const borderColor = deckType ? deckType.color : "var(--color-success)"
                const isSelected = selectedDeckIds.includes(deck.id)

                return (
                  <div
                    key={deck.id}
                    className={`relative flex flex-col justify-between h-40 sm:h-48 bg-[color:var(--color-card)] rounded-xl sm:rounded-2xl p-4 sm:p-6 shadow-lg border-t-4 hover:scale-105 transition-transform duration-200 cursor-pointer ${
                      isSelected ? "ring-2 sm:ring-4 ring-[color:var(--color-success)]" : ""
                    }`}
                    style={{ borderTopColor: borderColor }}
                    onClick={() => toggleDeckSelection(deck.id)}
                  >
                    {/* Selection Indicator */}
                    <div className="absolute top-2 sm:top-3 right-2 sm:right-3">
                      {isSelected ? (
                        <FaCheckCircle className="text-2xl sm:text-3xl text-[color:var(--color-success)]" />
                      ) : (
                        <FaCircle className="text-2xl sm:text-3xl text-[color:var(--color-text-muted)] opacity-30" />
                      )}
                    </div>

                    <div>
                      <span
                        className="inline-block px-2 sm:px-3 py-1 rounded-full text-[10px] sm:text-xs font-bold mb-2"
                        style={{
                          background: deckType?.color,
                          color: "var(--color-text-inverse)",
                        }}
                      >
                        {deck.type === "Luck" ? "Szerencse" : deck.type === "Question" ? "Kérdés" : "Joker"}
                      </span>
                      <h2 className="text-base sm:text-xl font-bold text-[color:var(--color-text)] mb-1 truncate">
                        {deck.name}
                      </h2>
                    </div>
                    <div className="text-[color:var(--color-text-muted)] text-xs sm:text-sm mt-2">
                      Létrehozva: {deck.created}
                    </div>
                  </div>
                )
              })}
          </div>

          {/* Continue Button */}
          <div className="flex justify-center mt-8 sm:mt-12">
            <ButtonGreen
              text={`Tovább (${selectedDeckIds.length} pakli kiválasztva)`}
              onClick={handleContinue}
              width="w-auto px-8"
            />
          </div>
        </motion.section>
      </main>

      <footer className="mt-auto">
        <Footer />
      </footer>
    </div>
  )
}

export default ChooseDeck
