"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, useLayoutEffect, useEffect } 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 { EditPositionInputs, editPosition, fetchPositionDetails, 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";
import { useSearchParams } from 'next/navigation'
import { PositionResult } from "@/app/api/positions";


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

  const [positionDetails, setPositionDetails] = useState<EditPositionInputs>()
  const positionId = searchParams.get("id")

  const fetchPositionDetail = async () =>{
    console.log(positionId)
    try{
      if (positionId !== null && parseInt(positionId) > 0) {
        const postionDetails = await fetchPositionDetails(parseInt(positionId))
        const updatedArray: EditPositionInputs[] = postionDetails.map((obj) => {
          return { 
            id: obj.id, 
            positionCode: obj.code, 
            positionName: obj.name, 
            description: obj.description 
          };
        });

        setPositionDetails(updatedArray[0])
      }
    } catch (error){
      console.log(error)
      setServerError(t("An error has occurred. Please try again later."));
    } 
  }

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

  const onSubmit = useCallback<SubmitHandler<EditPositionInputs>>(
    async (data) => {
      try {
        if (positionId !== null && parseInt(positionId) > 0) {
          console.log(data);
          setServerError("");
          // console.log(JSON.stringify(data));
          data.id = parseInt(positionId)
          console.log(data);
          await editPosition(data)
          router.replace("/settings/position");
        }
      } catch (e) {
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router, t],
  );

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

  const formProps = useForm<EditPositionInputs>({
    // defaultValues: {
    //   positionCode: positionDetails ? positionDetails.code : "AAA",
    //   positionName: positionDetails ? positionDetails.name : "BBB",
    //   description: positionDetails ? positionDetails.description : "CCC",
    // },
  });

  const errors = formProps.formState.errors;

  useEffect(() => {
    fetchPositionDetail()
  }, [])

  useEffect(() => {
    if (positionDetails !== null && positionDetails !== undefined) {
      console.log(positionDetails)
      
      formProps.reset(positionDetails)
    }
  }, [positionDetails])

  return (
    <FormProvider {...formProps}>
      <Stack
        spacing={2}
        component="form"
        onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
      >
        {
          positionDetails && <PositionDetails positionDetails={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 EditPosition;
