"use client";

import {
  FieldErrors,
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import StaffAllocation from "./StaffAllocation";
import { StaffResult } from "@/app/api/staff";
import { CreateTeamInputs, saveTeam } from "@/app/api/team/actions";
import { Button, Stack, Tab, Tabs, TabsProps, Typography } from "@mui/material";
import { Check, Close } from "@mui/icons-material";
import { useCallback, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import { Error } from "@mui/icons-material";
import TeamInfo from "./TeamInfo";

export interface Props {
  allstaff: StaffResult[];
}

const CreateTeam: React.FC<Props> = ({ allstaff }) => {
  const formProps = useForm<CreateTeamInputs>();
  const [serverError, setServerError] = useState("");
  const router = useRouter();
  const [tabIndex, setTabIndex] = useState(0);
  const { t } = useTranslation();
  const searchParams = useSearchParams()

  const errors = formProps.formState.errors;

  const onSubmit = useCallback<SubmitHandler<CreateTeamInputs>>(
    async (data) => {
      try {
        console.log(data);
        await saveTeam(data);
        router.replace("/settings/team");
      } 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<CreateTeamInputs>,
) => {
  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("Team Info")}
              icon={
                hasErrorsInTab(0, errors) ? (
                  <Error sx={{ marginInlineEnd: 1 }} color="error" />
                ) : undefined
              }
              iconPosition="end"
            />
            <Tab label={t("Staff Allocation")} iconPosition="end" />
          </Tabs>
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          {tabIndex === 0 && <TeamInfo/>}
          {tabIndex === 1 && <StaffAllocation allStaffs={allstaff} />}

          {/* <StaffAllocation allStaffs={allstaff} /> */}
          <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"
              // disabled={Boolean(formProps.watch("isGridEditing"))}
            >
              {t("Confirm")}
            </Button>
          </Stack>
        </Stack>
      </FormProvider>
    </>
  );
};

export default CreateTeam;
