"use client";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import SearchResults, { Column } from "../SearchResults";
// import { TeamResult } from "@/app/api/team";
import { useTranslation } from "react-i18next";
import { Button, Stack, Tab, Tabs, TabsProps, Typography } from "@mui/material";
import { CreateTeamInputs, saveTeam } from "@/app/api/team/actions";
import {
  FieldErrors,
  FormProvider,
  SubmitHandler,
  useForm,
  useFormContext,
} from "react-hook-form";
import { Check, Close, Error, RestartAlt } from "@mui/icons-material";
import TeamInfo from "../EditTeam/TeamInfo";
import Allocation from "./Allocation";
import { StaffResult } from "@/app/api/staff";
import { IndivTeam } from "@/app/api/team";

interface Props {
  staff: StaffResult[];
  teamInfo: IndivTeam;
}

const EditTeam: React.FC<Props> = async ({ staff, teamInfo }) => {
  const { team, staffIds } = teamInfo;
  console.log(team)
  const { t } = useTranslation();
  const formProps = useForm<CreateTeamInputs>();
  const searchParams = useSearchParams();
  const idString = searchParams.get("id");
  const [tabIndex, setTabIndex] = useState(0);
  const router = useRouter();

  const errors = formProps.formState.errors;

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

  const [serverError, setServerError] = useState("");

  const hasErrorsInTab = (
    tabIndex: number,
    errors: FieldErrors<CreateTeamInputs>
  ) => {
    switch (tabIndex) {
      case 0:
        return Object.keys(errors).length > 0;
      default:
        false;
    }
  };

  const onSubmit = useCallback<SubmitHandler<CreateTeamInputs>>(
    async (data) => {
      try {
        // console.log(data);
        const tempData = {
          description: data.description,
          addStaffIds: data.addStaffIds,
          deleteStaffIds: data.deleteStaffIds,
          code: data.code,
          name: data.name,
          id: parseInt(idString!!),
        } as  CreateTeamInputs
        console.log(tempData);
        await saveTeam(tempData);
        router.replace("/settings/team");
      } catch (e) {
        console.log(e);
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router]
  );

  const resetTeam = React.useCallback(() => {
    formProps.reset({
      name: team.name,
      code: team.code,
      description: team.description,
      addStaffIds: staffIds,
      deleteStaffIds: []
    });
  }, []);

  useEffect(() => {
    resetTeam();
  }, [team]);

  return (
    <>
      {serverError && (
        <Typography variant="body2" color="error" alignSelf="flex-end">
          {serverError}
        </Typography>
      )}
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit)}
        >
          <Typography variant="h4" marginInlineEnd={2}>
            {t("Edit Team")} - {team.name}
          </Typography>
          <Stack
            direction="row"
            justifyContent="space-between"
            flexWrap="wrap"
            rowGap={2}
          >
            <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>
          </Stack>
          {tabIndex === 0 && <TeamInfo />}
          {tabIndex === 1 && (
            <Allocation allStaffs={staff} teamLead={team.staff?.id} />
          )}
          <Stack direction="row" justifyContent="flex-end" gap={1}>
            <Button
              variant="text"
              startIcon={<RestartAlt />}
              onClick={resetTeam}
            >
              {t("Reset")}
            </Button>
            <Button
              variant="outlined"
              startIcon={<Close />}
              onClick={() => router.back()}
            >
              {t("Cancel")}
            </Button>
            <Button
              variant="contained"
              startIcon={<Check />}
              type="submit"
              // disabled={Boolean(formProps.watch("isGridEditing"))}
            >
              {t("Confirm")}
            </Button>
          </Stack>
        </Stack>
      </FormProvider>
    </>
  );
};
export default EditTeam;
