import { useState, useEffect, useCallback } from 'react';
import type { GuessEntry } from '@wordle/shared';
import { Grid } from '../components/Grid.js';
import { Keyboard } from '../components/Keyboard.js';
import { getMessages } from '../messages/index.js';
import { LangSwitch } from '../components/LangSwitch.js';

interface Screen2GameProps {
  guesses: GuessEntry[];
  letterColors: Record<string, string | undefined>;
  message: string | null;
  onGuess: (guess: string) => Promise<boolean>;
  onDismissMessage: () => void;
  gameOver: boolean;
}

export function Screen2Game({ guesses, letterColors, message, onGuess, onDismissMessage, gameOver }: Screen2GameProps) {
  const [currentGuess, setCurrentGuess] = useState<string>('');

  // Auto-dismiss message after 2 seconds
  useEffect(() => {
    if (!message) return;
    const timer = setTimeout(onDismissMessage, 2000);
    return () => clearTimeout(timer);
  }, [message, onDismissMessage]);

  const submitCurrent = useCallback(async () => {
    if (currentGuess.length !== 5 || gameOver) return;
    const accepted = await onGuess(currentGuess);
    if (accepted) {
      setCurrentGuess(''); // only clear when guess was valid
    }
  }, [currentGuess, onGuess, gameOver]);

  // Physical keyboard handler
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (gameOver) return;

      if (e.key === 'Enter') {
        submitCurrent();
        return;
      }
      if (e.key === 'Backspace') {
        if (message) onDismissMessage();
        setCurrentGuess((prev) => prev.slice(0, -1));
        return;
      }
      if (/^[a-zA-Z]$/.test(e.key) && currentGuess.length < 5) {
        setCurrentGuess((prev) => prev + e.key.toLowerCase());
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [currentGuess, message, gameOver, submitCurrent, onDismissMessage]);

  // On-screen keyboard handler
  const handleKeyPress = useCallback(
    (key: string) => {
      if (gameOver) return;
      if (key === 'Enter') {
        submitCurrent();
      } else if (key === 'Backspace') {
        if (message) onDismissMessage();
        setCurrentGuess((prev) => prev.slice(0, -1));
      } else if (currentGuess.length < 5) {
        setCurrentGuess((prev) => prev + key.toLowerCase());
      }
    },
    [currentGuess, message, gameOver, submitCurrent, onDismissMessage]
  );

  return (
    <div style={{ maxWidth: '400px', margin: '20px auto', padding: '8px', fontFamily: 'sans-serif', position: 'relative' }}>
      <LangSwitch />
      <h1 style={{ textAlign: 'center', fontSize: '1.6rem', marginBottom: '16px' }}>{getMessages().title}</h1>

      <div style={{ position: 'relative' }}>
        <Grid guesses={[...guesses, currentGuess ? { guess: currentGuess, colors: [] } : null].filter(Boolean) as GuessEntry[]} />

        {message && (
          <div
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              backgroundColor: '#333',
              color: '#fff',
              padding: '8px 16px',
              borderRadius: '6px',
              fontSize: '0.9rem',
              fontWeight: 'bold',
              zIndex: 10,
              whiteSpace: 'nowrap',
            }}
          >
            {message}
          </div>
        )}
      </div>

      <Keyboard letterColors={letterColors} onKeyPress={handleKeyPress} />
    </div>
  );
}
