"use client";

import {
  FieldErrors,
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { Button, Stack, Tab, Tabs, TabsProps, Typography } from "@mui/material";
import { Check, Close, RestartAlt } from "@mui/icons-material";
import { useCallback, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import { CreateSkillInputs, saveSkill } from "@/app/api/skill/actions";
import { Error } from "@mui/icons-material";
import SkillInfo from "./SkillInfo";
import { SkillResult } from "@/app/api/skill";

interface Props {
  skill: SkillResult[]
}

const CreateSkill: React.FC<Props> = ({
  skill
}) => {
  const codeList = skill.map(s => s.code.toLowerCase().trim())
  console.log(codeList)
  const formProps = useForm<CreateSkillInputs>();
  const [serverError, setServerError] = useState("");
  const router = useRouter();
  const { t } = useTranslation();
  // const [tabIndex, setTabIndex] = useState(0);
  const errors = formProps.formState.errors;

  const onSubmit = useCallback<SubmitHandler<CreateSkillInputs>>(
    async (data) => {
      try {
        let haveError = false
        haveError = codeList.includes(data.code.toLowerCase().trim())
        if (haveError) {
          formProps.setError("code", { message: t("Duplicated Code"), type: "required" })
          return 
        }
        data.name = data.name.trim()
        data.code = data.code.trim()
        data.description = data.description.trim()
        await saveSkill(data)
        router.replace(`/settings/skill`)
      } catch (e) {
        console.log(e);
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router]
  );

  const handleCancel = () => {
    router.back();
  };

  const resetSkill = useCallback(() => {
    formProps.reset()
}, [])

  // const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
  //   (_e, newValue) => {
  //     setTabIndex(newValue);
  //   },
  //   []
  // );

  // const hasErrorsInTab = (
  //   tabIndex: number,
  //   errors: FieldErrors<CreateSkillInputs>
  // ) => {
  //   switch (tabIndex) {
  //     case 0:
  //       return Object.keys(errors).length > 0;
  //     default:
  //       false;
  //   }
  // };
  return (
    <>
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit)}
        >
          {/* <Tabs
            value={tabIndex}
            onChange={handleTabChange}
            variant="scrollable"
          >
            <Tab
              label={t("Skill Info")}
              icon={
                hasErrorsInTab(0, errors) ? (
                  <Error sx={{ marginInlineEnd: 1 }} color="error" />
                ) : undefined
              }
              iconPosition="end"
            />
          </Tabs> */}
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          {/* {tabIndex === 0 && <SkillInfo />} */}
          <SkillInfo />
          <Stack direction="row" justifyContent="flex-end" gap={1}>
          <Button
              variant="text"
              startIcon={<RestartAlt />}
              onClick={resetSkill}
            >
              {t("Reset")}
            </Button>
            <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 CreateSkill;
