"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 { 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";

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

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

export interface comboItem {
  company: comboProp[];
  team: comboProp[];
  department: comboProp[];
  position: comboProp[];
  grade: comboProp[];
  skill: comboProp[];
  salary: comboProp[];
}

const CreateStaff: React.FC<formProps> = ({ Title }) => {
  // const router = useRouter();
  const { t } = useTranslation();
  const [companyCombo, setCompanyCombo] = useState<comboProp[]>();
  const [teamCombo, setTeamCombo] = useState<comboProp[]>();
  const [departmentCombo, setDepartmentCombo] = useState<comboProp[]>();
  const [positionCombo, setPositionCombo] = useState<comboProp[]>();
  const [gradeCombo, setGradeCombo] = useState<comboProp[]>();
  const [skillCombo, setSkillCombo] = useState<comboProp[]>();
  const [salaryCombo, setSalaryCombo] = useState<comboProp[]>();
  // const [serverError, setServerError] = useState("");

  let comboItem: comboItem = {
    company: [],
    team: [],
    department: [],
    position: [],
    grade: [],
    skill: [],
    salary: [],
  };

  const fetchCompany = async () => {
    await fetchCompanyCombo().then((data) => {
      if (data) setCompanyCombo(data.records);
    });
  }

  const fetchTeam = async () => {
    await fetchTeamCombo().then((data) => {
      if (data) setTeamCombo(data.records);
    });
  }

  const fetchDepartment = async () => {
    await fetchDepartmentCombo().then((data) => {
      if (data) setDepartmentCombo(data.records);
    });
  }

  const fetchPosition = async () => {
    await fetchPositionCombo().then((data) => {
      if (data) setPositionCombo(data.records);
    });
  }

  const fetchGrade = async () => {
    await fetchGradeCombo().then((data) => {
      if (data) setGradeCombo(data.records);
    });
  }

  const fetchSkill = async () => {
    await fetchSkillCombo().then((data) => {
      if (data) setSkillCombo(data.records);
    });
  }

  const fetchSalary = async () => {
    await fetchSalaryCombo().then((data) => {
      if (data) setSalaryCombo(data.records);
    });
  }

  useEffect(() => {
    fetchCompany()
    fetchTeam()
    fetchDepartment()
    fetchPosition()
    fetchGrade()
    fetchSkill()
    fetchSalary()
  }, []);

  useEffect(() => {
    if(!companyCombo)
        fetchCompany()
    if(!teamCombo)
        fetchTeam()
    if(!departmentCombo)
        fetchDepartment()
    if(!positionCombo)
        fetchPosition()
    if(!gradeCombo)
        fetchGrade()
    if(!skillCombo)
        fetchSkill()
    if(!salaryCombo)
        fetchSalary()

  }, [companyCombo, teamCombo, departmentCombo, positionCombo, gradeCombo, skillCombo, salaryCombo]);

  // useEffect(() => {
  //   console.log(companyCombo)
  // }, [companyCombo]);

  const fieldLists: Field[][] = [
    [
      {
        id: "staffId",
        label: t("Staff ID"),
        type: "text",
        required: true,
      },
      {
        id: "name",
        label: t("Staff Name"),
        type: "text",
        required: true,
      },
      {
        id: "companyId",
        label: t("Company"),
        type: "combo-Obj",
        options: companyCombo || [],
        required: true,
      },
      {
        id: "teamId",
        label: t("Team"),
        type: "combo-Obj",
        options: teamCombo || [],
        required: false,
      },
      {
        id: "departmentId",
        label: t("Department"),
        type: "combo-Obj",
        options: departmentCombo || [],
        required: true,
      },
      {
        id: "gradeId",
        label: t("Grade"),
        type: "combo-Obj",
        options: gradeCombo || [],
        required: false,
      },
      {
        id: "skillSetId",
        label: t("Skillset"),
        type: "combo-Obj",
        options: skillCombo || [],
        required: false,
      },
      {
        id: "currentPositionId",
        label: t("Current Position"),
        type: "combo-Obj",
        options: positionCombo || [],
        required: true,
      },
      {
        id: "salaryId",
        label: t("Salary Point"),
        type: "combo-Obj",
        options: salaryCombo || [],
        required: true,
      },
      // {
      //   id: "hourlyRate",
      //   label: t("Hourly Rate"),
      //   type: "numeric-testing",
      //   value: "",
      //   required: false,
      // },      
      {
        id: "hourlyRate",
        label: t("Hourly Rate"),
        type: "numeric-testing",
        required: true,
      },      
      {
        id: "employType",
        label: t("Employ Type"),
        type: "combo-Obj",
        options: [{id: "FT", label: t("FT")}, {id: "PT", label: t("PT")}],
        value: "",
        required: true,
      },
      {
        id: "email",
        label: t("Email"),
        type: "text",
        pattern: "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$",
        message: t("input matching format"),
        required: true,
      },
      {
        id: "phone1",
        label: t("Phone1"),
        type: "text",
        pattern: "^\\d{8}$",
        message: t("input correct phone no."),
        required: true,
      },
      {
        id: "phone2",
        label: t("Phone2"),
        type: "text",
        pattern: "^\\d{8}$",
        message: t("input correct phone no."),
        required: false,
      },      
    ],
    [
      {
        id: "emergContactName",
        label: t("Emergency Contact Name"),
        type: "text",
        required: true,
      },
      {
        id: "emergContactPhone",
        label: t("Emergency Contact Phone"),
        type: "text",
        pattern: "^\\d{8}$",
        message: t("input correct phone no."),
        required: true,
      },
      {
        id: "joinDate",
        label: t("Join Date"),
        type: "multiDate",
        required: true,
      },
      {
        id: "joinPositionId",
        label: t("Join Position"),
        type: "combo-Obj",
        options: positionCombo || [],
        required: true,
      },
      {
        id: "departDate",
        label: t("Depart Date"),
        type: "multiDate",
      },
      {
        id: "departReason",
        label: t("Depart Reason"),
        type: "text",
      },
      {
        id: "remark",
        label: t("Remark"),
        type: "remarks",
      },
    ]
  ];
  return (
    <>
      <CreateStaffForm Title={Title} fieldLists={fieldLists}/>
    </>
  );
};

export default CreateStaff;