import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';

interface LoadingScreenProps {
  isLoading: boolean;
}

const BOOT_MESSAGES = [
  { text: '> BIOS v3.14.159 initialized...', delay: 0 },
  { text: '> Loading kernel modules...', delay: 400 },
  { text: '> Establishing secure connection...', delay: 800 },
  { text: '> Decrypting user database...', delay: 1200 },
  { text: '> Bypassing firewall...', delay: 1600 },
  { text: '> Injecting payload...', delay: 2000 },
  { text: '> ACCESS GRANTED', delay: 2400, isSuccess: true },
];

const LoadingScreen = ({ isLoading }: LoadingScreenProps) => {
  const [visibleLines, setVisibleLines] = useState<number[]>([]);
  const [typedText, setTypedText] = useState<{ [key: number]: string }>({});
  const [progress, setProgress] = useState(0);
  const { playSound } = useSettings();
  const hasPlayedSound = useRef<{ [key: number]: boolean }>({});

  useEffect(() => {
    if (!isLoading) return;

    // Reset state when loading starts
    setVisibleLines([]);
    setTypedText({});
    setProgress(0);
    hasPlayedSound.current = {};

    BOOT_MESSAGES.forEach((msg, index) => {
      // Show line after delay
      setTimeout(() => {
        setVisibleLines(prev => [...prev, index]);
        
        // Play boot sound for each line (only once)
        if (!hasPlayedSound.current[index]) {
          hasPlayedSound.current[index] = true;
          if (msg.isSuccess) {
            playSound('success');
          } else {
            playSound('boot');
          }
        }

        // Type out the text character by character
        const text = msg.text;
        let charIndex = 0;
        const typeInterval = setInterval(() => {
          setTypedText(prev => ({
            ...prev,
            [index]: text.slice(0, charIndex + 1)
          }));
          charIndex++;
          
          if (charIndex >= text.length) {
            clearInterval(typeInterval);
          }
        }, 30);

        // Update progress
        setProgress(Math.round(((index + 1) / BOOT_MESSAGES.length) * 100));
      }, msg.delay);
    });
  }, [isLoading, playSound]);

  return (
    <AnimatePresence>
      {isLoading && (
        <motion.div
          initial={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.5 }}
          className="fixed inset-0 z-[9999] flex items-center justify-center bg-background"
        >
          <div className="w-full max-w-2xl px-6">
            {/* ASCII Art Header */}
            <pre className="font-mono text-primary text-glow text-xs md:text-sm mb-6 text-center">
{`
 ███╗   ███╗ █████╗ ████████╗██████╗ ██╗██╗  ██╗
 ████╗ ████║██╔══██╗╚══██╔══╝██╔══██╗██║╚██╗██╔╝
 ██╔████╔██║███████║   ██║   ██████╔╝██║ ╚███╔╝ 
 ██║╚██╔╝██║██╔══██║   ██║   ██╔══██╗██║ ██╔██╗ 
 ██║ ╚═╝ ██║██║  ██║   ██║   ██║  ██║██║██╔╝ ██╗
 ╚═╝     ╚═╝╚═╝  ╚═╝   ╚═╝   ╚═╝  ╚═╝╚═╝╚═╝  ╚═╝
`}
            </pre>

            {/* Terminal Output */}
            <div className="border border-primary/50 bg-background/80 p-4 font-mono text-sm box-glow min-h-[200px]">
              {BOOT_MESSAGES.map((msg, index) => (
                <motion.div
                  key={index}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: visibleLines.includes(index) ? 1 : 0 }}
                  className={`mb-1 ${msg.isSuccess ? 'text-primary text-glow-strong font-bold' : 'text-primary/80 text-glow'}`}
                >
                  {typedText[index] || ''}
                  {visibleLines.includes(index) && typedText[index]?.length < msg.text.length && (
                    <span className="animate-pulse">█</span>
                  )}
                </motion.div>
              ))}
              
              {/* Blinking cursor at the end */}
              {visibleLines.length === BOOT_MESSAGES.length && (
                <motion.span
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  className="text-primary animate-pulse"
                >
                  █
                </motion.span>
              )}
            </div>

            {/* Progress Bar */}
            <div className="mt-4">
              <div className="flex justify-between text-xs font-mono text-primary/70 mb-1">
                <span>LOADING SYSTEM</span>
                <span>{progress}%</span>
              </div>
              <div className="h-2 border border-primary/50 bg-background">
                <motion.div
                  initial={{ width: 0 }}
                  animate={{ width: `${progress}%` }}
                  transition={{ duration: 0.3 }}
                  className="h-full bg-primary box-glow"
                />
              </div>
            </div>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
};

export default LoadingScreen;
