"use client";
import { useRouter, useSearchParams } from "next/navigation";
import React, {
  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,
  adminChangePassword,
  editUser,
  fetchUserDetails,
} from "@/app/api/user/actions";
import UserDetail from "./UserDetail";
import { UserResult, passwordRule } from "@/app/api/user";
import { auth, fetchAuth } from "@/app/api/group/actions";
import AuthAllocation from "./AuthAllocation";

interface Props {
  user: UserResult;
  rules: passwordRule;
  auths: auth[];
}

const EditUser: React.FC<Props> = async ({ user, rules, auths }) => {
  const { t } = useTranslation("user");
  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 addAuthIds =
    auths && auths.length > 0
      ? auths
          .filter((item) => item.v === 1)
          .map((item) => item.id)
          .sort((a, b) => a - b)
      : [];

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

  const errors = formProps.formState.errors;

  const resetForm = React.useCallback(() => {
    console.log("triggerred");
    console.log(addAuthIds);
    try {
      formProps.reset({
        name: user.username,
        email: user.email,
        addAuthIds: addAuthIds,
        removeAuthIds: [],
        password: "",
      });
      console.log(formProps.formState.defaultValues);
    } catch (error) {
      console.log(error);
      setServerError(t("An error has occurred. Please try again later."));
    }
  }, [auths, user]);

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

  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 {
        let haveError = false;
        let regex_pw =
          /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,20}$/;
        let pw = "";
        if (data.password && data.password.length > 0) {
          pw = data.password;
          if (pw.length < rules.min) {
            haveError = true;
            formProps.setError("password", {
              message: t("The password requires 8-20 characters."),
              type: "required",
            });
          }
          if (pw.length > rules.max) {
            haveError = true;
            formProps.setError("password", {
              message: t("The password requires 8-20 characters."),
              type: "required",
            });
          }
          if (!regex_pw.test(pw)) {
            haveError = true;
            formProps.setError("password", {
              message:
                "A combination of uppercase letters, lowercase letters, numbers, and symbols is required.",
              type: "required",
            });
          }
        }
        const userData = {
          name: data.name,
          locked: false,
          addAuthIds: data.addAuthIds || [],
          removeAuthIds: data.removeAuthIds || [],
        };
        const pwData = {
          id: id,
          password: "",
          newPassword: pw,
        };
        if (haveError) {
          return;
        }
        console.log("passed");
        await editUser(id, userData);
        if (data.password && data.password.length > 0) {
          await adminChangePassword(pwData);
        }
        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 />}
          {tabIndex === 1 && <AuthAllocation auths={auths!} />}
          <Stack direction="row" justifyContent="flex-end" gap={1}>
            <Button
              variant="text"
              startIcon={<RestartAlt />}
              onClick={resetForm}
            >
              {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;
