import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button, Input, Card } from '../../components/ui';
import { useResetPasswordWithToken } from '../../api/hooks/auth';
import { showToast } from '../../utils/toast';
import { PublicLayout } from '../../components/layout';

const ResetPasswordPage: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [errors, setErrors] = useState<{ password?: string; confirmPassword?: string }>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  
  const token = searchParams.get('token');

  useEffect(() => {
    if (!token) {
      navigate('/forgot-password');
      showToast.error('Token de restablecimiento inválido o ausente.', { title: 'Error' });
    }
  }, [token, navigate]);

  const { mutate: resetPasswordWithToken } = useResetPasswordWithToken({
    onSuccess: () => {
      showToast.success('Tu contraseña ha sido restablecida exitosamente.', {
        title: '¡Contraseña Actualizada!'
      });
      setIsSubmitted(true);
    },
    onError: (error: any) => {
      const errorMessage = error.response?.data?.detail || 
                          'Hubo un problema al restablecer tu contraseña.';
      showToast.error(errorMessage, { title: 'Error' });
    },
    onSettled: () => {
      setIsSubmitting(false);
    }
  });

  const validateForm = (): boolean => {
    const newErrors: { password?: string; confirmPassword?: string } = {};

    if (!password) {
      newErrors.password = 'La contraseña es requerida';
    } else if (password.length < 8) {
      newErrors.password = 'La contraseña debe tener al menos 8 caracteres';
    } else if (!/(?=.*[a-z])/.test(password)) {
      newErrors.password = 'La contraseña debe contener al menos una letra minúscula';
    } else if (!/(?=.*[A-Z])/.test(password)) {
      newErrors.password = 'La contraseña debe contener al menos una letra mayúscula';
    } else if (!/(?=.*\d)/.test(password)) {
      newErrors.password = 'La contraseña debe contener al menos un número';
    }

    if (!confirmPassword) {
      newErrors.confirmPassword = 'Confirma tu nueva contraseña';
    } else if (password !== confirmPassword) {
      newErrors.confirmPassword = 'Las contraseñas no coinciden';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

    if (!validateForm() || !token) {
      return;
    }

    setIsSubmitting(true);
    resetPasswordWithToken({ token, newPassword: password });
  };

  const handleGoToLogin = () => {
    navigate('/login');
  };

  if (isSubmitted) {
    return (
      <PublicLayout
        variant="centered"
        maxWidth="md"
        headerProps={{
          showThemeToggle: true,
          showAuthButtons: false,
          showLanguageSelector: true,
          variant: "minimal"
        }}
      >
        <Card className="p-8 w-full max-w-md mx-auto" role="main">
          <div className="text-center mb-8">
            <div className="mx-auto bg-color-success/10 p-3 rounded-full w-16 h-16 flex items-center justify-center mb-4">
              <svg
                className="w-8 h-8 text-color-success"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                aria-hidden="true"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h1 className="text-2xl font-bold text-text-primary mb-2">
              {t('auth:reset_password.success_title', '¡Contraseña Restablecida!')}
            </h1>
            <p className="text-text-secondary">
              {t('auth:reset_password.success_message', 'Tu contraseña ha sido actualizada exitosamente.')}
            </p>
          </div>

          <div className="space-y-4">
            <Button
              variant="primary"
              size="lg"
              isFullWidth
              onClick={handleGoToLogin}
            >
              Iniciar Sesión
            </Button>
          </div>
        </Card>
      </PublicLayout>
    );
  }

  return (
    <PublicLayout
      variant="centered"
      maxWidth="md"
      headerProps={{
        showThemeToggle: true,
        showAuthButtons: false,
        showLanguageSelector: true,
        variant: "minimal"
      }}
    >
      <Card className="p-8 w-full max-w-md mx-auto" role="main">
        <div className="text-center mb-8">
          <h1 className="text-2xl font-bold text-text-primary mb-2">
            {t('auth:reset_password.title', 'Restablecer Contraseña')}
          </h1>
          <p className="text-text-secondary">
            {t('auth:reset_password.subtitle', 'Ingresa tu nueva contraseña.')}
          </p>
        </div>

        <form
          onSubmit={handleSubmit}
          className="space-y-6"
          noValidate
          aria-label={t('auth:reset_password.title', 'Formulario de restablecimiento de contraseña')}
        >
          <div>
            <Input
              type={showPassword ? 'text' : 'password'}
              label="Nueva Contraseña"
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              error={errors.password}
              disabled={isSubmitting}
              required
              aria-describedby={errors.password ? 'password-error' : undefined}
              leftIcon={
                <svg
                  className="w-5 h-5"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  aria-hidden="true"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
              }
              rightIcon={
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="text-text-secondary hover:text-text-primary transition-colors"
                  aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
                  tabIndex={0}
                >
                  {showPassword ? (
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                      aria-hidden="true"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                    </svg>
                  ) : (
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                      aria-hidden="true"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>
                  )}
                </button>
              }
            />
            {errors.password && (
              <p id="password-error" className="text-color-error text-sm mt-1" role="alert">
                {errors.password}
              </p>
            )}
          </div>

          <div>
            <Input
              type={showConfirmPassword ? 'text' : 'password'}
              label="Confirmar Nueva Contraseña"
              placeholder="••••••••"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              error={errors.confirmPassword}
              disabled={isSubmitting}
              required
              aria-describedby={errors.confirmPassword ? 'confirm-password-error' : undefined}
              leftIcon={
                <svg
                  className="w-5 h-5"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  aria-hidden="true"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
              }
              rightIcon={
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="text-text-secondary hover:text-text-primary transition-colors"
                  aria-label={showConfirmPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
                  tabIndex={0}
                >
                  {showConfirmPassword ? (
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                      aria-hidden="true"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                    </svg>
                  ) : (
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                      aria-hidden="true"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>
                  )}
                </button>
              }
            />
            {errors.confirmPassword && (
              <p id="confirm-password-error" className="text-color-error text-sm mt-1" role="alert">
                {errors.confirmPassword}
              </p>
            )}
          </div>

          <Button
            type="submit"
            variant="primary"
            size="lg"
            isFullWidth
            isLoading={isSubmitting}
            loadingText="Actualizando contraseña..."
            disabled={isSubmitting}
          >
            {isSubmitting ? 'Actualizando...' : 'Actualizar Contraseña'}
          </Button>
        </form>

        <div className="mt-6 text-center">
          <button
            type="button"
            onClick={handleGoToLogin}
            className="text-sm text-color-primary hover:text-color-primary-dark transition-colors underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-color-primary focus:ring-offset-2 rounded"
          >
            ← Volver al Inicio de Sesión
          </button>
        </div>
      </Card>
    </PublicLayout>
  );
};

export default ResetPasswordPage;