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

import { useEffect } from "react";
import { useForm } from 'react-hook-form';
import { useTranslations, useLocale } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { useSearchParams } from 'next/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";
import { OTPInput } from '@/components/form/otp-input';

const verifyResetSchema = z.object({
    email: z.string().email('Invalid email address'),
    otp: z.string().length(6, 'OTP must be 6 digits'),
});
type VerifyResetFormData = z.infer<typeof verifyResetSchema>;

export function ResetPasswordVerifyForm() {
    const t = useTranslations();
    const locale = useLocale();
    const searchParams = useSearchParams();
    const emailFromUrl = searchParams.get('email') || '';

    const {
        register,
        handleSubmit,
        formState: { errors },
        getValues,
        setValue,
        watch
    } = useForm<VerifyResetFormData>({
        defaultValues: {
            email: emailFromUrl,
            otp: '',
        },
    });

    useEffect(() => {
        if (emailFromUrl) {
            setValue('email', emailFromUrl);
        }
    }, [emailFromUrl, setValue]);

    const otpValue = watch('otp');

    const verifyFunc = useFormSubmission({
        endPoint: '/password/confirm-code/store',
        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.otp-verified'),
            });

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

            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 resendFunc = useFormSubmission({
        endPoint: '/password/reset',
        method: 'POST',
        context: 'main',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        onSuccess: () => {
            toast({
                variant: "success",
                title: t('custom.done'),
                description: t('custom.otp-resent'),
            });
        },
        onError: (err: any) => {
            const serverError = err?.response?.data?.error || err?.response?.data?.message;
            let finalDescription = serverError || t('custom.try-again');

            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: VerifyResetFormData) => {
        verifyFunc.mutate({
            identifier: data.email,
            confirmation_code: data.otp
        });
    };

    const handleResend = () => {
        const email = getValues('email');
        if (email) {
            resendFunc.mutate({ identifier: 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.verify-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)}
                >
                    {/* Hidden email field */}
                    <input type="hidden" {...register('email')} />

                    {/* OTP */}
                    <div className="space-y-2">
                        <Label htmlFor="otp" className="text-nowrap">
                            * {t("form.otp")}
                        </Label>
                        <OTPInput
                            value={otpValue}
                            onChange={(value) => setValue('otp', value)}
                            length={6}
                        />
                        {errors.otp && (
                            <span className="text-sm text-destructive">
                                {errors.otp.message}
                            </span>
                        )}
                    </div>

                    <Button
                        type="submit"
                        disabled={verifyFunc.isPending || otpValue.length !== 6}
                        className='w-full bg-primary-tw-400 text-white'
                    >
                        {verifyFunc.isPending ? (
                            <>
                                <Loader className="w-5 h-5 animate-spin" />
                                {t('custom.submitting')}
                            </>
                        ) : (
                            t("custom.verify")
                        )}
                    </Button>

                    {/* Resend OTP */}
                    <div className="text-center">
                        <button
                            type="button"
                            onClick={handleResend}
                            disabled={resendFunc.isPending}
                            className="text-primary-tw-400 hover:underline text-sm"
                        >
                            {resendFunc.isPending ? t('custom.sending') : t('custom.resend-otp')}
                        </button>
                    </div>

                    {/* 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>
    );
};
