import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Hexagon, ShieldCheck, ArrowRight, Loader2 } from 'lucide-react';
import { verifyCode } from '../services/dataService';

export const VerifyCode: React.FC = () => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  const [code, setCode] = useState('');
  const [error, setError] = useState('');
  const [email, setEmail] = useState('');

  useEffect(() => {
    const storedEmail = localStorage.getItem('pending_verify_email');
    if (!storedEmail) {
      navigate('/register');
    } else {
      setEmail(storedEmail);
    }
  }, [navigate]);

  const handleVerify = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');
    
    try {
      const success = await verifyCode({ email, code });
      if (success) {
        localStorage.removeItem('pending_verify_email');
        alert('Conta verificada com sucesso! Agora você pode fazer login.');
        navigate('/login');
      }
    } catch (err: any) {
      setError(err.message || 'Código inválido ou expirado.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
      <div className="sm:mx-auto sm:w-full sm:max-w-md">
        <div className="flex justify-center items-center gap-2 text-slate-900">
          <div className="bg-slate-900 text-white p-2 rounded-lg">
             <Hexagon size={28} fill="currentColor" />
          </div>
          <span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
        </div>
        <h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
          Verifique seu e-mail
        </h2>
        <p className="mt-2 text-center text-sm text-slate-600 px-4">
          Enviamos um código de 6 dígitos para <strong>{email}</strong>. Por favor, insira-o abaixo.
        </p>
      </div>

      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
          
          <form className="space-y-6" onSubmit={handleVerify}>
            <div>
              <label htmlFor="code" className="block text-sm font-medium text-slate-700 text-center mb-4">
                Código de Verificação
              </label>
              <input
                id="code"
                type="text"
                maxLength={6}
                required
                value={code}
                onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
                className="block w-full text-center text-3xl tracking-[0.5em] font-bold py-3 border border-slate-300 rounded-lg bg-slate-50 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 transition-all"
                placeholder="000000"
              />
            </div>

            {error && (
              <div className="text-red-500 text-sm font-medium text-center">
                {error}
              </div>
            )}

            <div>
              <button
                type="submit"
                disabled={isLoading || code.length !== 6}
                className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 disabled:opacity-70 disabled:cursor-not-allowed transition-all"
              >
                {isLoading ? (
                  <>
                    <Loader2 className="animate-spin h-4 w-4" />
                    Verificando...
                  </>
                ) : (
                  <>
                    Verificar Código <ShieldCheck className="h-4 w-4" />
                  </>
                )}
              </button>
            </div>
          </form>

          <div className="mt-6 text-center">
            <button 
              onClick={() => navigate('/register')}
              className="text-sm text-slate-500 hover:text-slate-800"
            >
              Alterar e-mail ou voltar ao registro
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
