/**
 * Find the Ring Game - Find the ring under shuffled cups
 */

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { Button } from '../ui/Button';

interface FindTheRingGameProps {
  onSuccess: () => void;
  onFail: () => void;
}

interface Cup {
  id: number;
  hasRing: boolean;
  revealed: boolean;
}

export const FIND_THE_RING_MAX_WRONG_ATTEMPTS = 3;

const createInitialCups = (): Cup[] => {
  const ringPosition = Math.floor(Math.random() * 3);

  return [
    { id: 0, hasRing: ringPosition === 0, revealed: false },
    { id: 1, hasRing: ringPosition === 1, revealed: false },
    { id: 2, hasRing: ringPosition === 2, revealed: false },
  ];
};

export const FindTheRingGame: React.FC<FindTheRingGameProps> = ({ onSuccess, onFail }) => {
  const [cups, setCups] = useState<Cup[]>(() => createInitialCups());
  const [gameStarted, setGameStarted] = useState(false);
  const [shuffling, setShuffling] = useState(false);
  const [wrongAttempts, setWrongAttempts] = useState(0);

  const handleStartGame = async () => {
    setGameStarted(true);
    setShuffling(true);
    await new Promise((resolve) => setTimeout(resolve, 1200));
    setShuffling(false);
  };

  const handleCupClick = (id: number) => {
    const cup = cups[id];
    if (shuffling || cup.revealed) {
      return;
    }

    setCups((prev) => prev.map((currentCup) => (currentCup.id === id ? { ...currentCup, revealed: true } : currentCup)));

    if (cup.hasRing) {
      window.setTimeout(() => {
        onSuccess();
      }, 700);
      return;
    }

    const nextWrongAttempts = wrongAttempts + 1;
    setWrongAttempts(nextWrongAttempts);

    if (nextWrongAttempts >= FIND_THE_RING_MAX_WRONG_ATTEMPTS) {
      window.setTimeout(() => {
        onFail();
      }, 900);
      return;
    }

    window.setTimeout(() => {
      setCups((prev) => prev.map((currentCup) => (currentCup.id === id ? { ...currentCup, revealed: false } : currentCup)));
    }, 800);
  };

  return (
    <div className="space-y-6">
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="text-center"
      >
        <h3 className="text-xl font-epic text-gold-dark mb-2">🏆 Find the Ring</h3>
        <p className="text-sm text-text-secondary">
          {!gameStarted ? 'Test your luck!' : `Wrong guesses: ${wrongAttempts}/${FIND_THE_RING_MAX_WRONG_ATTEMPTS}`}
        </p>
        {gameStarted && (
          <p className="text-xs text-text-secondary mt-1">
            Two wrong guesses are allowed. The third wrong pick fails the challenge.
          </p>
        )}
      </motion.div>

      {!gameStarted ? (
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center space-y-4"
        >
          <p className="text-parchment-light">Watch the cups as they shuffle. Can you find the ring?</p>
          <div className="flex justify-center gap-4 text-5xl">
            {[0, 1, 2].map((cupIndex) => (
              <motion.div
                key={cupIndex}
                initial={{ y: 0 }}
                animate={{ y: -10 }}
                transition={{ duration: 0.5, repeat: Infinity, repeatType: 'reverse' }}
              >
                🏺
              </motion.div>
            ))}
          </div>
          <Button onClick={handleStartGame} variant="epic" className="w-full">
            Start Shuffling
          </Button>
        </motion.div>
      ) : (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="space-y-6"
        >
          {shuffling && (
            <motion.div
              animate={{ x: [0, 10, -10, 0] }}
              transition={{ duration: 0.3, repeat: Infinity }}
              className="text-center text-yellow-400 font-semibold"
            >
              Shuffling...
            </motion.div>
          )}

          <div className="flex justify-center gap-4 sm:gap-6">
            {cups.map((cup) => (
              <motion.button
                key={cup.id}
                type="button"
                aria-label={`Cup ${cup.id + 1}`}
                onClick={() => handleCupClick(cup.id)}
                disabled={shuffling || cup.revealed}
                whileHover={!shuffling && !cup.revealed ? { scale: 1.04, y: -4 } : {}}
                whileTap={!shuffling && !cup.revealed ? { scale: 0.96 } : {}}
                className={`rounded-lg p-4 text-6xl sm:text-7xl transition-all duration-300 ${
                  cup.revealed
                    ? cup.hasRing
                      ? 'bg-green-600 cursor-default'
                      : 'bg-red-600 cursor-default'
                    : 'bg-forest hover:bg-forest-light cursor-pointer'
                } ${shuffling ? 'cursor-default' : ''}`}
              >
                <motion.div
                  animate={cup.revealed ? { rotateY: 180 } : { rotateY: 0 }}
                  transition={{ duration: 0.35 }}
                >
                  {cup.revealed ? (cup.hasRing ? '💍' : '∅') : '🏺'}
                </motion.div>
              </motion.button>
            ))}
          </div>

          {wrongAttempts > 0 && !cups.some((cup) => cup.revealed && cup.hasRing) && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="text-center text-red-400 font-semibold"
            >
              ✗ Wrong cup! Try again... ({wrongAttempts}/{FIND_THE_RING_MAX_WRONG_ATTEMPTS})
            </motion.div>
          )}

          {cups.some((cup) => cup.revealed && cup.hasRing) && (
            <motion.div
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              className="text-center text-green-400 font-semibold text-lg"
            >
              ✓ Found the ring!
            </motion.div>
          )}
        </motion.div>
      )}
    </div>
  );
};

FindTheRingGame.displayName = 'FindTheRingGame';
