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

const inputVariants = 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",
    },
  }
);

export interface Validation {
  pattern: RegExp;
  errorMessage: string;
}

export interface InputProps
  extends React.InputHTMLAttributes<HTMLInputElement>,
    VariantProps<typeof inputVariants> {
  validation?: Validation;
}

const Input = React.forwardRef<HTMLInputElement, InputProps>(
  ({ className, type, disable, validation, ...props }, ref) => {
    const [error, setError] = React.useState<string | null>(null);

    const validateInput = (value: string) => {
      // Check for white spaces or empty input
      if (!value.trim()) {
        setError(null);
        return true;
      }

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

      setError(null);
      return true;
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;
      validateInput(value);
    };

    return (
      <div>
        <input
          type={type}
          className={cn(" ", inputVariants({ disable, ...props }), className)}
          ref={ref}
          disabled={disable ?? undefined}
          onChange={handleChange}
          {...props}
        />
        <div className="text-error mt-1 ml-2 text-sm font-medium">
          { error ? error : "\u00a0"}
        </div>
      </div>
    );
  }
);

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