'use client';

import { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { Button, Input, Label, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@horux/shared-ui';
import { requestPasswordReset } from '@/lib/api/auth';
import { Mail, CheckCircle2 } from 'lucide-react';

export default function ForgotPasswordPage() {
  const [isLoading, setIsLoading] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState('');

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setIsLoading(true);
    setError('');

    const formData = new FormData(e.currentTarget);
    const email = formData.get('email') as string;

    try {
      await requestPasswordReset(email);
      setSubmitted(true);
    } catch (err: any) {
      // Rate limit u otro error explícito
      setError(err.response?.data?.message || 'Error al enviar el enlace. Intenta más tarde.');
    } finally {
      setIsLoading(false);
    }
  }

  if (submitted) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <div className="flex justify-center mb-4">
            <div className="rounded-full bg-green-100 p-3">
              <CheckCircle2 className="h-10 w-10 text-green-600" />
            </div>
          </div>
          <CardTitle>Revisa tu correo</CardTitle>
          <CardDescription>
            Si el email que ingresaste está registrado, recibirás un enlace para restablecer tu contraseña.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="rounded-lg bg-muted/40 border p-4 text-sm text-muted-foreground">
            <p className="font-medium text-foreground mb-1">¿No recibiste el correo?</p>
            <ul className="list-disc pl-5 space-y-1 text-xs">
              <li>Revisa tu carpeta de spam o promociones</li>
              <li>El enlace expira en 1 hora — si pasó más tiempo, vuelve a solicitar</li>
              <li>Asegúrate de haber escrito bien tu email</li>
            </ul>
          </div>
        </CardContent>
        <CardFooter className="flex flex-col gap-2">
          <Button variant="outline" className="w-full" onClick={() => setSubmitted(false)}>
            Solicitar de nuevo
          </Button>
          <Link href="/login" className="text-sm text-primary hover:underline">
            Volver al login
          </Link>
        </CardFooter>
      </Card>
    </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
    <Card className="w-full max-w-md">
      <CardHeader className="text-center">
        <div className="flex justify-center mb-4">
          <Image src="/logo.jpg" alt="Horux360" width={80} height={80} className="rounded-full" priority />
        </div>
        <CardTitle className="text-2xl flex items-center justify-center gap-2">
          <Mail className="h-5 w-5" />
          Recuperar contraseña
        </CardTitle>
        <CardDescription>
          Ingresa tu email y te enviaremos un enlace para crear una nueva contraseña.
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit}>
        <CardContent className="space-y-4">
          {error && (
            <div className="p-3 text-sm text-destructive bg-destructive/10 rounded-md">
              {error}
            </div>
          )}
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              name="email"
              type="email"
              placeholder="tu@email.com"
              required
              autoFocus
            />
          </div>
        </CardContent>
        <CardFooter className="flex flex-col gap-4">
          <Button type="submit" className="w-full" disabled={isLoading}>
            {isLoading ? 'Enviando...' : 'Enviar enlace'}
          </Button>
          <Link href="/login" className="text-sm text-primary hover:underline">
            Volver al login
          </Link>
        </CardFooter>
      </form>
    </Card>
    </div>
  );
}
