
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 } = useCTF();
  const navigate = useNavigate();
  const location = useLocation();
  const [name, setName] = useState('');
  const [pass, setPass] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (await login(name, pass)) {
      const from = (location.state as any)?.from?.pathname || '/';
      navigate(from, { replace: true });
    } else setError('ACCESS_DENIED: INVALID_CREDENTIALS');
  };

  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">
          <div className="absolute -top-4 -left-4 bg-[#ff0000] text-black font-black px-4 py-1 text-xs italic">AUTH_GATE_01</div>
          <h2 className="text-5xl font-black italic text-white mb-8 tracking-tighter uppercase">SIGN_IN</h2>
          <form onSubmit={handleSubmit} className="space-y-6">
            <input placeholder="TEAM_IDENTIFIER" 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="SECRET_KEY" className="w-full bg-black hxp-border-purple p-4 text-white font-black" value={pass} onChange={e => setPass(e.target.value)} required />
            {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">Initiate Session</Button>
          </form>
          <p className="mt-8 text-center text-[10px] font-bold text-slate-500 tracking-widest uppercase">New operator? <Link to="/register" className="text-[#bf00ff] hover:underline">Register_Identity</Link></p>
        </div>
      </div>
    </div>
  );
};

export const Register: React.FC = () => {
  const { register } = useCTF();
  const navigate = useNavigate();
  const [name, setName] = useState('');
  const [pass, setPass] = useState('');
  const [error, setError] = useState('');
  
  // CAPTCHA State
  const [captchaQ, setCaptchaQ] = useState('');
  const [captchaInput, setCaptchaInput] = useState('');

  const generateCaptcha = () => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 6; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setCaptchaQ(result);
    setCaptchaInput('');
  };

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // CAPTCHA Validation (Case-insensitive)
    if (captchaInput.toLowerCase() !== captchaQ.toLowerCase()) {
      setError('VALIDATION_ERROR: HUMAN_VERIFICATION_FAILED');
      generateCaptcha();
      return;
    }

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

  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">
          <div className="absolute -top-4 -left-4 bg-[#bf00ff] text-black font-black px-4 py-1 text-xs italic">IDENTITY_GEN_01</div>
          <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">Team Identifier</label>
              <input placeholder="DESIRED_IDENTIFIER" 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">Secret Key</label>
              <input type="password" placeholder="SECRET_KEY" 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">
                <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Human Verification: <span className="text-[#00ff00] font-mono tracking-widest bg-white/5 px-2 py-1">{captchaQ}</span></label>
                <button type="button" onClick={generateCaptcha} className="text-[#bf00ff] hover:text-white transition-colors" title="Regenerate CAPTCHA">
                  <RefreshCw size={14} />
                </button>
              </div>
              <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">Create Identity</Button>
          </form>
        </div>
      </div>
    </div>
  );
};
