/**
 * @fileoverview React component for SeletorDeFases.jsx
 * 
 * @module components.game.SeletorDeFases
 */


import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";
import ConfirmacaoModal from "./ConfirmacaoModal";
import { Lock, CheckCircle, Star, X } from "lucide-react";
import { getUnlockedPhases } from "../../utils/phaseUtils";

export default function SeletorDeFases({
  isVisible,
  onClose,
  gameConfig,
  currentPhase,
  onChangePhase,
  onResetProgress,
}) {
  const gameId = gameConfig.gameId;
  const totalPhases = gameConfig.fases.length;
  const storageKey = `${gameId}-completed-phases`;
  const [completedPhases, setCompletedPhases] = useState([]);
  const [showResetConfirmation, setShowResetConfirmation] = useState(false);

  useEffect(() => {
    if (!isVisible) return;
    const salvo = localStorage.getItem(storageKey);
    if (salvo) {
      try {
        const fases = JSON.parse(salvo);
        setCompletedPhases(fases);
      } catch {
        setCompletedPhases([]);
      }
    } else {
      setCompletedPhases([]);
    }
  }, [isVisible, storageKey]);

  const unlockedPhases = getUnlockedPhases(completedPhases, totalPhases);

  const selectPhase = (number) => {
    if (!unlockedPhases.includes(number)) return;
    if (onChangePhase) onChangePhase(number);
    onClose();
  };

  if (!isVisible) return null;

  return (
    <div
      className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50"
      onClick={onClose}
    >
      <div
        className="bg-white/95 backdrop-blur-sm border border-white/30 rounded-xl shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between p-6 border-b border-white/20">
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center text-black">
              <Star className="w-5 h-5" />
            </div>
            <h3 className="text-xl font-title font-bold text-gray-800">
              Selecionar Fase - {gameConfig.gameName || "Jogo"}
            </h3>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 cancel-icon bg-gray-200 hover:bg-gray-300 flex items-center justify-center text-gray-600 transition-colors"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {Array.from({ length: totalPhases }, (_, i) => {
              const phaseNumber = i + 1;
              const isUnlocked = unlockedPhases.includes(phaseNumber);
              const wasCompleted = completedPhases.includes(phaseNumber);
              const isCurrent = currentPhase === phaseNumber;
              const phaseData = gameConfig.fases[i];

              return (
                <div
                  key={phaseNumber}
                  className={`bg-white/80 backdrop-blur-sm border border-white/30 rounded-xl shadow-lg p-4 cursor-pointer transition-all duration-200 border-2 ${
                    isCurrent
                      ? "border-red-500 ring-2 ring-red-200"
                      : isUnlocked
                        ? "border-transparent hover:border-red-300"
                        : "border-gray-200 opacity-60 cursor-not-allowed"
                  }`}
                  onClick={() => isUnlocked && selectPhase(phaseNumber)}
                >
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center space-x-2">
                      <div
                        className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-title font-bold ${
                          wasCompleted
                            ? "bg-green-100 text-green-600"
                            : !isUnlocked
                              ? "bg-gray-100 text-gray-400"
                              : "bg-red-100 text-red-600"
                        }`}
                      >
                        {wasCompleted ? (
                          <CheckCircle className="w-4 h-4" />
                        ) : !isUnlocked ? (
                          <Lock className="w-4 h-4" />
                        ) : (
                          phaseNumber
                        )}
                      </div>
                    </div>
                    {isCurrent && (
                      <span className="text-xs bg-red-600 text-white px-2 py-1 rounded-full font-medium">
                        Atual
                      </span>
                    )}
                  </div>

                  <div className="space-y-2">
                    <h4 className="font-title font-semibold text-gray-800 text-sm">
                      Fase {phaseNumber}
                    </h4>
                    <h5 className="font-medium text-gray-700 text-sm">
                      {phaseData.nome}
                    </h5>
                    <p className="text-xs text-gray-600 line-clamp-2">
                      {phaseData.descricao}
                    </p>
                    <span className="inline-block mt-1 px-2 py-0.5 rounded-full text-xs font-medium bg-gray-200 text-gray-700">
                      {phaseData.dificuldade}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

          <div className="p-4 border-t border-white/20 flex justify-center">
            <button
              className="bg-green-100 text-black px-6 py-2 rounded-full font-semibold shadow transition-all duration-200 hover:bg-green-200"
              onClick={() => setShowResetConfirmation(true)}
            >
              Resetar TODO o progresso do jogo
            </button>
          </div>

          <ConfirmacaoModal
            isOpen={showResetConfirmation}
            onClose={() => setShowResetConfirmation(false)}
            onConfirm={() => {
              if (onResetProgress) onResetProgress();
              setShowResetConfirmation(false);
              onClose();
            }}
            title="Resetar progresso"
            message="Tem certeza que deseja apagar TODO o progresso e blocos salvos deste jogo? Esta ação não pode ser desfeita."
          />
      </div>
    </div>
  );
}

SeletorDeFases.propTypes = {
  isVisible: PropTypes.bool,
  onClose: PropTypes.func,
  gameConfig: PropTypes.object.isRequired,
  onChangePhase: PropTypes.func,
  onResetProgress: PropTypes.func,
};
