import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Hexagon, Lock, Mail, ArrowRight, Loader2, Eye, EyeOff, AlertCircle } from 'lucide-react';
import { login, logout } from '../services/dataService';

export const Login: React.FC = () => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');
  const [emailError, setEmailError] = useState('');

  const validateEmail = (val: string) => {
    setEmail(val);
    if (!val) {
      setEmailError('E-mail é obrigatório');
    } else if (!/\S+@\S+\.\S+/.test(val)) {
      setEmailError('E-mail inválido');
    } else {
      setEmailError('');
    }
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (emailError) return;

    setIsLoading(true);
    setError('');
    
    logout();
    
    try {
      const data = await login({ email, password });
      setIsLoading(false);
      if (data.user.role === 'super_admin') {
        navigate('/super-admin');
      } else {
        navigate('/');
      }
    } catch (err: any) {
      setIsLoading(false);
      setError(err.message || 'Erro ao fazer login. Verifique suas credenciais.');
    }
  };

  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">
          Acesse sua conta
        </h2>
        <p className="mt-2 text-center text-sm text-zinc-600 dark:text-dark-muted">
          Ou{' '}
          <Link to="/register" className="font-medium text-brand-yellow hover:text-yellow-600">
            registre sua nova organização
          </Link>
        </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 shadow-zinc-200/50 dark:shadow-none rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
          <form className="space-y-6" onSubmit={handleLogin}>
            {error && (
              <div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg flex items-center gap-2 text-red-600 dark:text-red-400 text-sm animate-in fade-in slide-in-from-top-1">
                <AlertCircle size={18} />
                {error}
              </div>
            )}

            <div>
              <label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
                Endereço de E-mail
              </label>
              <div className="mt-1 relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Mail className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
                </div>
                <input
                  id="email"
                  name="email"
                  type="email"
                  autoComplete="email"
                  required
                  value={email}
                  onChange={(e) => validateEmail(e.target.value)}
                  className={`block w-full pl-10 pr-3 py-2 border ${emailError ? 'border-red-300 focus:ring-red-100 focus:border-red-500' : 'border-zinc-300 dark:border-dark-border focus:ring-brand-yellow/20 focus:border-brand-yellow'} rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 sm:text-sm transition-all`}
                  placeholder="seu@email.com"
                />
              </div>
              {emailError && <p className="mt-1 text-xs text-red-500">{emailError}</p>}
            </div>

            <div>
              <div className="flex items-center justify-between">
                <label htmlFor="password" senior-admin-password className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
                  Senha
                </label>
                <div className="text-sm">
                  <Link to="/forgot-password" size="14" className="font-medium text-brand-yellow hover:text-yellow-600 transition-colors">
                    Esqueceu a senha?
                  </Link>
                </div>
              </div>
              <div className="mt-1 relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Lock className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
                </div>
                <input
                  id="password"
                  name="password"
                  type={showPassword ? 'text' : 'password'}
                  autoComplete="current-password"
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="block w-full pl-10 pr-10 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 sm:text-sm focus:ring-brand-yellow/20 focus:border-brand-yellow transition-all"
                  placeholder="••••••••"
                />
                <button
                  type="button"
                  className="absolute inset-y-0 right-0 pr-3 flex items-center text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-200 transition-colors"
                  onClick={() => setShowPassword(!showPassword)}
                >
                  {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                </button>
              </div>
            </div>

            <div>
              <button
                type="submit"
                disabled={isLoading}
                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 transition-all disabled:opacity-70"
              >
                {isLoading ? (
                  <>
                    <Loader2 className="animate-spin h-5 w-5" /> Entrando...
                  </>
                ) : (
                  <>
                    Entrar <ArrowRight size={18} />
                  </>
                )}
              </button>
            </div>
          </form>

          <div className="mt-8">
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-zinc-200 dark:border-dark-border" />
              </div>
              <div className="relative flex justify-center text-sm">
                <span className="px-2 bg-white dark:bg-dark-card text-zinc-500 dark:text-dark-muted text-xs uppercase tracking-widest font-bold transition-colors">
                  Powered by <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-brand-yellow hover:underline">Blyzer</a>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
