"use client";
import { SkillResult } from "@/app/api/skill";
import {
  Button,
  Card,
  CardContent,
  Grid,
  Stack,
  Tab,
  Tabs,
  TabsProps,
  TextField,
  Typography,
} from "@mui/material";
import {
  FieldErrors,
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
  useFormContext,
} from "react-hook-form";
import React, { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useRouter, useSearchParams } from "next/navigation";
import { Check, Close, Error, RestartAlt } from "@mui/icons-material";
import EditSkillForm from "./EditSkillForm";
import { CreateSkillInputs, saveSkill } from "@/app/api/skill/actions";
import AuthAllocation from "../EditUser/AuthAllocation";

interface Props {
  skills: SkillResult[];
  skillList: SkillResult[];
}

const EditSkill: React.FC<Props> = async ({ 
  skills,
  skillList
}) => {
  const codeList = skillList.map(s => s.code.toLowerCase().trim()).filter(code => code !== skills[0].code.toLowerCase().trim())
  const { t } = useTranslation();
  const formProps = useForm<CreateSkillInputs>();
  const [serverError, setServerError] = useState("");
  const router = useRouter();
  const searchParams = useSearchParams();
  const id = parseInt(searchParams.get("id") || "0");
  // const [tabIndex, setTabIndex] = useState(0);
  // const [filteredSkill, setFilteredSkill] = useState<SkillResult>(
  //   () => skills.filter((s) => s.id === id)[0] as SkillResult
  // );
  const errors = formProps.formState.errors;

  const onSubmit = useCallback<SubmitHandler<CreateSkillInputs>>(
    async (data) => {
      try {
        console.log(data);
        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()
        const postData = {
          ...data,
          id: id,
        };
        await saveSkill(postData);
        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 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;
  //   }
  // };
  const resetSkill = React.useCallback(() => {
    formProps.reset({
      name: skills[0].name,
      code: skills[0].code,
      description: skills[0].description,
    });
  }, []);
  
  useEffect(() => {
    console.log(skills)
    resetSkill()
  }, [skills]);

  return (
    <>
      {serverError && (
        <Typography variant="body2" color="error" alignSelf="flex-end">
          {serverError}
        </Typography>
      )}
      <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> */}
          {/* {tabIndex === 0 && <EditSkillForm />} */}
          <EditSkillForm />
          <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">
              {t("Confirm")}
            </Button>
          </Stack>
        </Stack>
      </FormProvider>
    </>
  );
};
export default EditSkill;
