'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2, Mail } from 'lucide-react';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { api, apiEndpoints } from '@/lib/api';
import { forgotPasswordSchema, type ForgotPasswordFormData } from '@/lib/validators';
import { useToast } from '@/hooks/use-toast';

export default function ForgotPasswordPage() {
  const router = useRouter();
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);

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

  const onSubmit = async (data: ForgotPasswordFormData) => {
    setIsLoading(true);
    try {
      await api.post(apiEndpoints.auth.forgotPassword, data);

      setIsSubmitted(true);
      toast({
        title: 'Solicitud enviada',
        description: 'Si el email existe, recibirás un mensaje con instrucciones.',
      });
    } catch (error) {
      // Even on error, show success message to prevent email enumeration
      setIsSubmitted(true);
      toast({
        title: 'Solicitud enviada',
        description: 'Si el email existe, recibirás un mensaje con instrucciones.',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const onSubmitHandler = (e: React.FormEvent) => {
    e.preventDefault();
    void handleSubmit(onSubmit)(e);
  };

  if (isSubmitted) {
    return (
      <Card className="w-full">
        <CardHeader className="space-y-1 text-center">
          <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
            <Mail className="h-6 w-6 text-primary" />
          </div>
          <CardTitle className="text-2xl">Solicitud enviada</CardTitle>
          <CardDescription>
            Si existe una cuenta con ese email, recibirás un mensaje via Telegram
            con el token para restablecer tu contraseña.
          </CardDescription>
        </CardHeader>
        <CardContent className="text-center text-sm text-muted-foreground">
          <p>
            El token expira en 1 hora. Si no tienes Telegram configurado,
            el token será enviado al administrador quien te lo reenviará.
          </p>
        </CardContent>
        <CardFooter className="flex flex-col space-y-4">
          <Button
            variant="outline"
            className="w-full"
            onClick={() => router.push('/login')}
          >
            Volver al login
          </Button>
          <p className="text-sm text-center text-muted-foreground">
            ¿No recibiste el mensaje?{' '}
            <button
              onClick={() => setIsSubmitted(false)}
              className="text-primary hover:underline"
            >
              Intentar nuevamente
            </button>
          </p>
        </CardFooter>
      </Card>
    );
  }

  return (
    <Card className="w-full">
      <CardHeader className="space-y-1 text-center">
        <CardTitle className="text-2xl">Recuperar contraseña</CardTitle>
        <CardDescription>
          Ingresa tu email para recibir un token de restablecimiento via Telegram
        </CardDescription>
      </CardHeader>
      <form onSubmit={onSubmitHandler}>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              placeholder="tu@email.com"
              disabled={isLoading}
              {...register('email')}
            />
            {errors.email && (
              <p className="text-sm text-destructive">{errors.email.message}</p>
            )}
          </div>
        </CardContent>

        <CardFooter className="flex flex-col space-y-4">
          <Button type="submit" className="w-full" disabled={isLoading}>
            {isLoading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Enviando...
              </>
            ) : (
              'Enviar solicitud'
            )}
          </Button>

          <p className="text-sm text-center text-muted-foreground">
            ¿Recordaste tu contraseña?{' '}
            <Link href="/login" className="text-primary hover:underline">
              Volver al login
            </Link>
          </p>
        </CardFooter>
      </form>
    </Card>
  );
}