/**
 * Quest Completion Modal - Shows mini-game and handles quest completion
 */

import React, { useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { analyticsService } from '../../services/analyticsService';
import { Modal } from '../ui/Modal';
import { Button } from '../ui/Button';
import { TriviaGame } from './TriviaGame';
import { MemoryGame } from './MemoryGame';
import { ReactionGame } from './ReactionGame';
import { FindTheRingGame } from './FindTheRingGame';

interface QuestCompletionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onComplete: (questId: number) => Promise<void>;
  questId: number;
  questTitle: string;
}

type GameType = 'trivia' | 'memory' | 'reaction' | 'findring';

const selectRandomGame = (): GameType => {
  const games: GameType[] = ['trivia', 'memory', 'reaction', 'findring'];
  return games[Math.floor(Math.random() * games.length)];
};

export const QuestCompletionModal: React.FC<QuestCompletionModalProps> = ({
  isOpen,
  onClose,
  onComplete,
  questId,
  questTitle,
}) => {
  const [gameType, setGameType] = useState<GameType | null>(null);
  const [gameWon, setGameWon] = useState(false);
  const [gameFailed, setGameFailed] = useState(false);
  const [isResetting, setIsResetting] = useState(false);
  const [isCompleting, setIsCompleting] = useState(false);
  const [gameInstanceKey, setGameInstanceKey] = useState(0);

  const handleModalOpen = useCallback(() => {
    if (gameType === null) {
      setGameType(selectRandomGame());
      setGameInstanceKey(0);
    }
  }, [gameType]);

  const handleGameSuccess = useCallback(() => {
    if (gameType) {
      analyticsService.trackGameCompleted(gameType);
    }
    setGameWon(true);
  }, [gameType]);

  const handleGameFail = useCallback(() => {
    if (gameType) {
      analyticsService.trackGameFailed(gameType);
    }
    setGameFailed(true);
  }, [gameType]);

  const handleTryAgain = useCallback(() => {
    setGameFailed(false);
    setIsResetting(true);
    setTimeout(() => {
      setGameWon(false);
      setGameInstanceKey((prev) => prev + 1);
      setIsResetting(false);
    }, 300);
  }, []);

  const handleClaimReward = useCallback(async () => {
    setIsCompleting(true);
    try {
      await onComplete(questId);
      setGameWon(false);
      setGameType(null);
      setGameInstanceKey(0);
      setIsCompleting(false);
      onClose();
    } catch (error) {
      console.error('Failed to complete quest:', error);
      setIsCompleting(false);
    }
  }, [questId, onComplete, onClose]);

  React.useEffect(() => {
    if (isOpen) {
      handleModalOpen();
    } else {
      setGameWon(false);
      setGameFailed(false);
      setIsResetting(false);
      setIsCompleting(false);
      setGameType(null);
      setGameInstanceKey(0);
    }
  }, [isOpen, handleModalOpen]);

  let gameContent: React.ReactNode = null;

  if (gameWon) {
    gameContent = (
      <motion.div
        key="reward"
        initial={{ opacity: 0, scale: 0.8 }}
        animate={{ opacity: 1, scale: 1 }}
        className="space-y-6 text-center"
      >
        <motion.div
          animate={{ scale: [1, 1.1, 1] }}
          transition={{ duration: 0.6, repeat: Infinity }}
          className="text-6xl"
        >
          ✨
        </motion.div>
        <div>
          <h4 className="text-2xl font-epic text-gold-dark mb-2">Quest Complete!</h4>
          <p className="text-parchment-light mb-4">You have overcome the challenge.</p>
          <p className="text-sm text-text-secondary italic">"{questTitle}"</p>
        </div>
        <Button
          onClick={handleClaimReward}
          isLoading={isCompleting}
          variant="epic"
          className="w-full"
        >
          💰 Claim Reward
        </Button>
      </motion.div>
    );
  } else if (gameFailed) {
    gameContent = (
      <motion.div
        key="failed"
        initial={{ opacity: 0, scale: 0.8 }}
        animate={{ opacity: 1, scale: 1 }}
        className="space-y-6 text-center"
      >
        <div className="text-6xl">💀</div>
        <div>
          <h4 className="text-2xl font-epic text-red-600 mb-2">Challenge Failed!</h4>
          <p className="text-parchment-light mb-4">The darkness prevails... for now.</p>
        </div>
        <Button
          onClick={handleTryAgain}
          variant="epic"
          className="w-full"
        >
          🔄 Try Again
        </Button>
      </motion.div>
    );
  } else if (isResetting) {
    gameContent = (
      <motion.div
        initial={{ opacity: 1 }}
        animate={{ opacity: 0.5 }}
        transition={{ duration: 0.3 }}
        className="text-center"
      >
        <p className="text-parchment-light">Resetting challenge...</p>
      </motion.div>
    );
  } else if (gameType === 'trivia') {
    gameContent = (
      <TriviaGame key={`trivia-${gameInstanceKey}`} onSuccess={handleGameSuccess} onFail={handleGameFail} />
    );
  } else if (gameType === 'memory') {
    gameContent = (
      <MemoryGame key={`memory-${gameInstanceKey}`} onSuccess={handleGameSuccess} onFail={handleGameFail} />
    );
  } else if (gameType === 'reaction') {
    gameContent = (
      <ReactionGame key={`reaction-${gameInstanceKey}`} onSuccess={handleGameSuccess} onFail={handleGameFail} />
    );
  } else if (gameType === 'findring') {
    gameContent = (
      <FindTheRingGame key={`findring-${gameInstanceKey}`} onSuccess={handleGameSuccess} onFail={handleGameFail} />
    );
  }

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="⚔️ Quest Challenge"
      size="full"
      className="w-full"
    >
      {/* Hidden test trigger buttons for e2e automation — rendered only when REACT_APP_ENABLE_TEST_CONTROLS=true */}
      {process.env.REACT_APP_ENABLE_TEST_CONTROLS === 'true' && (
        <div aria-hidden="true" style={{ position: 'absolute', top: '-9999px', left: '-9999px' }}>
          <button data-testid="force-game-win" onClick={handleGameSuccess} tabIndex={-1} type="button">
            Force Win
          </button>
          <button data-testid="force-game-fail" onClick={handleGameFail} tabIndex={-1} type="button">
            Force Fail
          </button>
        </div>
      )}
      <AnimatePresence mode="wait">
        <motion.div
          key={`${gameType}-${gameInstanceKey}`}
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -10 }}
          transition={{ duration: 0.3 }}
        >
          {gameContent}
        </motion.div>
      </AnimatePresence>
    </Modal>
  );
};
