"use client";
import { useRouter, useSearchParams } from "next/navigation";
import React, {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useState,
} from "react";
// 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 {
  UserInputs,
  adminChangePassword,
  fetchUserDetails,
  createUser,
} from "@/app/api/user/actions";
import UserDetail from "./UserDetail";
import { UserResult, passwordRule } from "@/app/api/user";
import { auth } from "@/app/api/group/actions";
import AuthAllocation from "./AuthAllocation";

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

const CreateUser: React.FC<Props> =  ({ rules, auths }) => {
  console.log(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((e?: React.MouseEvent<HTMLButtonElement>) => {
    e?.preventDefault();
    e?.stopPropagation();
    console.log("triggerred");
    console.log(addAuthIds);
    try {
      formProps.reset({
        username: "",
        name: "",
        staffNo: "",
        addAuthIds: addAuthIds,
        removeAuthIds: [],
        password: "",
      });
      console.log(formProps.formState.defaultValues);
    } catch (error) {
      console.log(error);
      setServerError(t("An error has occurred. Please try again later."));
    }
  }, [formProps, addAuthIds, t]);

  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;
        const 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: UserInputs = {
          username: data.username,
          name: data.name ?? "",
          staffNo: data.staffNo,
          locked: false,
          addAuthIds: data.addAuthIds || [],
          removeAuthIds: data.removeAuthIds || [],
          password: pw,
        };
        const pwData = {
          id: id,
          password: pw,
          newPassword: "",
        };
        if (haveError) {
          return;
        }
        console.log("passed");
        console.log(userData);
        await createUser(userData);
        // if (data.password && data.password.length > 0) {
        //   await adminChangePassword(pwData);
        // }
        router.replace("/settings/user");
      } 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={(e) => {
            e.preventDefault();
            e.stopPropagation();
            resetForm(e);
          }}
          type="button"
        >
          {t("Reset")}
        </Button>
        <Button
          variant="outlined"
          startIcon={<Close />}
          onClick={handleCancel}
          type="button"
        >
          {t("Cancel")}
        </Button>
            <Button variant="contained" startIcon={<Check />} type="submit">
              {t("Confirm")}
            </Button>
          </Stack>
        </Stack>
      </FormProvider>
    </>
  );
};
export default CreateUser;
