
import React, { useState, useEffect } from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { RefreshCw } from 'lucide-react';
import { useCTF } from './CTFContext';
import { Button } from './UIComponents';

export const Login: React.FC = () => {
  const { login, getCaptcha } = useCTF();
  const navigate = useNavigate();
  const location = useLocation();
  const [name, setName] = useState('');
  const [pass, setPass] = useState('');
  const [error, setError] = useState('');

  // CAPTCHA State
  const [captchaData, setCaptchaData] = useState<{ id: string, data: string } | null>(null);
  const [captchaInput, setCaptchaInput] = useState('');

  const fetchCaptcha = async () => {
    try {
      const res = await getCaptcha();
      setCaptchaData(res);
      setCaptchaInput('');
    } catch (err) {
      setError('FAILED_TO_LOAD_CAPTCHA');
    }
  };

  useEffect(() => {
    fetchCaptcha();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!captchaData) return;

    if (await login(name, pass, captchaData.id, captchaInput)) {
      const from = (location.state as any)?.from?.pathname || '/';
      navigate(from, { replace: true });
    } else {
      setError('ACCESS_DENIED: INVALID_CREDENTIALS_OR_CAPTCHA');
      fetchCaptcha();
    }
  };

  return (
    <div className="min-h-[80vh] flex items-center justify-center px-6">
      <div className="w-full max-w-md">
        <div className="hxp-border border-4 p-10 bg-black relative">
          <h2 className="text-5xl font-black italic text-white mb-8 tracking-tighter uppercase">LOGIN</h2>
          <form onSubmit={handleSubmit} className="space-y-6">
            <input placeholder="PLAYER" className="w-full bg-black hxp-border-purple p-4 text-white font-black" value={name} onChange={e => setName(e.target.value)} required />
            <input type="password" placeholder="PASSWORD" className="w-full bg-black hxp-border-purple p-4 text-white font-black" value={pass} onChange={e => setPass(e.target.value)} required />
            
            <div className="space-y-2 border-t border-white/10 pt-4">
              <div className="flex justify-between items-center mb-2">
                <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Human Verification</label>
                <button type="button" onClick={fetchCaptcha} className="text-[#bf00ff] hover:text-white transition-colors" title="Regenerate CAPTCHA">
                  <RefreshCw size={14} />
                </button>
              </div>
              
              {captchaData ? (
                <div 
                  className="bg-white/5 p-2 hxp-border-purple flex justify-center mb-4"
                  dangerouslySetInnerHTML={{ __html: captchaData.data }}
                />
              ) : <div className="h-16 bg-white/5 animate-pulse mb-4" />}

              <input 
                placeholder="ENTER CODE" 
                className="w-full bg-black hxp-border-purple p-4 text-white font-black" 
                value={captchaInput} 
                onChange={e => setCaptchaInput(e.target.value)} 
                required 
              />
            </div>

            {error && <p className="text-red-500 font-black italic animate-pulse uppercase">{error}</p>}
            <Button type="submit" className="w-full py-4 text-xl uppercase">LOGIN</Button>
          </form>
          <p className="mt-8 text-center text-[10px] font-bold text-slate-500 tracking-widest uppercase">New user? <Link to="/register" className="text-[#bf00ff] hover:underline">REGISTER</Link></p>
        </div>
      </div>
    </div>
  );
};

export const Register: React.FC = () => {
  const { register, getCaptcha } = useCTF();
  const navigate = useNavigate();
  const [name, setName] = useState('');
  const [pass, setPass] = useState('');
  const [error, setError] = useState('');
  
  // CAPTCHA State
  const [captchaData, setCaptchaData] = useState<{ id: string, data: string } | null>(null);
  const [captchaInput, setCaptchaInput] = useState('');

  const fetchCaptcha = async () => {
    try {
      const res = await getCaptcha();
      setCaptchaData(res);
      setCaptchaInput('');
    } catch (err) {
      setError('FAILED_TO_LOAD_CAPTCHA');
    }
  };

  useEffect(() => {
    fetchCaptcha();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!captchaData) return;

    try {
      await register(name, pass, captchaData.id, captchaInput);
      navigate('/challenges');
    } catch (err: any) { 
      setError(err.message || 'REGISTRATION_FAILED'); 
      fetchCaptcha();
    }
  };

  return (
    <div className="min-h-[80vh] flex items-center justify-center px-6">
      <div className="w-full max-w-md">
        <div className="hxp-border border-4 p-10 bg-black relative">
          <h2 className="text-5xl font-black italic text-white mb-8 tracking-tighter uppercase">REGISTER</h2>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="space-y-1">
              <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Player name</label>
              <input placeholder="DESIRED NAME" className="w-full bg-black hxp-border-purple p-4 text-white font-black" value={name} onChange={e => setName(e.target.value)} required />
            </div>
            
            <div className="space-y-1">
              <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest">PASSWORD</label>
              <input type="password" placeholder="PASSWORD" className="w-full bg-black hxp-border-purple p-4 text-white font-black" value={pass} onChange={e => setPass(e.target.value)} required />
            </div>

            <div className="space-y-2 border-t border-white/10 pt-4">
              <div className="flex justify-between items-center mb-2">
                <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Human Verification</label>
                <button type="button" onClick={fetchCaptcha} className="text-[#bf00ff] hover:text-white transition-colors" title="Regenerate CAPTCHA">
                  <RefreshCw size={14} />
                </button>
              </div>
              
              {captchaData ? (
                <div 
                  className="bg-white/5 p-2 hxp-border-purple flex justify-center mb-4"
                  dangerouslySetInnerHTML={{ __html: captchaData.data }}
                />
              ) : <div className="h-16 bg-white/5 animate-pulse mb-4" />}

              <input 
                placeholder="ENTER CODE" 
                className="w-full bg-black hxp-border-purple p-4 text-white font-black" 
                value={captchaInput} 
                onChange={e => setCaptchaInput(e.target.value)} 
                required 
              />
            </div>

            {error && <p className="text-red-500 font-black italic animate-pulse uppercase text-[10px]">{error}</p>}
            <Button type="submit" className="w-full py-4 text-xl uppercase">REGISTER</Button>
          </form>
        </div>
      </div>
    </div>
  );
};
