import React, { useState, useEffect } from 'react';
import { MapContainer, TileLayer, GeoJSON, FeatureGroup } from 'react-leaflet';
import Button from '../Button/Button';
import { FaPause, FaPlay } from 'react-icons/fa';

const MultipleChoiceMode = ({
  kyrgyzstanRegions,
  setShowResults,
  setGameStarted,
  elapsedTime,
  setElapsedTime,
  isPaused,
  setIsPaused,
  togglePauseMenu,
  showPauseMenu,
  message,
  setMessage,
  navigate,
  setCorrectAnswers,
  setIncorrectAnswers
}) => {
  const [regionData, setRegionData] = useState(null);
  const [guessedRegions, setGuessedRegions] = useState([]);
  const [remainingRegions, setRemainingRegions] = useState([]);
  const [totalRegions, setTotalRegions] = useState(0);
  const [currentRegion, setCurrentRegion] = useState(null);
  const [answerOptions, setAnswerOptions] = useState([]);
  const [incorrectGuesses, setIncorrectGuesses] = useState([]);
  const [correctAnswers, setCorrectAnswersLocal] = useState(0);
  const [incorrectAnswers, setIncorrectAnswersLocal] = useState(0);
  const [gameInitialized, setGameInitialized] = useState(false);

  const normalizeRegionName = (name) => {
    return name
      .toLowerCase()
      .trim()
      .replace(/[аáâãäå]/g, 'а')
      .replace(/[еéèêë]/g, 'е')
      .replace(/[иíìîï]/g, 'и')
      .replace(/[оóòôõö]/g, 'о')
      .replace(/[уúùûü]/g, 'у')
      .replace(/[ыýÿ]/g, 'ы')
      .replace(/[эèééêë]/g, 'э')
      .replace(/[юю]/g, 'ю')
      .replace(/[яя]/g, 'я');
  };

  useEffect(() => {
    if (kyrgyzstanRegions) {
      setRegionData(kyrgyzstanRegions);

      const regionsList = kyrgyzstanRegions.features
        .map(feature => feature.properties.NAME_1)
        .filter(name => name !== undefined)
        .map(normalizeRegionName);

      setRemainingRegions(regionsList);
      setTotalRegions(regionsList.length);
      setGameInitialized(true);
    }
  }, [kyrgyzstanRegions]);

  useEffect(() => {
    let timer;
    if (!isPaused) {
      const startTime = Date.now() - (elapsedTime * 1000);
      timer = setInterval(() => {
        setElapsedTime(Math.floor((Date.now() - startTime) / 1000));
      }, 1000);
    }
    return () => {
      if (timer) clearInterval(timer);
    };
  }, [isPaused, elapsedTime]);

  const selectRandomRegion = () => {
    const availableRegions = remainingRegions.filter(
      region =>
        !guessedRegions.includes(region) &&
        !incorrectGuesses.includes(region)
    );
  
    if (availableRegions.length === 0) {
      setGameStarted(false);
      setShowResults(true);
      setCorrectAnswers(correctAnswers);
      setIncorrectAnswers(incorrectAnswers);
      return;
    }
  
    const randomIndex = Math.floor(Math.random() * availableRegions.length);
    const selectedRegion = availableRegions[randomIndex];
    setCurrentRegion(selectedRegion);
  
    const options = [selectedRegion];
    const potentialOptions = remainingRegions.filter(
      r => r !== selectedRegion &&
           !guessedRegions.includes(r) &&
           !incorrectGuesses.includes(r)
    );
  
    while (options.length < 4 && potentialOptions.length > 0) {
      const randomOptionIndex = Math.floor(Math.random() * potentialOptions.length);
      const randomOption = potentialOptions[randomOptionIndex];
  
      if (!options.includes(randomOption)) {
        options.push(randomOption);
        potentialOptions.splice(randomOptionIndex, 1);
      }
    }
  
    while (options.length < 4) {
      const randomOption = remainingRegions[Math.floor(Math.random() * remainingRegions.length)];
      if (!options.includes(randomOption)) {
        options.push(randomOption);
      }
    }
  
    setAnswerOptions(options.sort(() => Math.random() - 0.5));
  };

  const handleAnswerSelection = (selectedAnswer) => {
    if (selectedAnswer === currentRegion) {
      setCorrectAnswersLocal(prev => prev + 1);
      setMessage(`Правильно! ${currentRegion}`);
      setGuessedRegions(prev => [...prev, currentRegion]);
    } else {
      setIncorrectAnswersLocal(prev => prev + 1);
      setMessage(`Неправильно. Правильный ответ: ${currentRegion}`);
      setIncorrectGuesses(prev => [...prev, currentRegion]);
    }

    const unguessedRegions = remainingRegions.filter(
      r => !guessedRegions.includes(r) && !incorrectGuesses.includes(r)
    );

    if (unguessedRegions.length === 0) {
      setGameStarted(false);
      setShowResults(true);
      setCorrectAnswers(correctAnswers);
      setIncorrectAnswers(incorrectAnswers);
    } else {
      selectRandomRegion();
    }
  };

  const onEachRegion = (feature, layer) => {
    const regionName = feature.properties.NAME_1
      ? normalizeRegionName(feature.properties.NAME_1)
      : '';

    const isGuessed = guessedRegions.includes(regionName);
    const isIncorrectGuess = incorrectGuesses.includes(regionName);

    layer.options.fillColor = isGuessed
      ? 'rgba(0, 255, 0, 0.5)'
      : isIncorrectGuess
      ? 'rgba(255, 0, 0, 0.5)'
      : 'transparent';

    layer.options.fillOpacity = isGuessed || isIncorrectGuess ? 0.7 : 0.2;
    layer.options.color = 'black';
    layer.options.weight = 1;

    if (isGuessed || isIncorrectGuess) {
      layer.bindTooltip(feature.properties.NAME_1, {
        permanent: true,
        direction: 'center',
        className: isGuessed ? 'correct-region-label' : 'incorrect-region-label'
      });
    }
  };

  useEffect(() => {
    if (gameInitialized && !currentRegion) {
      selectRandomRegion();
    }
  }, [gameInitialized, currentRegion]);

  return (
    <>
      <MapContainer
        center={[41.2044, 74.7661]}
        zoom={7}
        minZoom={5}
        maxZoom={15}
        style={{ height: '80vh', width: '100%' }}
      >
        <TileLayer
          url='https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png'
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>'
        />
        {regionData && (
          <GeoJSON
            key={guessedRegions.length + incorrectGuesses.length}
            data={regionData}
            onEachFeature={onEachRegion}
          />
        )}
        {currentRegion && (
          <FeatureGroup key={currentRegion}>
            <GeoJSON
              data={regionData}
              style={{
                fillColor: 'rgba(255, 0, 0, 0.5)',
                fillOpacity: 0.7,
                color: 'red',
                weight: 2,
              }}
              filter={(feature) => normalizeRegionName(feature.properties.NAME_1) === currentRegion}
            />
          </FeatureGroup>
        )}
      </MapContainer>

      <div className="answer-options">
        <p>{message}</p>
        {answerOptions.map((option, index) => (
          <Button key={index} variant="primary" onClick={() => handleAnswerSelection(option)}>
            {option}
          </Button>
        ))}
      </div>

      <div className="small-stats-block">
        <p>Правильные ответы: {correctAnswers}</p>
        <p>Неправильные ответы: {incorrectAnswers}</p>
        <p>Процент правильных ответов: {((correctAnswers / (correctAnswers + incorrectAnswers)) * 100).toFixed(2)}%</p>
        <Button variant="secondary" onClick={togglePauseMenu}>
          {isPaused ? <FaPlay /> : <FaPause />}
        </Button>
      </div>

      {showPauseMenu && (
        <div className="pause-menu">
          <h2>Пауза</h2>
          <div className="guessed-regions-list">
            <h3>Угадано:</h3>
            <ul>
              {guessedRegions.map((name, index) => (
                <li key={index}>{name}</li>
              ))}
            </ul>
          </div>
          <p>Время: {elapsedTime} секунд</p>
          <Button variant="primary" onClick={() => navigate('/kyrgyzstan/games')}>Вернуться в меню выбора игры</Button>
          <Button variant="secondary" onClick={togglePauseMenu}>Продолжить игру</Button>
        </div>
      )}
    </>
  );
};

export default MultipleChoiceMode;


как понять по какой причине там повторяются уже отгаданные области