import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "../lib/cn";

const inputVariants = cva(
  "flex h-10 w-full rounded-md border bg-transparent px-3 py-2 text-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-ctp-subtext0 focus-visible:outline-none focus-visible:ring-2 disabled:cursor-not-allowed disabled:opacity-50",
  {
    variants: {
      state: {
        default: "border-ctp-surface1 focus-visible:ring-ctp-blue",
        success: "border-ctp-green focus-visible:ring-ctp-green",
        error: "border-ctp-red focus-visible:ring-ctp-red",
      },
    },
    defaultVariants: {
      state: "default",
    },
  },
);

interface TextInputProps
  extends Omit<VariantProps<typeof inputVariants>, "state"> {
  label?: string;
  placeholder?: string;
  value?: string;
  onChange?: (value: string) => void;
  disabled?: boolean;
  error?: string;
  state?: "default" | "success" | "error";
  type?:
    | "text"
    | "email"
    | "password"
    | "number"
    | "tel"
    | "url"
    | "date"
    | "datetime-local";
  className?: string;
  id?: string;
  required?: boolean;
  autoComplete?: string;
  minLength?: number;
  pattern?: string;
}

export const TextInput = ({
  label,
  placeholder,
  value,
  onChange,
  disabled = false,
  error,
  state = "default",
  type = "text",
  className = "",
  id,
  required = false,
  autoComplete,
  minLength,
  pattern,
}: TextInputProps) => {
  const inputId =
    id || (label ? label.toLowerCase().replace(/\s+/g, "-") : undefined);
  const inputState = error ? "error" : state;

  return (
    <div className="space-y-1">
      {label && (
        <label htmlFor={inputId} className="text-sm font-medium text-ctp-text">
          {label}
        </label>
      )}
      <input
        id={inputId}
        type={type}
        placeholder={placeholder}
        value={value}
        onChange={(e) => onChange?.(e.target.value)}
        disabled={disabled}
        required={required}
        autoComplete={autoComplete}
        minLength={minLength}
        pattern={pattern}
        className={cn(inputVariants({ state: inputState }), className)}
      />
      {error && <p className="text-sm text-ctp-red">{error}</p>}
    </div>
  );
};
