import React, { useState } from "react";
import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";

interface InputProps
    extends Omit<
        React.InputHTMLAttributes<HTMLInputElement | HTMLTextAreaElement>,
        "type"
    > {
    type?:
    | "text"
    | "textarea"
    | "password"
    | "email"
    | "number"
    | "tel"
    | "url"
    | "search"
    | "date"
    | "time"
    | "datetime-local";
    rows?: number;
    error?: string;
}

export function Input({
    type = "text",
    rows = 4,
    className,
    value = "",
    onChange,
    error,
    ...restProps
}: InputProps) {
    const [isFocused, setIsFocused] = useState(false);

    const inputClasses = `
    w-full rounded-lg border bg-white px-4 py-2 outline-none
    transition-all duration-200 ease-out placeholder:text-tertiary-400
    ${error
            ? "border-red-500 focus:border-red-500 focus:ring-2 focus:ring-red-200"
            : "border-gray-200 hover:border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-100"
        }
    ${isFocused ? "ring-2 ring-opacity-50" : ""}
    ${className || ""}
  `;

    const InputElement = type === "textarea" ? "textarea" : "input";

    return (
        <div className="relative">
            <InputElement
                value={value}
                onChange={onChange}
                type={type !== "textarea" ? type : undefined}
                rows={type === "textarea" ? rows : undefined}
                {...restProps}
                onFocus={() => setIsFocused(true)}
                onBlur={(e) => {
                    setIsFocused(false);
                    restProps.onBlur?.(e);
                }}
                className={inputClasses}
            />
            <div className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center space-x-2">
                {value && isFocused && (
                    <button
                        type="button"
                        className="p-1.5 rounded-full text-tertiary-400 hover:text-gray-600 hover:bg-gray-100 transition-all duration-200 ease-out"
                        onMouseDown={(e) => e.preventDefault()}
                        onClick={() => onChange?.({ target: { value: "" } } as any)}
                        tabIndex={-1}
                    >
                        <XMarkIcon className="w-4 h-4" />
                    </button>
                )}
                {value && !error && (
                    <CheckIcon className="text-green-500 w-4 h-4 animate-fade-in duration-200" />
                )}
            </div>
        </div>
    );
}