"use client";

import React, { useState, forwardRef, useImperativeHandle } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { signInValidationSchema } from "@/utils/form";
import { login } from "@/app/(auth)/actions";
import { ModalStatus, SignInForm, TextOnUse } from "@/types";
import { useRouter } from "next/navigation";
export interface FormRefMethods {
  resetForm: () => void;
}

interface ModalSignInFormProps {
  textOnUse: TextOnUse;
  setStatus: React.Dispatch<React.SetStateAction<ModalStatus>>;
}

const ModalSignInForm = forwardRef<FormRefMethods, ModalSignInFormProps>(
  ({ textOnUse, setStatus }: ModalSignInFormProps, ref) => {
    // const context = useContext(Context);
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [organisation, setOrganisation] = useState("");
    const router = useRouter();

    const {
      register,
      handleSubmit,
      reset,
      setError,
      clearErrors,
      formState: { errors },
    } = useForm({
      resolver: yupResolver(signInValidationSchema),
    });

    const submitForm = async (data: SignInForm) => {
      console.log("data", data);
      clearErrors();
      setEmail(data.email);
      setPassword(!data.password ? "" : data.password);
      setStatus(ModalStatus.Loading);
      if (!data.password) return;
      let response = undefined;
      try {
        console.log("before login");
        response = await login({ email: data.email, password: data.password });
        if (!response.success) {
          throw new Error(response.error);
        }
        const signInModal = document.getElementById("sign-in-modal");
        if (!!signInModal) signInModal.click();
        router.push("/account");
      } catch (error) {
        setStatus(ModalStatus.Default);
        console.log(error);
        setError("email", { type: "custom", message: "Invalid Credentials" });
      }
    };
    useImperativeHandle(ref, () => ({
      resetForm: () => {
        reset();
        setEmail("");
        setPassword("");
        setOrganisation("");
      },
    }));
    return (
      <form onSubmit={handleSubmit(submitForm)} className="w-full md:w-1/2">
        <div className="relative mt-3">
          <input
            {...register("email")}
            id="SignInEmail"
            type="text"
            className="w-full appearance-none bg-transparent border rounded-sm px-4 mr-2 text-black placeholder-black border-black  dark:placeholder-white dark:border-white"
            placeholder="Your email…"
            aria-label="Your email…"
            autoComplete="on"
          />
          <label
            htmlFor="SignInEmail"
            className="md:absolute top-[50%] translate-y-[-50%] left-[105%] w-[220px] text-red-400"
          >
            {errors.email ? "*" + errors.email.message : ""}
          </label>
        </div>
        <div className="relative mt-1 mb-4">
          <input
            {...register("password")}
            id="SignInPwd"
            type="password"
            className="w-full appearance-none bg-transparent border rounded-sm px-4 mr-2 text-black placeholder-black border-black  dark:placeholder-white dark:border-white"
            placeholder="Your password..."
            aria-label="Your password..."
          />
          <label
            htmlFor="SignInPwd"
            className="md:absolute top-[50%] translate-y-[-50%] left-[105%] w-[220px] text-red-400"
          >
            {errors.password ? "*" + errors.password.message : ""}
          </label>
        </div>

        <button
          type="submit"
          className="btn capitalize font-bold text-black bg-base-100 hover:bg-base-100 shadow"
        >
          {textOnUse.buttonText}
        </button>
      </form>
    );
  }
);
ModalSignInForm.displayName = "ModalSignInForm";

export default ModalSignInForm;
