"use client";
import { useCallback, useEffect, useState } from "react";
import CustomInputForm from "../CustomInputForm";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
  FormProvider,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { CreateStaffInputs, saveStaff, testing } from "@/app/api/staff/actions";
import { Button, Stack, Typography } from "@mui/material";
import { comboProp } from "@/app/api/companys/actions";
import StaffInfo from "./StaffInfo";
import { Check, Close } from "@mui/icons-material";
import dayjs from "dayjs";
import { SalaryEffectiveInfo } from "@/app/api/staff";

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>({
    defaultValues: {
      teamHistory: []
    }
  });
  const [serverError, setServerError] = useState("");
  const router = useRouter();
  // const [tabIndex, setTabIndex] = useState(0);

  const errors = formProps.formState.errors;

  function chopSalaryPoints(input: string | number): number | null {
    if (typeof input === 'string') {
      const match = input.match(/(\d+) \((\d+) - (\d+)\)/);
      if (match) {
        return parseInt(match[1], 10);
      }
    } else if (typeof input === 'number') {
      return input;
    }
    return null;
  }

  const onSubmit = useCallback<SubmitHandler<CreateStaffInputs>>(
    async (data) => {
      // try {
        console.log(data);
        formProps.clearErrors()
        let haveError = false;
        const regex_email = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/
        const 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.phone2 === data.emergContactPhone && data.phone2.length > 0) {
          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.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 (!data.salaryEffectiveInfo || data.salaryEffectiveInfo.length < 1) {
          haveError = true
          formProps.setError("salaryId", { message: t("Please Enter Salary"), type: "required" })
        }        
        if (!data.gradeHistory || data.gradeHistory.length < 1) {
          haveError = true
          formProps.setError("gradeId", { message: t("Please Enter Grade"), type: "required" })
        }
        if (!data.positionHistory || data.positionHistory.length < 1) {
          console.log("asdadsasd")
          haveError = true
          formProps.setError("currentPositionId", { message: t("Please Enter Current Position"), type: "required" })
        }
        console.log(data.teamHistory)
        console.log(haveError)
        if (haveError) {
          return
        }
        const teamHistory = data.teamHistory.length !== 0 ? data.teamHistory
        .map((item) => ({
          id: item.id,
          team: combos.team.filter(team => team.label === item.team)[0].id,
          from: dayjs(item.from).format('YYYY-MM-DD'),
        }))
        .sort((a, b) => new Date(a.from).getTime() - new Date(b.from).getTime()) : []
        
        const gradeHistory = data.gradeHistory
        .map((item) => ({
          id: item.id,
          grade: combos.grade.filter(grade => grade.label === item.grade)[0].id,
          from: dayjs(item.from).format('YYYY-MM-DD'),
        }))
        .sort((a, b) => new Date(a.from).getTime() - new Date(b.from).getTime())
        
        console.log(data.positionHistory)
        const positionHistory = data.positionHistory
          .map((item) => ({
            id: item.id,
            position: combos.position.filter(position => position.label === item.position)[0].id,
            from: dayjs(item.from).format('YYYY-MM-DD'),
          }))
          .sort((a, b) => new Date(a.from).getTime() - new Date(b.from).getTime())
        
        const salaryEffectiveInfo = data.salaryEffectiveInfo.map((item: SalaryEffectiveInfo) => ({
          id: item.id,
          salaryPoint: chopSalaryPoints(item.salaryPoint),
          date: dayjs(item.date).format('YYYY-MM-DD').toString()
        })) // backend sort
        const postData: CreateStaffInputs = {
          // id: id,
          ...data,
          salaryEffectiveInfo: salaryEffectiveInfo,
          teamHistory: teamHistory,
          gradeHistory: gradeHistory ?? [],
          positionHistory: positionHistory ?? [],
          delTeamHistory: data.delTeamHistory ? data.delTeamHistory : [],
          delGradeHistory: data.delGradeHistory ? data.delGradeHistory : [],
          delPositionHistory: data.delPositionHistory ? data.delPositionHistory : [],
        }
        console.log("passed")
        console.log(postData)
        // return
        const res = await saveStaff(postData)
        console.log(res)
        if (!res.id) {
          setServerError(res.message!!);
          // formProps.setError(res.errorPosition as keyof CreateStaffInputs, {
          //   message: res.message!!,
          //   type: "required",
          // });
          return
        } 
        router.replace("/settings/staff")
      // } catch (e: any) {
      //   console.log(e);
      //   setServerError(`An error has occurred. Please try again later.`);
      // }
    },
    [router]
  );
  
  
  const errorKey = Object.keys(formProps.formState.errors)[0]
  const err = errors[errorKey as keyof CreateStaffInputs]

  const handleCancel = useCallback(() => {
    router.back();
  }, [router]);

  return (
    <>
      <FormProvider {...formProps}>
      <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit)}
        >
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          {err && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {err.message?.toString()}
            </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;