"use client"
import Button from "@/components/ui/Button"
import InputField from "@/components/ui/Input"
import { ROUTES } from "@/utils/Routing"
import { useForm } from "react-hook-form"
import { yupResolver } from "@hookform/resolvers/yup"
import { useRouter } from "next/navigation"

import * as yup from "yup";
import { useAuthStore } from "@/zustand/auth/useAuthStore"
import { useEffect, useMemo } from "react"
import { getDecryptedCookie, removeCookie, setEncryptedCookie } from "@/utils/Cookies"
import { LRFFlowContent } from "@/types/staticContent/lrfflow.content.type"

type LoginFormValues = {
    email: string
    password: string
    remember?: boolean
}


function LoginForm({ staticContent }: { staticContent: LRFFlowContent["LOGIN"] }) {
    const router = useRouter()
    const { login, isLoading, language } = useAuthStore()

    // const loginSchema = yup.object({
    //     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),
    // });
    const loginSchema = useMemo(() => {
        return yup.object({
            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),
            // remember: no validation needed
        })
    }, [language, staticContent])
    const {
        register,
        handleSubmit,
        setValue,
        trigger,
        reset,
        getValues,
        formState: { errors },
    } = useForm<LoginFormValues>({
        resolver: yupResolver(loginSchema),
    })

    useEffect(() => {
        // Forces form to re-validate with new resolver
        reset(
            {
                email: getValues("email"),
                password: getValues("password"),
                remember: getValues("remember"),
            },
            { keepValues: true, keepDirty: true }
        )
    }, [language, reset, getValues])
    useEffect(() => {
        const remembered = getDecryptedCookie<{
            email: string
            password: string
        }>("remember-auth")

        if (remembered) {
            setValue("email", remembered.email)
            setValue("password", remembered.password)
            setValue("remember", true)
        }
    }, [setValue])

    const onSubmit = (data: LoginFormValues) => {
        const { email, password, remember } = data



        login(
            { email, password },
            (success) => {
                if (!success) return
                router.push(ROUTES.DASHBOARD)
                if (remember) {
                    setEncryptedCookie(
                        "remember-auth",
                        { email, password },
                        { maxAge: 60 * 60 * 24 * 7 } // 7 days
                    )
                } else {
                    removeCookie("remember-auth")
                }
            },
            true
        )
    }


    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <InputField
                type="text"
                label={staticContent.FORM.ENTER_EMAIL}
                placeholder={staticContent.FORM.EMAIL}
                {...register("email")}
                error={errors.email}
            />

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

            <div className="flex items-center justify-between gap-3 mb-6">
                <InputField
                    type="checkbox"
                    label={staticContent.FORM.REMEMBER_ME}
                    {...register("remember")}
                />
                <Button
                    as="link"
                    href={'/forgot-password'}
                    variant="primary"
                    linkVariant="text"
                    className="text-primary! hover:text-primary-c5!"
                >
                    {staticContent.FORGOT_PASSWORD}
                </Button>
            </div>

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

            <span className="block text-center mt-6 text-grey92">
                {staticContent.FORM.DONT_HAVE_ACCOUNT}{" "}
                <Button as="link" href={ROUTES.REGISTER} linkVariant="text">
                    {staticContent.FORM.SIGN_UP}
                </Button>
            </span>
        </form>
    )
}

export default LoginForm
