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

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email) { setError('E-mail não encontrado. Tente registrar novamente.'); return; }
    
    setIsLoading(true);
    setError('');
    
    try {
      const success = await verifyCode({ email, code });
      if (success) {
        navigate('/login', { state: { message: 'E-mail verificado com sucesso! Agora você pode entrar.' } });
      }
    } catch (err: any) {
      setError(err.message || 'Código inválido ou expirado.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
      <div className="sm:mx-auto sm:w-full sm:max-w-md">
        <div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
          <div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
            <Hexagon size={32} fill="currentColor" />
          </div>
          <span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
        </div>
        <h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
          Verifique seu e-mail
        </h2>
        <p className="mt-2 text-center text-sm text-zinc-600 dark:text-dark-muted px-4">
          Insira o código de 6 dígitos enviado para <span className="font-semibold text-zinc-900 dark:text-zinc-200">{email}</span>
        </p>
      </div>

      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
          <form className="space-y-6" onSubmit={handleSubmit}>
            {error && (
              <div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg text-red-600 dark:text-red-400 text-sm">
                <AlertCircle size={18} />
                {error}
              </div>
            )}

            <div>
              <label htmlFor="code" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 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(/[^0-9]/g, ''))}
                className="block w-full text-center text-3xl tracking-[0.5em] font-bold py-3 border border-zinc-300 dark:border-dark-border rounded-lg bg-zinc-50 dark:bg-dark-input text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-brand-yellow/20 focus:border-brand-yellow transition-all"
                placeholder="000000"
              />
            </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-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow disabled:opacity-70 disabled:cursor-not-allowed transition-all"
              >
                {isLoading ? (
                  <Loader2 className="animate-spin h-5 w-5" />
                ) : (
                  <>
                    Verificar Código <ArrowRight size={18} />
                  </>
                )}
              </button>
            </div>
          </form>

          <div className="mt-6 text-center">
            <button 
              type="button"
              className="text-sm font-medium text-brand-yellow hover:text-yellow-600 transition-colors"
              onClick={() => navigate('/register')}
            >
              Voltar e corrigir e-mail
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
