import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Mail, ArrowLeft, CheckCircle } from 'lucide-react';
import { AuthLayout } from '@app/layouts/AuthLayout';
import { Button } from '@components/atoms/Button';
import { FormField } from '@components/molecules/FormField';
import { Alert } from '@components/molecules/Alert';
import { authApi } from '@services/api/auth.api';

const forgotPasswordSchema = z.object({
  email: z.string().email('Email inválido'),
});

type ForgotPasswordFormData = z.infer<typeof forgotPasswordSchema>;

export default function ForgotPasswordPage() {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isSuccess, setIsSuccess] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<ForgotPasswordFormData>({
    resolver: zodResolver(forgotPasswordSchema),
  });

  const onSubmit = async (data: ForgotPasswordFormData) => {
    setIsLoading(true);
    setError(null);
    try {
      await authApi.forgotPassword(data.email);
      setIsSuccess(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al enviar el correo');
    } finally {
      setIsLoading(false);
    }
  };

  if (isSuccess) {
    return (
      <AuthLayout
        title="Correo enviado"
        subtitle="Revisa tu bandeja de entrada"
      >
        <div className="text-center">
          <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-success-100">
            <CheckCircle className="h-6 w-6 text-success-600" />
          </div>
          <p className="mt-4 text-sm text-gray-600">
            Hemos enviado un correo con instrucciones para restablecer tu contraseña.
            Si no lo encuentras, revisa tu carpeta de spam.
          </p>
          <Link
            to="/login"
            className="mt-6 inline-flex items-center text-sm font-medium text-primary-600 hover:text-primary-500"
          >
            <ArrowLeft className="mr-2 h-4 w-4" />
            Volver al inicio de sesión
          </Link>
        </div>
      </AuthLayout>
    );
  }

  return (
    <AuthLayout
      title="¿Olvidaste tu contraseña?"
      subtitle="Ingresa tu email y te enviaremos instrucciones para restablecerla"
    >
      {error && (
        <Alert variant="danger" onClose={() => setError(null)} className="mb-4">
          {error}
        </Alert>
      )}

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          label="Email"
          type="email"
          placeholder="tu@email.com"
          error={errors.email?.message}
          leftIcon={<Mail className="h-5 w-5" />}
          {...register('email')}
        />

        <Button type="submit" fullWidth isLoading={isLoading}>
          Enviar instrucciones
        </Button>
      </form>

      <Link
        to="/login"
        className="mt-6 flex items-center justify-center text-sm font-medium text-primary-600 hover:text-primary-500"
      >
        <ArrowLeft className="mr-2 h-4 w-4" />
        Volver al inicio de sesión
      </Link>
    </AuthLayout>
  );
}
