"use client";

import { CreateGroupInputs, auth, saveGroup } from "@/app/api/group/actions";
import { useRouter } from "next/navigation";
import { useCallback, useState } from "react";
import { FieldErrors, FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { Button, Stack, Tab, Tabs, TabsProps, Typography } from "@mui/material";
import { Check, Close, Error } from "@mui/icons-material";
import GroupInfo from "./GroupInfo";
import AuthorityAllocation from "./AuthorityAllocation";
import UserAllocation from "./UserAllocation";
import { UserResult } from "@/app/api/user";

interface Props {
    auth?: auth[]
    users?: UserResult[]
}

const CreateGroup: React.FC<Props> = ({ auth, users }) => {
  const formProps = useForm<CreateGroupInputs>();
  const [serverError, setServerError] = useState("");
  const router = useRouter();
  const [tabIndex, setTabIndex] = useState(0);
  const { t } = useTranslation();

  const errors = formProps.formState.errors;

  const onSubmit = useCallback<SubmitHandler<CreateGroupInputs>>(
    async (data) => {
      try {
        console.log(data);
        const postData = {
          ...data,
          removeUserIds: [],
          removeAuthIds: [],

        }
        console.log(postData)
        await saveGroup(postData)
        router.replace("/settings/group")
      } 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<CreateGroupInputs>,
  ) => {
    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("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>
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          {tabIndex === 0 && <GroupInfo/>}
          {tabIndex === 1 && <AuthorityAllocation auth={auth!!}/>}
          {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 CreateGroup;
