import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Lock, Mail, AlertCircle, CheckCircle2, Loader2, ArrowLeft, Send } from 'lucide-react';
import { toast } from 'sonner';
import * as grService from '../services/grService';
import '../styles/gr-theme.css';

const ResetPasswordView = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const token = searchParams.get('token');

  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');
  const [mode, setMode] = useState(token ? 'RESET' : 'REQUEST');
  const [email, setEmail] = useState('');
  const [formData, setFormData] = useState({
    password: '',
    confirmPassword: ''
  });

  useEffect(() => {
    if (token) {
      setMode('RESET');
    } else {
      setMode('REQUEST');
    }
  }, [token]);

  const validateInput = (input) => {
    const containsScript = /<script>|<\/script>|script/i;
    const containsSQL = /select|insert|update|delete|drop|create|table|union/i;

    if (containsScript.test(input) || containsSQL.test(input)) {
      return false;
    }
    return true;
  };

  const handleRequestReset = async (e) => {
    e.preventDefault();
    setErrorMsg('');

    if (!email) {
      setErrorMsg('Por favor, informe seu e-mail.');
      return;
    }

    if (!validateInput(email)) {
      setErrorMsg('Entrada inválida detectada.');
      return;
    }

    setLoading(true);
    try {
      await grService.requestPasswordReset({ email });
      setSuccess(true);
      toast.success("E-mail de recuperação enviado!");
    } catch (err) {
      console.error(err);
      setErrorMsg(err.message || 'Erro ao solicitar redefinição.');
    } finally {
      setLoading(false);
    }
  };

  const handleResetPassword = async (e) => {
    e.preventDefault();
    setErrorMsg('');

    if (!token) {
      setErrorMsg('Token não encontrado ou expirado.');
      return;
    }

    if (formData.password !== formData.confirmPassword) {
      setErrorMsg('As senhas não coincidem.');
      return;
    }

    if (!validateInput(formData.password)) {
      setErrorMsg('Senha contém caracteres ou termos não permitidos.');
      return;
    }

    if (formData.password.length < 4) {
      setErrorMsg('A senha deve ter pelo menos 4 caracteres.');
      return;
    }

    setLoading(true);
    try {
      await grService.resetPasswordExternal({
        token,
        senha: formData.password
      });
      
      setSuccess(true);
      toast.success("Senha alterada com sucesso!");
      
      setTimeout(() => {
        navigate('/plataforma/gr/login');
      }, 3000);

    } catch (err) {
      console.error(err);
      setErrorMsg(err.message || 'Erro ao redefinir senha.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-[#0a0a0a] relative overflow-hidden p-6 font-sans">
      {/* Premium Background Elements */}
      <div className="absolute top-[-10%] left-[-10%] w-[70%] h-[70%] bg-[var(--gr-primary)]/5 rounded-full blur-[150px] animate-pulse"></div>
      <div className="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-[var(--gr-primary-dark)]/10 rounded-full blur-[120px] animate-pulse" style={{ animationDelay: '3s' }}></div>
      <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full h-full opacity-[0.02] dark:opacity-[0.03] pointer-events-none" 
           style={{ backgroundImage: 'radial-gradient(var(--gr-primary) 1px, transparent 1px)', backgroundSize: '40px 40px' }}></div>

      <div className="w-full max-w-md bg-white/80 dark:bg-[#121212]/90 backdrop-blur-xl rounded-[48px] shadow-[0_32px_80px_-20px_rgba(0,0,0,0.15)] dark:shadow-[0_40px_100px_-20px_rgba(0,0,0,0.6)] p-12 z-10 relative border border-white/20 dark:border-white/5 animate-in fade-in zoom-in-95 duration-700 overflow-hidden">
        
        {/* Top Gradient Bar */}
        <div className="absolute top-0 left-0 right-0 h-2 bg-gradient-to-r from-[var(--gr-primary)] via-[var(--gr-primary-dark)] to-[var(--gr-primary)] opacity-80"></div>

        <div className="flex flex-col items-center mb-12">
          <div className="w-24 h-24 bg-gradient-to-br from-[var(--gr-primary)] to-[var(--gr-primary-dark)] text-white rounded-[32px] flex items-center justify-center text-4xl font-bold shadow-2xl shadow-[var(--gr-primary)]/30 mb-8 transition-transform hover:scale-105 duration-500">
            GR
          </div>
          <h1 className="text-3xl font-extrabold text-slate-800 dark:text-white tracking-tight text-center">
            {mode === 'REQUEST' ? 'Recuperar ' : 'Redefinir '}
            <span className="text-transparent bg-clip-text bg-gradient-to-r from-[var(--gr-primary)] to-[var(--gr-primary-dark)]">Senha</span>
          </h1>
          <p className="text-slate-500 dark:text-slate-400 text-sm mt-3 font-medium text-center leading-relaxed px-4">
            {mode === 'REQUEST' 
              ? 'Informe seu e-mail para receber um link de recuperação funcional.' 
              : 'Crie uma nova credencial robusta para acessar seu ambiente.'}
          </p>
        </div>

        {success ? (
          <div className="flex flex-col items-center py-10 text-center space-y-6 animate-in zoom-in-95 duration-500">
            <div className="w-20 h-20 bg-green-50 dark:bg-green-500/10 text-green-500 rounded-full flex items-center justify-center shadow-inner">
              <CheckCircle2 size={40} strokeWidth={1.5} />
            </div>
            <div className="space-y-2">
              <h2 className="text-2xl font-bold text-slate-800 dark:text-white">
                {mode === 'REQUEST' ? 'E-mail Enviado!' : 'Senha Atualizada!'}
              </h2>
              <p className="text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-[280px]">
                {mode === 'REQUEST' 
                  ? 'Verifique sua caixa de entrada e spam para continuar o processo.' 
                  : 'Sua conta está protegida. Redirecionando para o login...'}
              </p>
            </div>
            {mode === 'REQUEST' && (
               <button 
                  onClick={() => navigate('/plataforma/gr/login')}
                  className="mt-4 text-sm font-bold text-[var(--gr-primary)] hover:underline uppercase tracking-widest flex items-center gap-2"
               >
                 <ArrowLeft size={16} /> Voltar ao Login
               </button>
            )}
          </div>
        ) : (
          <form onSubmit={mode === 'REQUEST' ? handleRequestReset : handleResetPassword} className="space-y-8">
            {mode === 'REQUEST' ? (
              <div className="space-y-3">
                <label className="text-[11px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] ml-2">E-mail de Cadastro</label>
                <div className="relative group">
                  <div className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-[var(--gr-primary)] transition-all duration-300">
                    <Mail size={22} strokeWidth={2} />
                  </div>
                  <input 
                    type="email" 
                    className="w-full pl-14 pr-6 py-5 bg-slate-50 dark:bg-black/40 border border-slate-100 dark:border-white/5 rounded-[24px] focus:outline-none focus:border-[var(--gr-primary)] focus:ring-4 focus:ring-[var(--gr-primary)]/5 dark:text-white transition-all font-medium text-lg placeholder:text-slate-300 dark:placeholder:text-slate-700 shadow-sm"
                    placeholder="usuario@dominio.com.br"
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    required
                    disabled={loading}
                  />
                </div>
              </div>
            ) : (
              <>
                <div className="space-y-3">
                  <label className="text-[11px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] ml-2">Nova Senha</label>
                  <div className="relative group">
                    <div className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-[var(--gr-primary)] transition-all duration-300">
                      <Lock size={22} strokeWidth={2} />
                    </div>
                    <input 
                      type="password" 
                      className="w-full pl-14 pr-6 py-5 bg-slate-50 dark:bg-black/40 border border-slate-100 dark:border-white/5 rounded-[24px] focus:outline-none focus:border-[var(--gr-primary)] focus:ring-4 focus:ring-[var(--gr-primary)]/5 dark:text-white transition-all font-medium text-lg placeholder:text-slate-300 dark:placeholder:text-slate-700 shadow-sm"
                      placeholder="••••••••"
                      value={formData.password}
                      onChange={e => setFormData({...formData, password: e.target.value})}
                      required
                      disabled={loading}
                    />
                  </div>
                </div>

                <div className="space-y-3">
                  <label className="text-[11px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] ml-2">Confirmar Senha</label>
                  <div className="relative group">
                    <div className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-[var(--gr-primary)] transition-all duration-300">
                      <Lock size={22} strokeWidth={2} />
                    </div>
                    <input 
                      type="password" 
                      className="w-full pl-14 pr-6 py-5 bg-slate-50 dark:bg-black/40 border border-slate-100 dark:border-white/5 rounded-[24px] focus:outline-none focus:border-[var(--gr-primary)] focus:ring-4 focus:ring-[var(--gr-primary)]/5 dark:text-white transition-all font-medium text-lg placeholder:text-slate-300 dark:placeholder:text-slate-700 shadow-sm"
                      placeholder="••••••••"
                      value={formData.confirmPassword}
                      onChange={e => setFormData({...formData, confirmPassword: e.target.value})}
                      required
                      disabled={loading}
                    />
                  </div>
                </div>
              </>
            )}

            {errorMsg && (
              <div className="flex items-start gap-4 rounded-2xl bg-red-50 dark:bg-red-950/20 border border-red-200/50 dark:border-red-900/30 px-6 py-4 text-sm text-red-700 dark:text-red-400 animate-in fade-in slide-in-from-top-2 duration-300">
                <AlertCircle size={20} className="shrink-0 mt-0.5" />
                <p className="font-medium">{errorMsg}</p>
              </div>
            )}

            <button 
              type="submit"
              disabled={loading}
              className="group w-full py-5 bg-gradient-to-r from-[var(--gr-primary)] to-[var(--gr-primary-dark)] text-white font-bold rounded-[24px] hover:shadow-2xl hover:shadow-[var(--gr-primary)]/40 active:scale-[0.98] transition-all disabled:opacity-50 disabled:cursor-not-allowed mt-4 flex items-center justify-center gap-3 text-sm uppercase tracking-[0.2em] overflow-hidden relative"
            >
              {loading ? (
                <Loader2 size={24} className="animate-spin" />
              ) : (
                <>
                  <span>{mode === 'REQUEST' ? 'Enviar Link' : 'Redefinir Senha'}</span>
                  <Send size={18} className="transition-transform group-hover:translate-x-1 group-hover:-translate-y-1" />
                </>
              )}
            </button>

            <button 
              type="button"
              onClick={() => navigate('/plataforma/gr/login')}
              className="w-full flex items-center justify-center gap-2 text-xs font-bold text-slate-400 dark:text-slate-500 hover:text-[var(--gr-primary)] uppercase tracking-widest transition-all duration-300"
            >
              <ArrowLeft size={14} /> Voltar para o Login
            </button>
          </form>
        )}
      </div>

      {/* Footer Branding */}
      <div className="absolute bottom-10 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 opacity-30 dark:opacity-20 select-none">
          <span className="text-[10px] font-bold tracking-[0.4em] text-slate-500 uppercase">Powered by IT Guys</span>
          <div className="flex gap-2">
              <div className="w-1.5 h-1.5 rounded-full bg-[var(--gr-primary)]"></div>
              <div className="w-1.5 h-1.5 rounded-full bg-slate-400"></div>
              <div className="w-1.5 h-1.5 rounded-full bg-slate-400"></div>
          </div>
      </div>
    </div>
  );
};

export default ResetPasswordView;
