'use client';
import * as z from 'zod';
import Image from "next/image";

import { useForm } from 'react-hook-form';
import { useTranslations, useLocale } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { toast } from '@/hooks/use-toast';
import { useFormSubmission } from '@/hooks/use-form-submission';

import { Loader, Mail } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { TextField } from '@/components/form/text-field';
import { Label } from "@/components/ui/label";

const resetPasswordSchema = z.object({
    email: z.string().email('Invalid email address'),
});
type ResetPasswordFormData = z.infer<typeof resetPasswordSchema>;

export function ResetPasswordForm() {
    const t = useTranslations();
    const locale = useLocale();

    const {
        register,
        handleSubmit,
        formState: { errors },
        getValues
    } = useForm<ResetPasswordFormData>({
        defaultValues: {
            email: '',
        },
    });

    const resetFunc = useFormSubmission({
        endPoint: '/password/reset',
        method: 'POST',
        context: 'main',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        onSuccess: (response) => {
            const email = getValues('email');
            toast({
                variant: "success",
                title: t('custom.done'),
                description: t('custom.reset-link-sent'),
            });

            window.location.href = `/reset-password/verify?email=${encodeURIComponent(email)}`;
        },
        onError: (err: any) => {
            const serverError = err?.response?.data?.error || err?.response?.data?.message;
            let finalDescription = serverError || t('custom.email-not-found');

            if (typeof serverError === 'string' && serverError.includes('Too many password reset requests')) {
                const minutesMatch = serverError.match(/\d+/);
                const minutes = minutesMatch ? minutesMatch[0] : '15';
                finalDescription = t('custom.too-many-requests-reset', { minutes });
            }

            toast({
                variant: "destructive",
                title: t('custom.failed'),
                description: finalDescription
            });
            return { handled: true };
        }
    })

    const onSubmit = (data: ResetPasswordFormData) => {
        resetFunc.mutate({ identifier: data.email });
    };

    return (
        <div className="w-full px-6">
            <div className="space-y-4">
                <div className="w-40">
                    <Link href={'/'}>
                        <Image
                            src={locale === 'ar' ? '/images/logo.png' : '/images/logo-en.png'}
                            alt="mwaheb-logo"
                            className="w-full h-20 object-contain"
                            width={200}
                            height={200}
                            priority
                        />
                    </Link>
                </div>
                <div className="text-start mb-8">
                    <p className="text-baby-blue w-64 font-bold text-xl">
                        {t("reset-password.desc")}
                    </p>
                </div>
            </div>
            <div className="flex-1 py-10 flex flex-col justify-center mx-auto w-full">
                <form className="space-y-6 text-black"
                    onSubmit={handleSubmit(onSubmit)}
                >
                    {/* email */}
                    <TextField
                        label={t("form.email")}
                        placeholder={t('placeholder.email')}
                        labelIcon={<Mail className='size-3.5' />}
                        type="email"

                        register={register}
                        registerFor='email'
                        errors={errors}
                        required
                    />

                    <Button
                        type="submit"
                        disabled={resetFunc.isPending}
                        className='w-full bg-primary-tw-400 text-white'
                    >
                        {resetFunc.isPending ? (
                            <>
                                <Loader className="w-5 h-5 animate-spin" />
                                {t('custom.submitting')}
                            </>
                        ) : (
                            t("custom.send-reset-link")
                        )}
                    </Button>

                    {/* Back to Login */}
                    <div className="text-center text-gray-600 text-sm">
                        <Link
                            href="/login"
                            className="text-purple-800 font-semibold !underline underline-offset-1"
                        >
                            {t("custom.back-to-login")}
                        </Link>
                    </div>
                </form>
            </div>
        </div>
    );
};
