import * as React from "react";
import { View, TextInput, type TextInputProps } from "react-native";
import { cn } from "~/lib/utils";

interface InputProps extends TextInputProps {
  containerClassName?: string;
  borderClassName?: string;
  placeholderText?: string;
  placeholderClassName?: string;
  placeholderColor?: string;
  textClassName?: string;
  leftIcon?: React.ReactNode;
  rightIcon?: React.ReactNode;
}

const Input = React.forwardRef<React.ElementRef<typeof TextInput>, InputProps>(
  (
    {
      containerClassName,
      borderClassName,
      className,
      placeholderText,
      placeholderClassName,
      placeholderColor,
      textClassName,
      leftIcon,
      rightIcon,
      placeholder,
      ...props
    },
    ref
  ) => {
    const resolvedPlaceholder = placeholder ?? placeholderText;

    // If no container / icons are provided, fall back to a simple input
    if (!leftIcon && !rightIcon && !containerClassName && !borderClassName) {
      return (
        <TextInput
          ref={ref}
          className={cn(
            "h-10 native:h-12 rounded-xl border border-input bg-background px-3 text-base lg:text-sm native:text-lg native:leading-[1.25] placeholder:text-muted-foreground file:border-0 file:bg-transparent file:font-medium",
            props.editable === false && "opacity-50",
            textClassName,
            className
          )}
          placeholder={resolvedPlaceholder}
          placeholderClassName={cn(
            "text-muted-foreground",
            placeholderClassName
          )}
          placeholderTextColor={placeholderColor}
          {...props}
        />
      );
    }

    // Enhanced layout: rounded container with optional left/right icons (search-bar style)
    return (
      <View className={cn("flex-row items-center", containerClassName)}>
        <View
          className={cn(
            "flex-row items-center rounded-[8px] border border-[#E5E7F0] bg-white px-4 h-10 native:h-12 flex-1",
            borderClassName
          )}
        >
          {leftIcon ? <View className="mr-2">{leftIcon}</View> : null}

          <TextInput
            ref={ref}
            {...props}
            placeholder={resolvedPlaceholder}
            className={cn(
              "flex-1 text-sm native:text-sm lg:text-sm native:leading-[1.25]",
              props.editable === false && "opacity-50",
              textClassName,
              className
            )}
            placeholderClassName={cn(
              "text-muted-foreground",
              placeholderClassName
            )}
            placeholderTextColor={placeholderColor}
          />
        </View>

        {rightIcon ? (
          <View className="ml-3 w-10 h-10 native:h-12 native:w-12 rounded-[8px] border border-[#D9DBE9] bg-white items-center justify-center">
            {rightIcon}
          </View>
        ) : null}
      </View>
    );
  }
);

Input.displayName = "Input";

export { Input };
