'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { BrandedAuthShell } from '@/components/shared/branded-auth-shell';
import { cn } from '@/lib/utils';

const resetSchema = z.object({
  email: z.string().email('Please enter a valid email address'),
});

type ResetFormData = z.infer<typeof resetSchema>;

export default function ResetPasswordPage() {
  const [submitted, setSubmitted] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

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

  async function onSubmit(data: ResetFormData) {
    setIsLoading(true);
    try {
      // Always show the same success message regardless of whether the email exists.
      await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: data.email }),
      });

      setSubmitted(true);
    } catch {
      toast.error('Something went wrong. Please try again.');
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <BrandedAuthShell>
      <div className="text-center mb-6">
        <h1 className="text-xl font-semibold text-gray-900">Reset your password</h1>
        <p className="text-sm text-gray-500 mt-1">We&apos;ll email you a link</p>
      </div>

      {submitted ? (
        <div className="space-y-4 text-center">
          <p className="font-medium text-gray-900">Check your email</p>
          <p className="text-sm text-gray-500">
            If an account exists for that email address, we have sent a password reset link. Please
            check your inbox and spam folder.
          </p>
          <Link href="/login" className="inline-block text-sm text-[#007bff] hover:underline">
            Back to sign in
          </Link>
        </div>
      ) : (
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
          <div className="space-y-1.5">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              autoComplete="email"
              placeholder="you@example.com"
              disabled={isLoading}
              className={cn(errors.email && 'border-destructive focus-visible:ring-destructive')}
              {...register('email')}
            />
            {errors.email && <p className="text-sm text-destructive">{errors.email.message}</p>}
          </div>

          <Button
            type="submit"
            className="w-full bg-[#007bff] hover:bg-[#0069d9] text-white"
            disabled={isLoading}
          >
            {isLoading ? 'Sending…' : 'Send reset link'}
          </Button>

          <p className="text-center text-sm text-gray-500">
            Remember your password?{' '}
            <Link href="/login" className="text-[#007bff] hover:underline">
              Sign in
            </Link>
          </p>
        </form>
      )}
    </BrandedAuthShell>
  );
}
