'use client';
import axios from "axios"
import * as z from 'zod';
import Image from "next/image";
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useTranslations, useLocale } from 'next-intl';
import { useMutation } from '@tanstack/react-query';
import { Link, useRouter } from '@/i18n/navigation';
import { USER_TOKEN_CL } from "@/utils/data/user-client";
import { BASE_URL } from "@/utils/url";
import { toast } from '@/hooks/use-toast';

import { Briefcase, Loader, Lock, Mail, Phone, User2, Users } from 'lucide-react';

import { genders } from "@/constants";
import { Button } from '@/components/ui/button';
import { TextField } from '@/components/form/text-field';
import { Picker } from "@/components/form/picker";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { useState, useEffect } from "react";

import { useSearchParams } from 'next/navigation';

export function RegisterForm() {
    const t = useTranslations();
    const locale = useLocale();
    const router = useRouter();

    const signUpScheme = z.object({
        email: z.string().email("Invalid email address"),
        phone: z.string().min(5, "Phone is required"),
        first_name: z.string().min(2, "First name is required"),
        second_name: z.string().min(2, "Second name is required"),
        third_name: z.string().min(2, "Third name is required"),
        gender: z.enum(["male", "female"], {
            message: "Please select a gender"
        }),
        function: z.string().min(2, "Function/Role is required"),
        password: z.string()
            .min(8, t("custom.password-min"))
            .regex(/[A-Z]/, t("custom.password-upper"))
            .regex(/[a-z]/, t("custom.password-lower"))
            .regex(/[0-9]/, t("custom.password-number")),
        confirm_password: z.string().min(8, t("custom.confirm-password")),
        ref: z.string().optional(),
    }).refine((data) => data.password === data.confirm_password, {
        message: t("custom.passwords-dont-match"),
        path: ["confirm_password"],
    });

    type SignUpFormData = z.infer<typeof signUpScheme>;
    const [accepted, setAccepted] = useState(false);
    const searchParams = useSearchParams();
    const ref = searchParams.get('ref');

    useEffect(() => {
        const token = USER_TOKEN_CL();
        if (token) {
            router.push('/');
        }
    }, [router]);

    const {
        register,
        setValue,
        setError,
        watch,
        handleSubmit,
        formState: { errors },
    } = useForm<SignUpFormData>({
        resolver: zodResolver(signUpScheme),
        defaultValues: {
            email: "",
            phone: "",
            first_name: "",
            second_name: "",
            third_name: "",
            gender: undefined,
            function: "",
            password: "",
            confirm_password: "",
            ref: ref || "",
        }
    });

    // Watch password fields for real-time validation
    const password = watch("password");
    const confirmPassword = watch("confirm_password");

    useEffect(() => {
        // Only validate if confirm_password has a value
        if (confirmPassword) {
            if (password !== confirmPassword) {
                setError("confirm_password", {
                    type: "manual",
                    message: t("custom.passwords-dont-match")
                });
            } else {
                // Clear the error if passwords match
                setError("confirm_password", {
                    type: "manual",
                    message: undefined as any
                });
            }
        }
    }, [password, confirmPassword, setError]);


    const registerFnc = useMutation({
        mutationKey: ['signup'],
        mutationFn: async (data: SignUpFormData) => {
            const { ...body } = data;
            // Ensure ref is included if present in default values or explicitly passed
            if (ref && !body.ref) {
                 body.ref = ref;
            }

            // The API requires a username, so we copy the email string to it identically.
            const apiBody = {
                ...body,
                username: body.email
            };

            const response = await axios.post(`${BASE_URL}/register`, apiBody);

            if (response.status !== 200) throw new Error(response.data);

            return response.data;
        },
        onSuccess: (response) => {
            const status: boolean = response?.status;
            const errors: Record<string, string[]> = response?.errors;

            if (status) {
                toast({
                    variant: "success",
                    title: t('custom.done'),
                });

                setTimeout(() => router.push(`/login`), 1000);
            } else {
                Object.keys(errors).map((err) => {
                    setError((err as any), { type: "server", message: errors[err][0] });
                })
            }
        },
        onError: () => {
            toast({
                variant: "destructive",
                title: t('custom.failed'),
                description: t('custom.try-again')
            })
        }
    });

    return (
        <div className="w-full px-4 py-12">
            <div className="space-y-4">
                <div className="w-40 pt-6">
                    <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("register.desc")}
                    </p>
                </div>
            </div>

            <div className="py-10 flex flex-col justify-center w-full">
                <form
                    className="text-black grid  md:grid-cols-3 gap-4 "
                    onKeyDown={(e) => {
                        if (!accepted) return;
                        if (e.key === "Enter") {
                            e.stopPropagation();
                            e.preventDefault();
                            handleSubmit((data) => registerFnc.mutate(data))();
                        }
                    }}
                    onSubmit={handleSubmit((data) => registerFnc.mutate(data))}
                >
                    {/* ROW 1: Names */}
                    {/* first name */}
                    <TextField
                        label={t("form.first-name")}
                        placeholder={t('placeholder.first-name')}
                        labelIcon={<User2 className='size-3.5' />}
                        register={register}
                        registerFor='first_name'
                        errors={errors}
                        required
                    />

                    {/* second name */}
                    <TextField
                        label={t("form.second-name")}
                        placeholder={t('placeholder.second-name')}
                        labelIcon={<User2 className='size-3.5' />}
                        register={register}
                        registerFor='second_name'
                        errors={errors}
                        required
                    />

                    {/* third name */}
                    <TextField
                        label={t("form.third-name")}
                        placeholder={t('placeholder.third-name')}
                        labelIcon={<User2 className='size-3.5' />}
                        register={register}
                        registerFor='third_name'
                        errors={errors}
                        required
                    />

                    {/* ROW 2: Contact Information */}
                    {/* 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
                    />

                    {/* phone */}
                    <TextField
                        label={t("form.phone")}
                        placeholder={t('placeholder.phone')}
                        labelIcon={<Phone className='size-3.5' />}
                        type="number"
                        register={register}
                        registerFor='phone'
                        errors={errors}
                        required
                    />

                    {/* ROW 3: Additional Information */}
                    {/* gender */}
                    <Picker
                        items={genders(t)}
                        label={t("form.gender")}
                        labelIcon={<Users className='size-3.5' />}
                        placeHolder={t('placeholder.select-gender')}
                        setValue={setValue}
                        setValueFor={"gender"}
                        value={watch("gender")}
                        required
                    />

                    {/* function */}
                    <TextField
                        label={t("form.function")}
                        placeholder={t('placeholder.function')}
                        labelIcon={<Briefcase className='size-3.5' />}
                        register={register}
                        registerFor='function'
                        errors={errors}
                        required
                    />

                    

                    {/* ROW 4: Security */}
                    {/* password */}
                    <TextField
                        label={t("form.password")}
                        placeholder={t('placeholder.password')}
                        labelIcon={<Lock className='size-3.5' />}
                        type='password'
                        register={register}
                        registerFor='password'
                        errors={errors}
                        toggleSeePassword
                        required
                    />

                    {/* confirm password */}
                    <TextField
                        label={t("form.confirm-password")}
                        placeholder={t('placeholder.confirm-password')}
                        labelIcon={<Lock className='size-3.5' />}
                        type='password'
                        register={register}
                        registerFor='confirm_password'
                        errors={errors}
                        toggleSeePassword
                        required
                    />
                    {/* referral code */}
                    <TextField
                        label={t("form.referral-code")}
                        placeholder={t('placeholder.referral-code')}
                        labelIcon={<User2 className='size-3.5' />}
                        register={register}
                        registerFor='ref'
                        errors={errors}
                    />
                    <div className="md:col-span-3 flex flex-col gap-3">
                        <div className="flex items-center gap-2">
                            <Checkbox
                                id="privacy"
                                checked={accepted}
                                onCheckedChange={(value) => setAccepted(!!value)}
                                required
                            />
                             <span>
                                    {t("custom.accept_privacy")}
                                </span>
                            <Label htmlFor="privacy" className="flex items-center gap-1">
                               
                                <Link className="text-primary-tw-400 lowercase" target='_blank' href={'/privacy'}>
                                    {t("routes.privacy")}
                                </Link>
                            </Label>
                        </div>
                    </div>
                    <div className="md:col-span-3 grid place-items-center mt-4 gap-4">
                        <Button
                            type="submit"
                            disabled={registerFnc.isPending || !accepted}
                            className='w-full bg-primary-tw-400 text-white'
                        >
                            {registerFnc.isPending ? (
                                <>
                                    <Loader className="w-5 h-5 animate-spin" />
                                    {t('custom.submitting')}
                                </>
                            ) : (
                                t("custom.register now")
                            )}
                        </Button>

                        <div className="text-center text-gray-600 text-sm">
                            {t("form.have-acc")}{" "}
                            <Link
                                href="/login"
                                className="text-purple-800 font-semibold !underline underline-offset-1"
                            >
                                {t("routes.login")}
                            </Link>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    );
};