"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 { StaffResult } from "@/app/api/staff";
import { CreateGroupInputs, auth, fetchAuth, saveGroup } from "@/app/api/group/actions";
import { IndivUserGroup, 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[];
  group: IndivUserGroup
}

const EditUserGroup: React.FC<Props> = ({ users, auths, group }) => {
  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 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]
  );

  const resetGroup = React.useCallback(() => {
    formProps.reset({
      name: group.data.name,
      description: group.data.description,
      addAuthIds: group.authIds,
      addUserIds: group.userIds,
    })
  }, [group, users]);

  useEffect(() => {
    resetGroup()
  }, []);
  // }, [group, 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="text"
              startIcon={<RestartAlt />}
              onClick={resetGroup}
            >
              {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 EditUserGroup;
