import { useState, useEffect } from 'react';
import { Link, useSearchParams, useNavigate } from 'react-router-dom';
import { Eye, EyeOff, Loader2, CheckCircle, XCircle, Check, X } from 'lucide-react';

export default function ResetPassword() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [status, setStatus] = useState<'form' | 'success' | 'error' | 'no-token'>('form');
  const [error, setError] = useState<string | null>(null);

  const token = searchParams.get('token');

  const [formData, setFormData] = useState({
    password: '',
    confirmPassword: '',
  });

  useEffect(() => {
    if (!token) {
      setStatus('no-token');
    }
  }, [token]);

  // Password validation
  const passwordChecks = {
    length: formData.password.length >= 8,
    uppercase: /[A-Z]/.test(formData.password),
    lowercase: /[a-z]/.test(formData.password),
    number: /[0-9]/.test(formData.password),
    special: /[!@#$%^&*(),.?":{}|<>]/.test(formData.password),
    match: formData.password === formData.confirmPassword && formData.password.length > 0,
  };

  const isPasswordValid = Object.values(passwordChecks).every(Boolean);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!isPasswordValid || !token) return;

    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/v1/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          token,
          password: formData.password,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Error al restablecer contrasena');
      }

      setStatus('success');
    } catch (err) {
      setStatus('error');
      setError(err instanceof Error ? err.message : 'Error desconocido');
    } finally {
      setIsLoading(false);
    }
  };

  if (status === 'no-token') {
    return (
      <div className="text-center">
        <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
        <h2 className="text-2xl font-bold text-white mb-2">Enlace Invalido</h2>
        <p className="text-gray-400 mb-6">
          El enlace de restablecimiento no es valido o ha expirado.
        </p>
        <Link to="/forgot-password" className="btn btn-primary">
          Solicitar Nuevo Enlace
        </Link>
      </div>
    );
  }

  if (status === 'success') {
    return (
      <div className="text-center">
        <CheckCircle className="w-16 h-16 text-green-500 mx-auto mb-4" />
        <h2 className="text-2xl font-bold text-white mb-2">Contrasena Restablecida</h2>
        <p className="text-gray-400 mb-6">
          Tu contrasena ha sido cambiada exitosamente. Ya puedes iniciar sesion con tu nueva contrasena.
        </p>
        <Link to="/login" className="btn btn-primary">
          Iniciar Sesion
        </Link>
      </div>
    );
  }

  if (status === 'error') {
    return (
      <div className="text-center">
        <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
        <h2 className="text-2xl font-bold text-white mb-2">Error</h2>
        <p className="text-gray-400 mb-6">{error}</p>
        <div className="space-y-3">
          <button onClick={() => setStatus('form')} className="btn btn-primary">
            Intentar de Nuevo
          </button>
          <Link to="/forgot-password" className="btn btn-secondary block">
            Solicitar Nuevo Enlace
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div>
      <h2 className="text-2xl font-bold text-white mb-2">Nueva Contrasena</h2>
      <p className="text-gray-400 mb-6">
        Ingresa tu nueva contrasena
      </p>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="label">Nueva Contrasena</label>
          <div className="relative">
            <input
              type={showPassword ? 'text' : 'password'}
              className="input pr-10"
              placeholder="********"
              value={formData.password}
              onChange={(e) => setFormData({ ...formData, password: e.target.value })}
              required
            />
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
            >
              {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
            </button>
          </div>

          {formData.password.length > 0 && (
            <div className="mt-2 grid grid-cols-2 gap-1 text-xs">
              <PasswordCheck valid={passwordChecks.length} text="8+ caracteres" />
              <PasswordCheck valid={passwordChecks.uppercase} text="Una mayuscula" />
              <PasswordCheck valid={passwordChecks.lowercase} text="Una minuscula" />
              <PasswordCheck valid={passwordChecks.number} text="Un numero" />
              <PasswordCheck valid={passwordChecks.special} text="Un caracter especial" />
            </div>
          )}
        </div>

        <div>
          <label className="label">Confirmar Contrasena</label>
          <input
            type="password"
            className={`input ${
              formData.confirmPassword.length > 0 && !passwordChecks.match
                ? 'border-red-500 focus:border-red-500'
                : ''
            }`}
            placeholder="********"
            value={formData.confirmPassword}
            onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
            required
          />
          {formData.confirmPassword.length > 0 && !passwordChecks.match && (
            <p className="text-red-400 text-xs mt-1">Las contrasenas no coinciden</p>
          )}
        </div>

        <button
          type="submit"
          disabled={isLoading || !isPasswordValid}
          className="btn btn-primary w-full flex items-center justify-center gap-2"
        >
          {isLoading ? (
            <>
              <Loader2 className="w-5 h-5 animate-spin" />
              Restableciendo...
            </>
          ) : (
            'Restablecer Contrasena'
          )}
        </button>
      </form>

      <div className="mt-6 text-center text-sm text-gray-400">
        <Link to="/login" className="text-primary-400 hover:underline">
          Volver a Iniciar Sesion
        </Link>
      </div>
    </div>
  );
}

function PasswordCheck({ valid, text }: { valid: boolean; text: string }) {
  return (
    <div className={`flex items-center gap-1 ${valid ? 'text-green-400' : 'text-gray-500'}`}>
      {valid ? <Check className="w-3 h-3" /> : <X className="w-3 h-3" />}
      {text}
    </div>
  );
}
