import React, { useState, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import Navbar from "../../components/Navbar";
import Footer from "../HomePage/Footer";
import { gameRegistryUtils } from "../../config/gameRegistry";
import { difficultyLevels } from "../../config/difficulty";
import { gameCategory } from "../../config/categories";
import { gameType } from "../../config/type";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useAtividadesTour } from "./hooks/useAtividadesTour";
import "shepherd.js/dist/css/shepherd.css";
import "../../styles/shepherd-theme.css";

const Atividades = () => {
  const navigate = useNavigate();

  // Inicializa o tour guiado
  useAtividadesTour();
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [selectedDifficulty, setSelectedDifficulty] = useState("all");
  const [selectedType, setSelectedType] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(8);

  // Obter jogos filtrados
  const filteredGames = useMemo(() => {
    let games = gameRegistryUtils.getActiveGames();

    // Filtrar por categoria
    if (selectedCategory !== "all") {
      games = games.filter((game) => game.categoria === selectedCategory);
    }

    // Filtrar por dificuldade
    if (selectedDifficulty !== "all") {
      games = games.filter((game) => game.dificuldade === selectedDifficulty);
    }

    // Filtrar por tipo
    if (selectedType !== "all") {
      games = games.filter((game) => game.type === selectedType);
    }

    // Filtrar por busca
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      games = games.filter(
        (game) =>
          game.gameName.toLowerCase().includes(query) ||
          game.descricao.toLowerCase().includes(query) ||
          (game.conceitos &&
            game.conceitos.some((concept) =>
              concept.toLowerCase().includes(query)
            ))
      );
    }

    return games;
  }, [selectedCategory, selectedDifficulty, selectedType, searchQuery]);

  // Paginação
  const totalPages = Math.ceil(filteredGames.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentGames = filteredGames.slice(startIndex, endIndex);

  // Reset para página 1 quando filtros mudam
  React.useEffect(() => {
    setCurrentPage(1);
  }, [
    selectedCategory,
    selectedDifficulty,
    selectedType,
    searchQuery,
    itemsPerPage,
  ]);

  const getDifficultyColor = (difficulty) => {
    return difficultyLevels[difficulty]?.color || "#6c757d";
  };

  const getCategoryColor = (category) => {
    return gameCategory[category]?.color || "#6c757d";
  };

  const getTypeColor = (type) => {
    return gameType[type]?.color || "#6c757d";
  };

  const getNameFromType = (type) => {
    return gameType[type]?.name || type;
  };

  const handleGameSelect = (game) => {
    if (game.route) {
      navigate(game.route);
    } else {
      navigate(`/atividades/programacao/${game.gameId || game.id}`);
    }
  };

  const handleClearFilters = () => {
    setSelectedCategory("all");
    setSelectedDifficulty("all");
    setSelectedType("all");
    setSearchQuery("");
  };

  return (
    <>
      <Navbar />

      {/* Background Gradient */}
      <div
        className="isolate -z-10 fixed h-full w-full top-0 left-0"
        style={{
          background: "#EAEEF5",
        }}
      ></div>

      <section className="flex flex-col relative mt-32 lg:mt-[195px]">
        {/* Container principal */}
        <div className="mx-auto max-w-7xl px-6 py-24 sm:py-24 lg:py-32 lg:px-8">
          {/* Header */}
          <div className="mb-8 flex flex-col">
            <div className="flex flex-col justify-start gap-4">
              <h3 className="font-bold text-gray-900 tracking-tight text-4xl sm:text-5xl">
                Atividades de Programação
              </h3>
              <p className="mt-2 font-normal text-gray-700 text-base">
                Explore nossos jogos educativos para aprender programação.
              </p>
            </div>
          </div>

          {/* Filtros */}
          <div className="mb-12 relative bg-white/50 backdrop-blur-lg shadow-2xl rounded-xl border border-gray-200 p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {/* Busca */}
              <div className="lg:col-span-4">
                <label className="block text-sm font-semibold text-gray-900 mb-3">
                  Buscar atividades
                </label>
                <div className="relative">
                  <input
                    type="text"
                    placeholder="Digite o nome ou conceito..."
                    className="w-full px-6 py-3 pr-12 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent outline-none transition-all bg-white text-gray-900"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                  />
                  <div className="absolute inset-y-0 right-0 flex items-center pr-4">
                    <svg
                      className="w-5 h-5 text-gray-400"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="2"
                        d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                      />
                    </svg>
                  </div>
                </div>
              </div>

              {/* Categoria */}
              <div>
                <label className="block text-sm font-semibold text-gray-900 mb-3">
                  Categoria
                </label>
                <select
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent outline-none transition-all bg-white text-gray-900"
                  value={selectedCategory}
                  onChange={(e) => setSelectedCategory(e.target.value)}
                >
                  <option value="all">Todas as categorias</option>
                  {Object.entries(gameCategory).map(([key, category]) => (
                    <option key={key} value={key}>
                      {category.name}
                    </option>
                  ))}
                </select>
              </div>

              {/* Tipo */}
              <div>
                <label className="block text-sm font-semibold text-gray-900 mb-3">
                  Tipo
                </label>
                <select
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent outline-none transition-all bg-white text-gray-900"
                  value={selectedType}
                  onChange={(e) => setSelectedType(e.target.value)}
                >
                  <option value="all">Todos os tipos</option>
                  {Object.entries(gameType).map(([key, type]) => (
                    <option key={key} value={key}>
                      {type.name}
                    </option>
                  ))}
                </select>
              </div>

              {/* Dificuldade */}
              <div>
                <label className="block text-sm font-semibold text-gray-900 mb-3">
                  Dificuldade
                </label>
                <select
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent outline-none transition-all bg-white text-gray-900"
                  value={selectedDifficulty}
                  onChange={(e) => setSelectedDifficulty(e.target.value)}
                >
                  <option value="all">Todas as dificuldades</option>
                  {Object.entries(difficultyLevels).map(([key, level]) => (
                    <option key={key} value={key}>
                      {level.name}
                    </option>
                  ))}
                </select>
              </div>

              {/* Itens por página */}
              <div>
                <label className="block text-sm font-semibold text-gray-900 mb-3">
                  Itens por página
                </label>
                <select
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent outline-none transition-all bg-white text-gray-900"
                  value={itemsPerPage}
                  onChange={(e) => setItemsPerPage(Number(e.target.value))}
                >
                  <option value={8}>8 atividades</option>
                  <option value={16}>16 atividades</option>
                  <option value={32}>32 atividades</option>
                </select>
              </div>
            </div>

            {/* Botão limpar filtros */}
            {(selectedCategory !== "all" ||
              selectedDifficulty !== "all" ||
              selectedType !== "all" ||
              searchQuery) && (
              <div className="mt-6 text-center">
                <button
                  onClick={handleClearFilters}
                  className="px-6 py-3 bg-gradient-to-r from-red-600 via-pink-600 to-purple-600 hover:from-red-700 hover:via-pink-700 hover:to-purple-700 text-white font-bold rounded-full shadow-lg transition-all duration-300 transform hover:scale-105"
                >
                  Limpar todos os filtros
                </button>
              </div>
            )}
          </div>

          {/* Resultado e contador */}
          <div className="flex items-center justify-between mb-8">
            <h4 className="text-2xl font-bold text-gray-900">
              {searchQuery
                ? `Resultados para "${searchQuery}"`
                : "Todas as Atividades"}
            </h4>
            <div className="bg-brand-500 text-white px-6 py-2 rounded-full text-sm font-bold">
              {filteredGames.length}{" "}
              {filteredGames.length === 1 ? "atividade" : "atividades"}
            </div>
          </div>

          {/* Grid de Cards */}
          {currentGames.length > 0 ? (
            <>
              <div className="my-3 grid grid-cols-1 gap-4 md:gap-7 sm:grid-cols-2 lg:grid-cols-2">
                {currentGames.map((game) => (
                  <div
                    key={game.gameId || game.id}
                    onClick={() => handleGameSelect(game)}
                    data-prd-ready={game.prdReady}
                    className="relative bg-white/50 backdrop-blur-lg shadow-md hover:shadow-xl rounded-xl border border-gray-200 p-6 flex flex-col md:flex-row gap-6 cursor-pointer transition-all duration-300 hover:scale-[1.02] group data-[prd-ready=false]:opacity-50"
                  >
                    {/* Thumbnail */}
                    <div className="flex-shrink-0 rounded-lg h-16 w-16 md:h-20 md:w-20">
                      <div className="relative w-full h-full rounded-xl overflow-hidden group-hover:scale-110 transition-transform duration-300 bg-gradient-to-br from-blue-100 to-purple-100">
                        <img 
                          src={game.thumbnail || game.icon} 
                          alt={game.gameName}
                          className="w-full h-full object-cover"
                          loading="lazy"
                          onError={(e) => {
                            e.target.style.display = 'none';
                            e.target.parentElement.innerHTML = `<div class="w-full h-full flex items-center justify-center text-4xl md:text-5xl">${game.icon}</div>`;
                          }}
                        />
                      </div>
                    </div>

                    {/* Conteúdo */}
                    <div className="flex h-full w-full flex-col items-start gap-3 justify-between">
                      <div className="flex w-full flex-col gap-3">
                        <div className="flex w-full flex-row items-start justify-between gap-3">
                          <h3 className="max-w-[400px] overflow-hidden truncate text-ellipsis font-semibold text-gray-900 tracking-tight text-lg md:text-xl">
                            {game.gameName}
                          </h3>

                          {/* Badges */}
                          <div className="flex flex-wrap gap-2 justify-end">
                            <span
                              className="px-3 py-1 text-xs font-bold rounded-full text-white whitespace-nowrap"
                              style={{
                                backgroundColor: getCategoryColor(
                                  game.categoria
                                ),
                              }}
                            >
                              {gameCategory[game.categoria]?.name}
                            </span>
                            {!game.prdReady && (
                              <span className="px-3 py-1 text-xs font-bold rounded-full text-white whitespace-nowrap bg-gray-500">
                                Em desenvolvimento
                              </span>
                            )}
                          </div>
                        </div>

                        <p className="line-clamp-2 font-normal text-gray-700 text-sm md:text-base">
                          {game.descricao}
                        </p>

                        {/* Informações adicionais */}
                        <div className="flex flex-wrap gap-3 text-xs text-gray-600">
                          <span className="flex items-center gap-1">
                            ⏱️ {game.tempoEstimado}
                          </span>
                          <span className="flex items-center gap-1">
                            🎯 {game.faixaEtaria}
                          </span>
                          <span className="flex items-center gap-1">
                            📊 {game.fases?.length || 0} fases
                          </span>
                        </div>

                        {/* Conceitos */}
                        {game.conceitos && game.conceitos.length > 0 && (
                          <div className="flex flex-wrap gap-2">
                            {game.conceitos.slice(0, 3).map((concept) => (
                              <span
                                key={concept}
                                className="px-3 py-1 bg-gray-100 text-gray-700 text-xs rounded-full"
                              >
                                {concept}
                              </span>
                            ))}
                            {game.conceitos.length > 3 && (
                              <span className="group/conceitos-extra relative inline-flex">
                                <span
                                  className="px-3 py-1 bg-gray-100 text-gray-700 text-xs rounded-full"
                                  tabIndex={0}
                                >
                                  +{game.conceitos.length - 3}
                                </span>

                                <span className="pointer-events-none absolute left-1/2 top-0 z-20 w-max max-w-[260px] -translate-x-1/2 -translate-y-[calc(100%+8px)] rounded-md bg-gray-900 px-3 py-2 text-[11px] leading-relaxed text-white opacity-0 shadow-lg transition-opacity duration-150 group-hover/conceitos-extra:opacity-100 group-focus-within/conceitos-extra:opacity-100">
                                  {game.conceitos.slice(3).join(", ")}
                                </span>
                              </span>
                            )}
                          </div>
                        )}
                      </div>

                      {/* Badges de tipo e dificuldade */}
                      <div className="flex flex-wrap gap-2 w-full">
                        <div className="relative bg-white/50 backdrop-blur-lg shadow-lg rounded-md border border-gray-200 inline-flex items-center">
                          <span
                            className="px-3 py-1 text-xs font-bold text-white rounded-l-md"
                            style={{ backgroundColor: getTypeColor(game.type) }}
                          >
                            {getNameFromType(game.type)}
                          </span>
                          <span
                            className="px-3 py-1 text-xs font-bold text-white rounded-r-md"
                            style={{
                              backgroundColor: getDifficultyColor(
                                game.dificuldade
                              ),
                            }}
                          >
                            {difficultyLevels[game.dificuldade]?.name}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* Paginação */}
              {totalPages > 1 && (
                <div className="mt-12 flex items-center justify-center gap-4">
                  <button
                    onClick={() =>
                      setCurrentPage((prev) => Math.max(1, prev - 1))
                    }
                    disabled={currentPage === 1}
                    className="p-2 rounded-lg bg-white border border-gray-200 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                  >
                    <ChevronLeft className="w-5 h-5 text-gray-900" />
                  </button>

                  <div className="flex items-center gap-2">
                    {Array.from({ length: totalPages }, (_, i) => i + 1).map(
                      (page) => (
                        <button
                          key={page}
                          onClick={() => setCurrentPage(page)}
                          className={`px-4 py-2 rounded-lg font-semibold transition-all ${
                            currentPage === page
                              ? "bg-gradient-to-r from-red-600 via-pink-600 to-purple-600 text-white shadow-lg"
                              : "bg-white border border-gray-200 text-gray-900 hover:bg-gray-50"
                          }`}
                        >
                          {page}
                        </button>
                      )
                    )}
                  </div>

                  <button
                    onClick={() =>
                      setCurrentPage((prev) => Math.min(totalPages, prev + 1))
                    }
                    disabled={currentPage === totalPages}
                    className="p-2 rounded-lg bg-white border border-gray-200 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                  >
                    <ChevronRight className="w-5 h-5 text-gray-900" />
                  </button>
                </div>
              )}
            </>
          ) : (
            // Estado vazio
            <div className="text-center py-20">
              <div className="text-8xl mb-8">🎮</div>
              <h3 className="text-3xl font-bold text-gray-900 mb-6">
                Nenhuma atividade encontrada
              </h3>
              <p className="text-xl text-gray-700 mb-8 max-w-md mx-auto">
                Não encontramos atividades que correspondam aos seus critérios.
                Que tal tentar uma busca diferente?
              </p>
              <button
                onClick={handleClearFilters}
                className="px-8 py-4 bg-gradient-to-r from-red-600 via-pink-600 to-purple-600 hover:from-red-700 hover:via-pink-700 hover:to-purple-700 text-white font-bold rounded-full shadow-lg transition-all duration-300 transform hover:scale-105"
              >
                Ver todas as atividades
              </button>
            </div>
          )}
        </div>
      </section>

      {/* Footer */}
      <Footer />
    </>
  );
};

export default Atividades;
