"use client";
import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Grid from "@mui/material/Grid";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useCallback, useState } from "react";
import { PasswordInputs } from "@/app/api/user/actions";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import {
  FormHelperText,
  IconButton,
  InputAdornment,
  createTheme,
} from "@mui/material";
import { ThemeProvider } from "../../../node_modules/@mui/system/index";
import { PW_RULE_THEME as defaultTheme } from "@/theme/colorConst";
import Check from "@mui/icons-material/Check";
import Clear from "@mui/icons-material/Clear";
import { PasswordRulesProps } from "./ChangePassword";

const ChagnePasswordForm: React.FC<PasswordRulesProps> = ({ pwRules:rules }) => {
  const { t } = useTranslation("changePassword");
  const [showNewPassword, setShowNewPassword] = useState(false);
  const handleClickShowNewPassword = () => setShowNewPassword(!showNewPassword);
  const handleMouseDownNewPassword = () => setShowNewPassword(!showNewPassword);

  const [showPassword, setShowPassword] = useState(false);
  const handleClickShowPassword = () => setShowPassword(!showPassword);
  const handleMouseDownPassword = () => setShowPassword(!showPassword);

  const [helperTextColors, setHelperTextColors] = useState<string[]>([
    "red",
    "green",
    "blue",
  ]);
  const [inputValue, setInputValue] = useState("");
  const [theme, setTheme] =
    useState<ReturnType<typeof createTheme>>(defaultTheme);
  const pwlengthString = `${rules.min || 0}-${rules.max || " "} characters` 
  let msgList = [
    pwlengthString,
  ]
  switch (true) {
    case rules.upperEng:
      msgList.push("Uppercase letters")
    case rules.lowerEng:
      msgList.push("Lowercase letters")
    case rules.number:
      msgList.push("Numbers")
    case rules.specialChar:
      msgList.push("Symbols")
    default:
      break
  }
  const {
    register,
    formState: { errors, defaultValues },
    control,
    reset,
    resetField,
    setValue,
    setError
  } = useFormContext<PasswordInputs>();

  const getColorFromInput = (
    inputValue: string,
    helperTextLines: string[]
  ): string[] => {
    // Determine the color for each line based on the input value
    return helperTextLines.map((_, index) => {
      if ((index === 0 && inputValue.length < rules.min) || inputValue.length > rules.max) {
        // testing length
        return "red";
      } else if (index === 1 && rules.upperEng &&!/[A-Z]/.test(inputValue)) {
        //testing for uppercase letters
        return "red";
      } else if (index === 2 && rules.lowerEng && !/[a-z]/.test(inputValue)) {
        //testing for lowercase letters
        return "red";
      } else if (index === 3 && rules.number && !/[0-9]/.test(inputValue)) {
        //testing for numbers
        return "red";
      } else if (index === 4 && rules.specialChar && !/[-!@#$%^&=+_*(),.?":{}|<>]/.test(inputValue)) {
        //testing for special characters
        return "red";
      } else {
        return "green";
      }
    });
  };
  
  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    // Update the theme with the new color based on the input value
    const newInputValue = event.target.value;
    setInputValue(newInputValue);
    const newTheme = createTheme({
      ...theme,
      components: {
        MuiFormHelperText: {
          styleOverrides: {
            root: {
              color: getColorFromInput(newInputValue, msgList),
              fontFamily: "Roboto",
              "& .icon": {
                alignItems: "center",
                AlignHorizontalCenter: "center",
                marginRight: "4px",
                fontSize: "1rem", // Adjust the font size as needed
              },
            },
          },
        },
      },
    });
    setTheme(newTheme);
  };

  return (
    <Card sx={{ display: "block" }}>
      <CardContent component={Stack} spacing={4}>
        <Box>
          <Typography variant="overline" display="block" marginBlockEnd={1}>
            {t("Please Fill in All Fields")}
          </Typography>
          <Grid container spacing={2} columns={{ xs: 6, sm: 12 }}>
            <Grid item xs={6}>
              <TextField
                label={t("Input Old Password")}
                fullWidth
                type={showPassword ? "text" : "password"}
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton
                        aria-label="toggle password visibility"
                        onClick={handleClickShowPassword}
                        onMouseDown={handleMouseDownPassword}
                      >
                        {showPassword ? <Visibility /> : <VisibilityOff />}
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
                {...register("password", {
                  required: true,
                })}
                error={Boolean(errors.password)}
                helperText={
                  Boolean(errors.password) &&
                  (errors.password?.message
                    ? t(errors.password.message)
                    : t("Please input correct password"))
                }
              />
            </Grid>
            <Grid item xs={6} />
            <Grid item xs={6}>
              <ThemeProvider theme={theme}>
                <TextField
                  label={t("Input New Password")}
                  fullWidth
                  type={showNewPassword ? "text" : "password"}
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          aria-label="toggle password visibility"
                          onClick={handleClickShowNewPassword}
                          onMouseDown={handleMouseDownNewPassword}
                        >
                          {showNewPassword ? <Visibility /> : <VisibilityOff />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                  {...register("newPassword")}
                  onChange={handleInputChange}
                  error={Boolean(errors.newPassword)}
                  // error={Boolean(errors.newPassword)}
                  helperText={msgList}
                  FormHelperTextProps={{
                    component: (props) => {
                      return (
                        <FormHelperText {...props}>
                          {(props.children as string[]).map((line, index) => (
                            <span
                              key={index}
                              style={{
                                color: getColorFromInput(inputValue, msgList)[
                                  index
                                ],
                              }}
                            >
                              {getColorFromInput(inputValue, msgList)[index] ===
                              "red" ? (
                                <Clear className="icon" />
                              ) : (
                                <Check className="icon" color="success" />
                              )}
                              {line}
                              {index <
                                (props.children as string[]).length - 1 && (
                                <br />
                              )}
                            </span>
                          )
                          )}
                        </FormHelperText>
                      );
                    },
                  }}
                  // (Boolean(errors.newPassword) &&
                  // (errors.newPassword?.message
                  //   ? t(errors.newPassword.message)
                  //   : t("Please input correct newPassword")))
                />
              </ThemeProvider>
            </Grid>
            <Grid item xs={6}>
              <TextField
                label={t("Input New Password Again")}
                fullWidth
                type={showNewPassword ? "text" : "password"}
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton
                        aria-label="toggle password visibility"
                        onClick={handleClickShowNewPassword}
                        onMouseDown={handleMouseDownNewPassword}
                      >
                        {showNewPassword ? <Visibility /> : <VisibilityOff />}
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
                {...register("newPasswordCheck")}
                error={Boolean(errors.newPassword)}
                helperText={
                  Boolean(errors.newPassword) &&
                  (errors.newPassword?.message
                    ? t(errors.newPassword.message)
                    : t("Please input correct newPassword"))
                }
              />
            </Grid>
          </Grid>
        </Box>
      </CardContent>
    </Card>
  );
};
export default ChagnePasswordForm;
