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

const iconInputVariants = cva("border p-2 w-96 flex flex-row rounded-xl", {
  variants: {
    variant: {
      default: "border-primary",
      outline: "border-accent",
      none: "border-none",
    },
  },
  defaultVariants: {
    variant: "default",
  },
});

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

interface IconInputProps
  extends React.InputHTMLAttributes<HTMLInputElement>,
    VariantProps<typeof iconInputVariants> {
  icon: React.ReactElement;
  validation?: Validation;
}

const IconInput = React.forwardRef<HTMLInputElement, IconInputProps>(
  ({ className, variant, icon, validation, ...props }, ref) => {
    const [error, setError] = React.useState<string | null>(null);

    const validateInput = (value: string) => {
      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>
        <div className={cn(iconInputVariants({ variant, className }))}>
          {icon && <span className={cn()}>{React.cloneElement(icon)}</span>}
          <input
            ref={ref}
            {...props}
            onChange={handleChange}
            className={`border-none focus:outline-none ml-2 ${
              error ? "border-red-500" : ""
            }`}
          />
        </div>
         <div className="text-error mt-1 ml-2 text-sm font-medium">
          { error ? error : "\u00a0"}
        </div>
      </div>
    );
  }
);

IconInput.displayName = "IconInput";

export { IconInput, iconInputVariants };
