import React, { useState, useEffect, useRef } from 'react';

interface RatPoisonChallengeProps {
  challengeString: string;
  expiresAt: number;
  onSolve: (solvedString: string) => void;
  onClose: () => void;
}

export function RatPoisonChallenge({ challengeString, expiresAt, onSolve, onClose }: RatPoisonChallengeProps) {
  const [inputValue, setInputValue] = useState('');
  const [timeLeft, setTimeLeft] = useState(0);
  const [initialDuration, setInitialDuration] = useState(0);
  const timerRef = useRef<number | null>(null);

  useEffect(() => {
    const now = Date.now();
    const duration = expiresAt - now;
    setInitialDuration(Math.ceil(duration / 1000));

    const calculateTimeLeft = () => {
      const remaining = Math.max(0, expiresAt - Date.now());
      setTimeLeft(Math.ceil(remaining / 1000));
    };

    calculateTimeLeft(); // Initial calculation
    timerRef.current = setInterval(calculateTimeLeft, 1000);

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [expiresAt]);

  useEffect(() => {
    if (timeLeft === 0 && Date.now() >= expiresAt) {
      // Challenge expired, automatically close or handle failure
      onSolve(''); // Send empty string to indicate failure due to timeout
      onClose();
    }
  }, [timeLeft, expiresAt, onSolve, onClose]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSolve(inputValue);
    onClose();
  };

  const progressPercentage = initialDuration > 0 ? (timeLeft / initialDuration) * 100 : 0;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 pointer-events-auto">
      <div className="bg-gradient-to-br from-purple-700 to-indigo-900 p-8 rounded-lg shadow-2xl border-4 border-pink-500 text-white text-center max-w-md mx-auto">
        <h2 className="text-3xl font-bold mb-4 text-yellow-300">RAT POISON CHALLENGE!</h2>
        <p className="text-lg mb-6">Type the following string:</p>
        <p className="text-2xl font-mono bg-gray-800 p-4 rounded-md break-all mb-6 border-2 border-gray-600">{challengeString}</p>
        
        <div className="w-full bg-gray-700 rounded-full h-4 mb-4">
          <div 
            className="bg-green-500 h-4 rounded-full transition-all duration-1000 ease-linear" 
            style={{ width: `${progressPercentage}%` }}
          ></div>
        </div>

        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
          <input
            type="text"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            className="p-3 rounded-md bg-gray-700 text-white border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="Type here..."
            autoFocus
          />
          <button
            type="submit"
            className="bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-6 rounded-md transition duration-300 ease-in-out transform hover:scale-105"
            disabled={timeLeft === 0}
          >
            SUBMIT ({timeLeft}s)
          </button>
        </form>
        {timeLeft === 0 && <p className="text-red-400 mt-4">Time's up!</p>}
      </div>
    </div>
  );
}
