"use client";
import { useRouter, useSearchParams } from "next/navigation";
import React, {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useState,
} from "react";
import { useTranslation } from "react-i18next";
import {
  Button,
  Stack,
  Typography,
} from "@mui/material";
import {
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { Check, Close, RestartAlt } from "@mui/icons-material";
import {
  UserInputs,
  adminChangePassword,
  editUser,
} from "@/app/api/user/actions";
import UserDetail from "./UserDetail";
import { UserResult, passwordRule } from "@/app/api/user";

interface Props {
  user: UserResult & { authIds?: number[] };
  rules: passwordRule;
}

const EditUser: React.FC<Props> = ({ user, rules }) => {
  console.log(user);
  const { t } = useTranslation("user");
  const formProps = useForm<UserInputs>();
  const searchParams = useSearchParams();
  const id = parseInt(searchParams.get("id") || "0");
  const router = useRouter();
  const [serverError, setServerError] = useState("");

  const resetForm = React.useCallback((e?: React.MouseEvent<HTMLButtonElement>) => {
    e?.preventDefault();
    e?.stopPropagation();
    try {
      formProps.reset({
        username: user.username,
        name: user.name,
        staffNo: user.staffNo?.toString() ?? "",
        addAuthIds: user.authIds ?? [],
        removeAuthIds: [],
        password: "",
      });
      formProps.clearErrors();
    } catch (error) {
      console.log(error);
      setServerError(t("An error has occurred. Please try again later."));
    }
  }, [formProps, user, t]);

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

  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: t(
                "A combination of uppercase letters, lowercase letters, numbers, and symbols is required.",
              ),
              type: "required",
            });
          }
        }
        const userData = {
          username: data.username,
          name: data.name,
          staffNo: data.staffNo,
          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/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)}
        >
          <UserDetail />
          <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 EditUser;