import * as React from "react";
import { cn } from "../../../lib/utils";
import { cva, type VariantProps } from "class-variance-authority";
import Image from "next/image";

const inputVariants = cva(
  "rounded-md py-2 pl-1 border  transition border focus-visible:outline-none w-96",
  {
    variants: {
      variant: {
        default: "border-accent",
        primary: "border-accent hover:border-primary focus:ring-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 ValidationProps {
  validation?: {
    pattern?: string | RegExp;
    errorMessage?: string;
  };
}

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

interface InputProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "pattern">,
    VariantProps<typeof inputVariants>,
    ValidationProps,
    IconProps {}

const EmailInput = React.forwardRef<HTMLInputElement, InputProps>(
  (
    { className, type, disable, validation, iconPath, iconClasses, ...props },
    ref
  ) => {
    const [isValid, setIsValid] = React.useState(true);
    const [error, setError] = React.useState("");

    const defaultEmailPattern =
      /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$/;

    const handleValidation = (value: string) => {
      const usedPattern = validation?.pattern || defaultEmailPattern;
      const usedErrorMessage =
        validation?.errorMessage || validation?.errorMessage === ""
          ? validation.errorMessage
          : "Invalid email address";

      if (!value.trim()) {
        setIsValid(true);
        setError("");
      } else {
        const regex =
          usedPattern instanceof RegExp ? usedPattern : new RegExp(usedPattern);
        const isValid = regex.test(value);
        setIsValid(isValid);
        setError(isValid ? "" : usedErrorMessage);
      }
    };

    return (
      <div className="items-center">
        <div
          className={cn(
            "flex items-center",
            inputVariants({ disable, ...props }),
            className
          )}
        >
          <div>
            {iconPath && (
              <Image
                src={iconPath} 
                alt="icon"
                width={20}
                height={20}
                className={cn("mr-1", iconClasses)}
              />
            )}{" "}
          </div>
          <div>
            <input
              type="email"
              className="border-none focus:outline-none"
              ref={ref}
              placeholder="Enter email here..."
              disabled={disable ?? undefined}
              onBlur={(e) => {
                handleValidation(e.target.value);
                if (!isValid && validation?.errorMessage && props.onBlur) {
                  props.onBlur(e);
                }
              }}
              onFocus={(e) => {
                if (!isValid && validation?.errorMessage) {
                  setIsValid(true);
                  setError("");
                }
                if (props.onFocus) {
                  props.onFocus(e);
                }
              }}
              {...props}
            />
          </div>
        </div>

        <div className="text-error mt-1 ml-2 text-sm font-medium">
          {!isValid && error ? error : "\u00a0"}
        </div>
      </div>
    );
  }
);

EmailInput.displayName = "Input";
export { EmailInput };
