"use client";
import { useCallback, useEffect, 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, testing } from "@/app/api/staff/actions";
import { Button, Stack, Typography } from "@mui/material";
// import CreateStaffForm from "../CreateStaffForm";
import { comboProp, fetchCompanyCombo } from "@/app/api/companys/actions";
import { fetchTeamCombo } from "@/app/api/team/actions";
import { fetchDepartmentCombo } from "@/app/api/departments/actions";
import { fetchPositionCombo } from "@/app/api/positions/actions";
import { fetchGradeCombo } from "@/app/api/grades/actions";
import { fetchSkillCombo } from "@/app/api/skill/actions";
import { fetchSalaryCombo } from "@/app/api/salarys/actions";
import StaffInfo from "./StaffInfo";
import { Check, Close } from "@mui/icons-material";
import { ServerFetchError } from "@/app/utils/fetchUtil";

interface Field {
  id: string;
  label: string;
  type: string;
  value?: any;
  required?: boolean;
  pattern?: string;
  message?: string;
  options?: any[];
  readOnly?: boolean;
}
export interface comboItem {
  company: comboProp[];
  team: comboProp[];
  department: comboProp[];
  position: comboProp[];
  grade: comboProp[];
  skill: comboProp[];
  salary: comboProp[];
}

interface formProps {
  // Title?: string[];
  combos: comboItem;
}


const CreateStaff: React.FC<formProps> = ({ combos }) => {
  const { t } = useTranslation();
  const formProps = useForm<CreateStaffInputs>();
  const [serverError, setServerError] = useState("");
  const router = useRouter();
  const [tabIndex, setTabIndex] = useState(0);

  const errors = formProps.formState.errors;

  const checkDuplicates = (str1: string, str2: string, str3: string) => {
    return str1 === str2 || str1 === str3 || str2 === str3;
  }

  const onSubmit = useCallback<SubmitHandler<CreateStaffInputs>>(
    async (data) => {
      try {
        console.log(data);
        let haveError = false;
        let regex_email = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/
        let regex_phone = /^\d{8}$/

        if (!regex_email.test(data.email)) {
          haveError = true
          formProps.setError("email", { message: t("Please Enter Correct Email."), type: "required" })
        }
        if(!regex_phone.test(data.phone1)) {
          haveError = true
          formProps.setError("phone1", { message: t("Please Enter Correct Phone No.."), type: "required" })
        }
        if(data.emergContactPhone && !regex_phone.test(data.emergContactPhone)) {
          haveError = true
          formProps.setError("emergContactPhone", { message: t("Please Enter Correct Phone No.."), type: "required" })
        }
        if (data.phone2 && data.phone2?.length > 0) {
          if(!regex_phone.test(data.phone2)) {
            haveError = true
            formProps.setError("phone2", { message: t("Please Enter Correct Phone No.."), type: "required" })
          }
        }
        if (data.phone1 === data.phone2 || data.phone1 === data.emergContactPhone || data.phone2 === data.emergContactPhone) {
          haveError = true
          formProps.setError("phone1", { message: t("Please Enter Different Phone No.."), type: "required" })
          if (data.phone2!.length > 0) {
            formProps.setError("phone2", { message: t("Please Enter Different Phone No.."), type: "required" })
          }
          formProps.setError("emergContactPhone", { message: t("Please Enter Different Phone No.."), type: "required" })
        }
        if (!regex_email.test(data.email)) {
          haveError = true
          formProps.setError("email", { message: t("Please Enter Correct Email."), type: "required" })
        }
        if (!data.companyId) {
          haveError = true
          formProps.setError("companyId", { message: t("Please Enter Company."), type: "required" })
        }
        if (!data.employType) {
          haveError = true
          formProps.setError("employType", { message: t("Please Enter Employ Type."), type: "required" })
        }
        if (!data.salaryId) {
          haveError = true
          formProps.setError("salaryId", { message: t("Please Enter Salary."), type: "required" })
        }
        if (data.joinDate &&data.departDate && new Date(data.departDate) <= new Date(data.joinDate)) {
          haveError = true
          formProps.setError("departDate", { message: t("Depart Date cannot be earlier than Join Date."), type: "required" })
        }
        if (haveError) {
          return
        }
        console.log("passed")
        await saveStaff(data)
        router.replace("/settings/staff")
      } catch (e: any) {
        console.log(e);
        formProps.setError("staffId", { message: t("Please Enter Employ Type."), type: "required" })
        let msg = ""
        if (e.message === "Duplicated StaffId Found") {
          msg = t("Duplicated StaffId Found")
        }
        setServerError(`${t("An error has occurred. Please try again later.")} ${msg} `);
      }
    },
    [router]
  );
  
  const handleCancel = () => {
    router.back();
  };

  return (
    <>
      <FormProvider {...formProps}>
      <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit)}
        >
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          <StaffInfo combos={combos}/>
          <Stack direction="row" justifyContent="flex-end" gap={1}>
            <Button
              variant="outlined"
              startIcon={<Close />}
              onClick={handleCancel}
            >
              {t("Cancel")}
            </Button>
            <Button
              variant="contained"
              startIcon={<Check />}
              type="submit"
              // disabled={Boolean(formProps.watch("isGridEditing"))}
            >
              {t("Confirm")}
            </Button>
          </Stack>
        </Stack>
      </FormProvider>
    </>
  );
};

export default CreateStaff;