import React, { useState } from "react";
import { motion } from "framer-motion";
import { AlertCircle } from "lucide-react";
import { cn } from "@/lib/utils";

interface AuthInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  icon?: React.ElementType;
  label: string;
  error?: string;
  rightElement?: React.ReactNode;
  className?: string;
  containerClassName?: string;
}

const AuthInput = React.forwardRef<HTMLInputElement, AuthInputProps>(
  (
    {
      icon: Icon,
      label,
      error,
      rightElement,
      className,
      containerClassName,
      ...props
    },
    ref
  ) => {
    const [isFocused, setIsFocused] = useState<boolean>(false);

    return (
      <div className={cn("space-y-1.5", containerClassName)}>
        <label className="text-sm font-semibold text-gray-700 dark:text-gray-300 ml-1">
          {label}
        </label>

        <div
          className={cn(
            "relative flex items-center transition-all duration-200 border rounded-xl overflow-hidden bg-white dark:bg-gray-900",
            error
              ? "border-red-300 focus-within:border-red-500 focus-within:ring-4 focus-within:ring-red-100"
              : isFocused
              ? "border-[#338660] ring-4 ring-[#338660]/10 shadow-sm"
              : "border-gray-200 dark:border-gray-800 hover:border-gray-300 dark:hover:border-gray-700"
          )}
        >
          {Icon && (
            <div className="pl-4 pr-2 text-gray-400">
              <Icon className="w-5 h-5" />
            </div>
          )}

          <input
            ref={ref}
            className={cn(
              "w-full py-3 pr-4 bg-transparent border-none focus:ring-0 text-gray-900 dark:text-white placeholder-gray-400 text-base",
              !Icon && "pl-4",
              className
            )}
            onFocus={() => setIsFocused(true)}
            onBlur={() => setIsFocused(false)}
            {...props}
          />

          {rightElement && (
            <div className="pr-4 pl-2">
              {rightElement}
            </div>
          )}
        </div>

        {error && (
          <motion.p
            initial={{ opacity: 0, y: -5 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-xs text-red-500 font-medium ml-1 flex items-center gap-1"
          >
            <AlertCircle className="w-3 h-3" />
            {error}
          </motion.p>
        )}
      </div>
    );
  }
);

AuthInput.displayName = "AuthInput";

export default AuthInput;
