"use client";
import { useCallback, useState } from "react";
import CustomInputForm from "../CustomInputForm";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
  FieldErrors,
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { CreateStaffInputs, saveStaff } from "@/app/api/staff/actions";
import { Typography } from "@mui/material";

interface Field {
  //   subtitle: string;
  id: string;
  label: string;
  type: string;
  value?: any;
  required?: boolean;
  options?: any[];
  readOnly?: boolean;
}

interface formProps {
  Title?: string[];
  fieldLists: Field[][];
}

const CreateStaffForm: React.FC<formProps> = ({ Title, fieldLists }) => {
  const router = useRouter();
  const { t } = useTranslation();
  const [serverError, setServerError] = useState("");

  const handleCancel = () => {
    router.back();
  };
  const onSubmit = useCallback<SubmitHandler<CreateStaffInputs>>(
    async (data) => {
      try {
        console.log(data);
        let haveError = false;
        //check if joinDate exist
        if (data.joinDate == null && data.joinDate == "Invalid Date") {
          haveError = true;
          return haveError;
        }
        //check if joinDate > departDate
        if (data.departDate != null && data.departDate != "Invalid Date") {
          if (data.joinDate != null) {
            const joinDate = new Date(data.joinDate);
            const departDate = new Date(data.departDate);
            if (joinDate.getTime() > departDate.getTime()) {
              haveError = true;
              return haveError;
            }
          }
        }

        if (haveError) {
          return
        }
        const postData = {
          ...data,
          emergContactPhone: data.emergContactPhone.toString(),
          phone1: data.phone1.toString(),
          phone2: data.phone2.toString(),
          hourlyRate: typeof data.hourlyRate === 'string' ? parseInt(data.hourlyRate.replace("$", "").replace(",", "")) : 0
        };
        console.log(postData);
        setServerError("");
        await saveStaff(postData);
        router.replace("/settings/staff");
      } catch (e) {
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router, t]
  );

  const onSubmitError = useCallback<SubmitErrorHandler<CreateStaffInputs>>(
    (errors) => {
      console.log(errors);
    },
    []
  );

  return (
    <>
      {serverError && (
        <Typography variant="body2" color="error" alignSelf="flex-end">
          {serverError}
        </Typography>
      )}
      <CustomInputForm
        Title={Title}
        fieldLists={fieldLists}
        isActive={true}
        onSubmit={onSubmit}
        onSubmitError={onSubmitError}
        onCancel={handleCancel}
      />
    </>
  );
};

export default CreateStaffForm;
