"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;
  const { t } = useTranslation();
  const formProps = useForm<CreateTeamInputs>();
  const searchParams = useSearchParams();
  const idString = searchParams.get("id");
  // const [allStaffs, setAllStaffs] = useState<StaffResult[]>();
  // const [teamLead, setTeamLead] = useState<number>();
  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("");

  // useEffect(() => {
  //   let idList: number[] = [];
  //   // console.log(desc)
  //   if (idString) {
  //     const filteredTeam = staff.filter((item) => {
  //       return item.teamId === parseInt(idString);
  //     });
  //     setTeamLead(team.teamLead);
  //     if (filteredTeam.length > 0) {
  //       const filteredIds: number[] = filteredTeam.map((i) => i.id);

  //       // const teamLead = tempDesc[0].teamLead
  //       // const index = filteredIds.indexOf(teamLead);

  //       // if (index !== -1) {
  //       //   filteredIds.splice(index, 1);
  //       //   filteredIds.unshift(teamLead);
  //       // }

  //       idList = filteredIds;
  //     }
  //     formProps.reset({ description: team.description, addStaffIds: idList });
  //   }
  //   // console.log(staff)

  //   setAllStaffs(staff);
  // }, [searchParams]);

  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,
          id: parseInt(idString!!),
        };
        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.teamLead} />
          )}
          <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;
