"use client";
import { useTranslations } from "next-intl";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";

import { FormItem, FormWrapper } from "@/components/ui/form";
import { useEffect, useState } from "react";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import { doForgotPassword } from "@/lib/redux/features/auth";
import AppInput from "@/components/ui/input/input";

import { ForgotPasswordResponse } from "@/types/auth";
import { ResponseStatus } from "@/types/common";
import Link from "next/link";
import InputField from "../../ui/input/input-field";
import { USER_CONFIG } from "@/lib/appConstant";
import { useRouter, useSearchParams } from "next/navigation";
import { getServicePath } from "@/lib/redux/features/serviceAdmin";
import { LogIn } from "lucide-react";
import AppButton from "../../ui/button/app-button";

export type ForgotPasswordFormProps = {
  setIsSuccess?: (data: boolean) => void;
};

export default function ForgotPasswordForm(props: any) {
  // const { location } = props;
  const dispatch = useAppDispatch();
  const t = useTranslations("");
  const router = useRouter();
  
  const [isLoading, setIsLoading] = useState(false);

  const searchParam = useSearchParams();

  const servicePath = useAppSelector(getServicePath);

  const formSchema = z.object({
    email: z
      .string()
      .trim()
      .min(1, { message: t("validate.required") })
      .max(255, { message: t('validate.max_length_255')})
      .email({
        message: t("validate.email.invalid"),
      }),
  });

  type ForgotPasswordFormSchema = z.infer<typeof formSchema>;

  const forgotPasswordForm = useForm<ForgotPasswordFormSchema>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: "",
    },
  });

  async function onSubmit(values: ForgotPasswordFormSchema) {
    try {
      setIsLoading(true);
      const request = {
        email: values.email,
        loginType: USER_CONFIG.USER.loginType
      };

      const response = await dispatch(doForgotPassword(request));
      const payload = response.payload as ForgotPasswordResponse;
      if (payload && payload.status === ResponseStatus.SUCCESS) {
        router.push(`${servicePath ? '/'+servicePath : ''}/login`)
      }
    } catch (error) {
      console.error("Login error:", error);
    } finally {
      setIsLoading(false);
    }
  }

  // useEffect(() => {
  //   // Handle keydown enter to submit form
  //   const keyDownHandler = (event) => {
  //     if (event.key === "Enter") {
  //       event.preventDefault();
  //       forgotPasswordForm.handleSubmit(onSubmit)();
  //     }
  //   };

  //   document.addEventListener("keydown", keyDownHandler);

  //   return () => {
  //     document.removeEventListener("keydown", keyDownHandler);
  //   };
  // }, [forgotPasswordForm]);

  const emailParams = searchParam.get('email');
  const sentParams = searchParam.get('sent');

  return (
    <FormWrapper<ForgotPasswordFormSchema>
      form={forgotPasswordForm}
      onSubmit={onSubmit}
      layout="vertical"
      className="space-y-4"
    >
      <div>
        {
          emailParams && sentParams
          ? (
            <p>
              { t('text.resetPasswordMessage', { email: emailParams.replaceAll(' ', '+') })}
            </p>
          )
          : (
            <div>
              <div className="">
                <FormItem name="email" label={t('label.email_address')}>
                  {({ value, ...field }) => (
                    <InputField  {...field} placeholder={t('label.email_address')} />
                  )}
                </FormItem>
              </div>
              <div className="text-right">
                <AppButton
                  type="submit"
                  // loading={isLoading}
                  className="btn btn-info mr-1 w-full"
                >
                  {t("button.resetPassword")}
                </AppButton>
                <div className="dropdown-divider" />
                <div className="flex justify-center mb-3 text-[14px] w-full ">
                  <Link href={`${servicePath ? '/'+servicePath : ''}/login`} className="flex items-center">
                     <LogIn className="text-center mr-1" strokeWidth={'3px'} size={16}/>
                     {t('menu.login')}
                  </Link>
                </div>
              </div>
            </div>
          )
        }
      </div>
    </FormWrapper>
  );
}
