import React, { forwardRef, useState, ChangeEvent } from "react";
import { cn } from "../../../lib/utils";
import { cva, type VariantProps } from "class-variance-authority";
import { FaEye, FaEyeSlash } from "react-icons/fa";
import Image from "next/image"; 

const passwordInputVariants = cva(
  "rounded-md p-2 border  transition border focus-visible:outline-none w-96",
  {
    variants: {
      variant: {
        default: "border-accent",
        primary:
          "border-accent hover:border-primary focus:ring-primary focus:border-primary",
      },
      inputSize: {
        default: "text-base",
        sm: "text-sm",
        lg: "text-lg",
      },
      disable: {
        true: "cursor-not-allowed bg-orange-50 opacity-40",
        false: "",
      },
    },
    defaultVariants: {
      variant: "default",
      inputSize: "default",
    },
  }
);

interface ValidationObject {
  pattern: RegExp;
  errorMessage: string;
}

interface IconProps {
  iconPath?: string;
  iconClasses?: string;
}

interface PasswordInputProps
  extends React.InputHTMLAttributes<HTMLInputElement>,
    VariantProps<typeof passwordInputVariants>,
    IconProps {
  validations?: ValidationObject[];
}

const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
  (
    { className, disable, validations = [], iconPath, iconClasses, ...props },
    ref
  ) => {
    const defaultPattern: RegExp = /^(?=.*[!@#$%^&*(),.?":{}|<>]).{8,}$/;
    const defaultErrorMessage: string = "* Invalid password";

    const [isValid, setIsValid] = useState(true);
    const [error, setError] = useState("");

    const currentValidations =
      validations.length > 0
        ? validations
        : [{ pattern: defaultPattern, errorMessage: defaultErrorMessage }];

    const handleValidation = (value: string) => {
      if (value.trim() === "") {
        setIsValid(true);
        setError("");
        return;
      }

      for (let i = 0; i < currentValidations.length; i++) {
        const { pattern, errorMessage } = currentValidations[i];

        if (!pattern.test(value)) {
          setIsValid(false);
          setError(errorMessage);
          return;
        }
      }

      setIsValid(true);
      setError("");
    };

    const [showPassword, setShowPassword] = useState(false);

    return (
      <div>
        <div
          className={cn(
            "flex flex-row items-center justify-between",
            passwordInputVariants({ disable, ...props }),
            className
          )}
        >
          <div className="flex flex-row items-center">
            {iconPath && (
              <Image
                src={iconPath}
                alt="icon"
                height={20}
                width={20}
                className={cn("mr-1", iconClasses)}
              />
            )}{" "}
            <input
              type={showPassword ? "text" : "password"}
              ref={ref}
              className="border-none focus:outline-none"
              placeholder="Type your password..."
              disabled={disable ?? undefined}
              onChange={(e: ChangeEvent<HTMLInputElement>) =>
                handleValidation(e.target.value)
              }
              {...props}
            />
          </div>

          <div
            className="cursor-pointer ml-2"
            onClick={() => setShowPassword(!showPassword)}
          >
            {showPassword ? <FaEyeSlash /> : <FaEye />}
          </div>
        </div>
        <div className="text-error mt-1 ml-2 text-sm font-medium">
          {!isValid && error ? error : "\u00a0"}
        </div>
      </div>
    );
  }
);

PasswordInput.displayName = "PasswordInput";
export { PasswordInput };
