"use client";
import { PasswordInputs, changePassword } from "@/app/api/user/actions";
import { Grid } from "@mui/material";
import { useRouter } from "next/navigation";
import { useCallback, useState } from "react";
import { FormProvider, SubmitErrorHandler, 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 ChagnePasswordForm from "./ChangePasswordForm";
import { passwordRule } from "@/app/api/user";

export interface PasswordRulesProps {
    pwRules: passwordRule
}

const ChangePassword: React.FC<PasswordRulesProps> = ({
  pwRules
}) => {
  const formProps = useForm<PasswordInputs>();
  const [serverError, setServerError] = useState("");
  const router = useRouter();
  //   const [tabIndex, setTabIndex] = useState(0);
  const { t } = useTranslation();

  const onSubmit = useCallback<SubmitHandler<PasswordInputs>>(
    async (data) => {
      try {
        let haveError = false;
        // Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:
        let regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&-=+_*(),.?":{}|<>])[A-Za-z\d@$!%*?&-=+_*(),.?":{}|<>]{8,}$/

        if (data.newPassword.length < 8 || data.newPassword.length > 20) {
            haveError = true
            formProps.setError("newPassword", { type: "required" })
            // formProps.setError("newPassword", { message: "The password requires 8-20 characters", type: "required" })
        }
        if (!regex.test(data.newPassword)) {
            haveError = true
            formProps.setError("newPassword", { type: "required" })
            // formProps.setError("newPassword", { message: "A combination of uppercase letters, lowercase letters, numbers, and symbols is required.", type: "required" })
        }
        if (data.password == data.newPassword) {
            haveError = true
            formProps.setError("newPassword", { type: "required" })
            // formProps.setError("newPassword", { message: "The new password cannot be the same as the old password", type: "required" })
        }
        if (data.newPassword != data.newPasswordCheck) {
            haveError = true
            formProps.setError("newPassword", { type: "required" })
            // formProps.setError("newPassword", { message: "The new password has to be the same as the new password", type: "required" })
            formProps.setError("newPasswordCheck", { message: "The new password has to be the same as the new password", type: "required" })
        }
        if (haveError) {
            return
        }
        const postData = {
            password: data.password,
            newPassword: data.newPassword
        }
        await changePassword(postData)
        router.replace("/home")
      } catch (e) {
        console.log(e)
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router]
  );

  const handleCancel = () => {
    router.push(`/home`);
  };

  const onSubmitError = useCallback<SubmitErrorHandler<PasswordInputs>>(
    (errors) => {
      console.log(errors);
    },
    []
  );

  return (
    <FormProvider {...formProps}>
      <Stack
        spacing={2}
        component="form"
        onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
      >
        <ChagnePasswordForm pwRules={pwRules}/>
        <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 ChangePassword;
