"use client";

import Check from "@mui/icons-material/Check";
import Close from "@mui/icons-material/Close";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import Tab from "@mui/material/Tab";
import Tabs, { TabsProps } from "@mui/material/Tabs";
import { useRouter } from "next/navigation";
import React, { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { Task, TaskTemplate } from "@/app/api/tasks";
import {
  FieldErrors,
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { CreatePositionInputs, savePosition } from "@/app/api/positions/actions";
import { Error } from "@mui/icons-material";
import { ProjectCategory } from "@/app/api/projects";
import { Typography } from "@mui/material";
import PositionDetails from "./PositionDetails";


const CreatePosition: React.FC = ({
  // allTasks,
  // projectCategories,
  // taskTemplates,
  // teamLeads,
}) => {
  const [serverError, setServerError] = useState("");
  const { t } = useTranslation();
  const router = useRouter();

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

  const onSubmit = useCallback<SubmitHandler<CreatePositionInputs>>(
    async (data) => {
      try {
        console.log(data);
        setServerError("");
        // console.log(JSON.stringify(data));
        await savePosition(data)
        router.replace("/settings/position");
      } catch (e) {
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router, t],
  );

  const onSubmitError = useCallback<SubmitErrorHandler<CreatePositionInputs>>(
    (errors) => {
      console.log(errors)
    },
    [],
  );

  const formProps = useForm<CreatePositionInputs>({
    defaultValues: {
      positionCode: "",
      positionName: "",
      description: "",
    },
  });

  const errors = formProps.formState.errors;

  return (
    <FormProvider {...formProps}>
      <Stack
        spacing={2}
        component="form"
        onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
      >
        {
          <PositionDetails />
        }

        <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">
            {t("Confirm")}
          </Button>
        </Stack>
      </Stack>
    </FormProvider>
  );
};

export default CreatePosition;
