"use client";

import { useForm } from "react-hook-form";
import InputField from "@/components/ui/Input";
import Button from "@/components/ui/Button";

import { ROUTES } from "@/utils/Routing";
import { useRouter } from "next/navigation";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useAuthStore } from "@/zustand/auth/useAuthStore";
import { encrypt } from "@/utils/Crypto";
import { useEffect, useState } from "react";
import { LRFFlowContent } from "@/types/staticContent/lrfflow.content.type";
import { stat } from "fs";

type SignupFormValues = {
    first_name: string
    last_name: string
    email: string
    username: string
    password: string
    confirmPassword: string
    profile_picture: FileList
}

export default function SignupForm({ staticContent }: { staticContent: LRFFlowContent["SIGNUP"] }) {
    const router = useRouter();
    const { registerUser, isLoading, language } = useAuthStore()
    const signupSchema = yup.object({
        first_name: yup.string().required(staticContent.FORM.FIRST_NAME_REQUIRED),
        last_name: yup.string().required(staticContent.FORM.LAST_NAME_REQUIRED),
        username: yup.string().required(staticContent.FORM.USERNAME_REQUIRED),
        email: yup
            .string()
            .required(staticContent.FORM.EMAIL_REQUIRED)
            .matches(
                /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
                staticContent.FORM.EMAIL_INVALID
            ),
        password: yup
            .string()
            .required(staticContent.FORM.PASSWORD_REQUIRED)
            .min(6, staticContent.FORM.PASSWORD_MIN_LENGTH),
        confirmPassword: yup
            .string()
            .required(staticContent.FORM.CONFIRM_PASSWORD_REQUIRED)
            .oneOf([yup.ref("password")], staticContent.FORM.PASSWORD_NOT_MATCHED),

        profile_picture: yup
            .mixed<FileList>()
            .nullable()
            .test("fileSize", staticContent.FORM.FILE_TOO_LARGE, (value) => {
                if (!value || value.length === 0) return true
                return value[0].size <= 2_000_000
            })
            .test("fileType", staticContent.FORM.FILE_TYPE_INVALID, (value) => {
                if (!value || value.length === 0) return true
                return ["image/jpeg", "image/png", "image/webp"].includes(value[0].type)
            }),
    })

    const {
        register,
        handleSubmit,
        watch,
        setValue,
        getValues,
        reset,
        formState: { errors },
    } = useForm<any>({
        resolver: yupResolver(signupSchema),
    });
    const profile_picture = watch("profile_picture");
    const [preview, setPreview] = useState<string | null>(null);

    useEffect(() => {
        if (profile_picture && profile_picture.length > 0) {
            const file = profile_picture[0];
            const url = URL.createObjectURL(file);
            setPreview(url);

            return () => URL.revokeObjectURL(url);
        } else {
            setPreview(null);
        }
    }, [profile_picture]);

    const removeImage = () => {
        setValue("profile_picture", null, { shouldValidate: true });
        setPreview(null);
    };
    useEffect(() => {
        // Forces form to re-validate with new resolver
        reset(
            {
                email: getValues("email"),
                first_name: getValues("first_name"),
                last_name: getValues("last_name"),
                username: getValues("username"),
                password: getValues("password"),
                confirmPassword: getValues("confirmPassword"),
                profile_picture: getValues("profile_picture"),
            },
            { keepValues: true, keepDirty: true }
        )
    }, [language, reset, getValues])
    const onSubmit = (data: SignupFormValues) => {
        const formData = new FormData()

        formData.append("first_name", data.first_name)
        formData.append("last_name", data.last_name)
        formData.append("email", data.email)
        formData.append("username", data.username)
        formData.append("password", data.password)

        if (data.profile_picture?.[0]) {
            formData.append("profile_picture", data.profile_picture[0])
        }

        // send to API
        // await authStore.signup(formData)
        registerUser(formData, (success) => {
            if (!success) return
            router.push(
                `${ROUTES.VERIFY_YOUR_EMAIL}?email=${encodeURIComponent(
                    encrypt(data.email)
                )}&type=register`
            )
        }, true)


        // router.push(ROUTES.LOGIN)
    }


    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            {/* Avatar */}
            <div className="relative w-16 h-16 lg:w-[90px] lg:h-[90px] border border-grey32 rounded-full flex justify-center items-center mx-auto mb-4 lg:mb-6 2xl:mb-10">

                {preview ? (
                    <>
                        <img
                            src={preview}
                            alt={staticContent.FORM.PROFILE_PREVIEW}
                            className="w-full h-full object-cover rounded-full"
                        />

                        <button
                            type="button"
                            onClick={removeImage}
                            className="absolute top-0.5 lg:top-1 right-0.5 lg:right-1 bg-black rounded-full w-4.5 h-4.5 lg:w-5.5 lg:h-5.5 flex justify-center items-center cursor-pointer hover:bg-primary duration-300 ease-in-out"
                        >
                            <i className="icon icon-close w-3.5 h-3.5 lg:w-4.5 lg:h-4.5 bg-white "></i>
                        </button>
                    </>
                ) : (
                    <>
                        <i className="icon icon-user w-6 lg:w-8 h-6 lg:h-8 bg-light"></i>

                        <button
                            type="button"
                            className="bg-primary w-5 lg:w-7.5 h-5 lg:h-7.5 rounded-full absolute bottom-0 right-0 flex justify-center items-center cursor-pointer"
                        >
                            <i className="icon icon-camera w-3.5 lg:w-4 h-3.5 lg:h-4 bg-white"></i>
                            <input
                                type="file"
                                accept="image/*"
                                {...register("profile_picture")}
                                className="w-full h-full opacity-0 cursor-pointer absolute inset-0 text-[0px] leading-0"
                            />
                        </button>
                    </>
                )}
            </div>

            {errors.profile_picture && (
                <p className="text-red-500 text-xs text-center">
                    {errors.profile_picture.message as string}
                </p>
            )}


            <div className="flex flex-col md:flex-row gap-x-4">
                <InputField
                    label={staticContent.FORM.FIRST_NAME}
                    placeholder={staticContent.FORM.FIRST_NAME}
                    {...register("first_name")}
                    error={errors.first_name}
                />

                <InputField
                    label={staticContent.FORM.LAST_NAME}
                    placeholder={staticContent.FORM.LAST_NAME}
                    {...register("last_name")}
                    error={errors.last_name}
                />
            </div>

            <InputField
                type="email"
                label={staticContent.FORM.EMAIL_ADDRESS}
                placeholder={staticContent.FORM.EMAIL}
                {...register("email")}
                error={errors.email}
            />

            <InputField
                label={staticContent.FORM.USERNAME}
                placeholder={staticContent.FORM.USERNAME}
                {...register("username")}
                error={errors.username}
            />

            <InputField
                type="password"
                label={staticContent.FORM.PASSWORD}
                placeholder={staticContent.FORM.PASSWORD}
                {...register("password")}
                error={errors.password}
            />

            <InputField
                type="password"
                label={staticContent.FORM.CONFIRM_PASSWORD}
                placeholder={staticContent.FORM.CONFIRM_PASSWORD}
                {...register("confirmPassword")}
                error={errors.confirmPassword}
            />

            <Button type="submit" variant="primary" isLoading={isLoading} >{staticContent.SIGN_UP}</Button>

            <span className="block text-center mt-4 md:mt-6 text-grey92">
                {staticContent.ALREADY_HAVE_ACCOUNT}{" "}
                <Button as="link" href={ROUTES.LOGIN} linkVariant="text">
                    {staticContent.LOGIN}
                </Button>
            </span>
        </form>
    );
}
