"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { 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 } from "@mui/icons-material";
import { StaffResult } from "@/app/api/staff";
import { CreateGroupInputs, auth, fetchAuth, saveGroup } from "@/app/api/group/actions";
import { UserGroupResult } from "@/app/api/group";
import { UserResult } from "@/app/api/user";
import GroupInfo from "./GroupInfo";
import AuthorityAllocation from "./AuthorityAllocation";
import UserAllocation from "./UserAllocation";
interface Props {
  groups: UserGroupResult[];
//   auths: auth[];
  users: UserResult[];
}

const EditUserGroup: React.FC<Props> = ({ groups, users }) => {
    // console.log(users)
  const { t } = useTranslation();
  const [serverError, setServerError] = useState("");
  const formProps = useForm<CreateGroupInputs>();
  const searchParams = useSearchParams();
  const id = parseInt(searchParams.get("id") || "0");
  const router = useRouter();
  const [tabIndex, setTabIndex] = useState(0);
  const [auths, setAuths] = useState<auth[]>();

  const errors = formProps.formState.errors;

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

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

  const onSubmit = useCallback<SubmitHandler<CreateGroupInputs>>(
    async (data) => {
      try {
        console.log(data);
        const tempData = {
            ...data,
            removeUserIds: data.removeUserIds ?? [],
            removeAuthIds: data.removeAuthIds ?? [],
            id: id
        }
        console.log(tempData)
        await saveGroup(tempData);
        router.replace("/settings/group");
      } catch (e) {
        console.log(e);
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router]
  );
  useEffect(() => {
    const thisGroup = groups.filter((item) => item.id === id)[0];
    const addUserIds = users.filter((item) => item.groupId === id).map((data) => data.id)
    let addAuthIds: number[] = []
    fetchAuth("group", id).then((data) => {
        setAuths(data.records)
        addAuthIds = data.records.filter((data) => data.v === 1).map((data) => data.id).sort((a, b) => a - b);
        formProps.reset({
          name: thisGroup.name,
          description: thisGroup.description,
          addAuthIds: addAuthIds,
          addUserIds: addUserIds,
        });
    });
    // console.log(auths)
  }, [groups, users]);

  return (
    <>
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit)}
        >
          <Typography variant="h4" marginInlineEnd={2}>
            {t("Edit User Group")}
          </Typography>
          <Stack
            direction="row"
            justifyContent="space-between"
            flexWrap="wrap"
            rowGap={2}
          >
            <Tabs
              value={tabIndex}
              onChange={handleTabChange}
              variant="scrollable"
            >
              <Tab
                label={t("Group Info")}
                icon={
                  hasErrorsInTab(0, errors) ? (
                    <Error sx={{ marginInlineEnd: 1 }} color="error" />
                  ) : undefined
                }
                iconPosition="end"
              />
              <Tab label={t("Authority Allocation")} iconPosition="end" />
              <Tab label={t("User Allocation")} iconPosition="end" />
            </Tabs>
          </Stack>
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          {tabIndex === 0 && <GroupInfo />}
          {tabIndex === 1 && <AuthorityAllocation auth={auths!!}/>}
          {tabIndex === 2 && <UserAllocation users={users!!} />}
          <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 EditUserGroup;
