"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useLayoutEffect, useMemo, useState } from "react";
import SearchResults, { Column } from "../SearchResults";
// import { TeamResult } from "@/app/api/team";
import { useTranslation } from "react-i18next";
import {
  Button,
  Card,
  CardContent,
  Grid,
  Stack,
  Tab,
  Tabs,
  TabsProps,
  TextField,
  Typography,
} from "@mui/material";
import {
  FieldErrors,
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
  useFormContext,
} from "react-hook-form";
import { Check, Close, Error, RestartAlt } from "@mui/icons-material";
import { StaffResult } from "@/app/api/staff";
import { UserInputs, editUser, fetchUserDetails } from "@/app/api/user/actions";
import UserDetail from "./UserDetail";
import { UserResult } from "@/app/api/user";
import { auth, fetchAuth } from "@/app/api/group/actions";
import AuthAllocation from "./AuthAllocation";

interface Props {
  // users: UserResult[]
}

const EditUser: React.FC<Props> = async ({ }) => {
  const { t } = useTranslation();
  const formProps = useForm<UserInputs>();
  const searchParams = useSearchParams();
  const id = parseInt(searchParams.get("id") || "0");
  const [tabIndex, setTabIndex] = useState(0);
  const router = useRouter();
  const [serverError, setServerError] = useState("");
  const [data, setData] = useState<UserResult>();
  const [auths, setAuths] = useState<auth[]>();

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

  const errors = formProps.formState.errors;

  const fetchUserDetail = async () => {
    console.log(id);
    try {
      // fetch user info
      const userDetail = await fetchUserDetails(id);
      console.log(userDetail);
      const _data = userDetail.data as UserResult;
      console.log(_data);
      setData(_data);
      //fetch user auths
      const authDetail = await fetchAuth("user", id);
      setAuths(authDetail.records)
      const addAuthIds = authDetail.records.filter((item) => item.v === 1).map((item) => item.id).sort((a, b) => a - b);

      formProps.reset({
        name: _data.username,
        email: _data.email,
        addAuthIds: addAuthIds || []
      });
    } catch (error) {
      console.log(error);
      setServerError(t("An error has occurred. Please try again later."));
    }
  }

  useEffect(() => {
    fetchUserDetail();
  }, []);

  // useEffect(() => {
    // const thisUser = users.filter((item) => item.id === id)
    // formProps.reset({
    //   username: thisUser[0].username,
    //   email: thisUser[0].email,
    // });
  // }, []);

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

  const handleCancel = () => {
    router.back();
  };

  const onSubmit = useCallback<SubmitHandler<UserInputs>>(
    async (data) => {
      try {
        console.log(data);
        const tempData = {
          name: data.name,
          email: data.email,
          locked: false,
          addAuthIds: data.addAuthIds || [],
          removeAuthIds: data.removeAuthIds || [],
        }
        console.log(tempData);
        await editUser(id, tempData);
        router.replace("/settings/staff");
      } catch (e) {
        console.log(e);
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router]
  );
  const onSubmitError = useCallback<SubmitErrorHandler<UserInputs>>(
    (errors) => {
      console.log(errors);
    },
    []
  );

  return (
    <>
      {serverError && (
        <Typography variant="body2" color="error" alignSelf="flex-end">
          {serverError}
        </Typography>
      )}
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
        >
          <Stack
            direction="row"
            justifyContent="space-between"
            flexWrap="wrap"
            rowGap={2}
          >
            <Tabs
              value={tabIndex}
              onChange={handleTabChange}
              variant="scrollable"
            >
              <Tab
                label={t("User Detail")}
                icon={
                  hasErrorsInTab(0, errors) ? (
                    <Error sx={{ marginInlineEnd: 1 }} color="error" />
                  ) : undefined
                }
                iconPosition="end"
              />
              <Tab label={t("User Authority")} iconPosition="end" />
            </Tabs>
          </Stack>
          {tabIndex == 0 && <UserDetail data={data!} />}
          {tabIndex === 1 && <AuthAllocation auths={auths!}/>}
          <Stack direction="row" justifyContent="flex-end" gap={1}>
            <Button
              variant="text"
              startIcon={<RestartAlt />}
              // onClick={() => console.log("asdasd")}
            >
              {t("Reset")}
            </Button>
            <Button
              variant="outlined"
              startIcon={<Close />}
              onClick={handleCancel}
            >
              {t("Cancel")}
            </Button>
            <Button variant="contained" startIcon={<Check />} type="submit">
              {t("Confirm")}
            </Button>
          </Stack>
        </Stack>
      </FormProvider>
    </>
  );
};
export default EditUser;
