import { Ionicons } from "@expo/vector-icons";
import { useState } from "react";
import { Control, Controller, FieldError, FieldValues, Path, RegisterOptions } from "react-hook-form";
import { Platform, Pressable, Text, TextInput, View } from "react-native";

type InputGroupProps<T extends FieldValues> = {
  control: Control<T>;
  label: string;
  name: Path<T>;
  error?: FieldError;
  backendError?: string | null;
  keyboardType?: "default" | "email-address" | "numeric" | "phone-pad";
  secureTextEntry?: boolean;
  multiline?: boolean;
  placeholder?: string;
  numberOfLines?: number;
  rules?: RegisterOptions<T, Path<T>>;
};

export default function InputGroup<T extends FieldValues>({
  control,
  label,
  name,
  error,
  backendError,
  keyboardType = "default",
  secureTextEntry = false,
  multiline = false,
  placeholder,
  numberOfLines,
  rules,
}: InputGroupProps<T>) {
  const [showPassword, setShowPassword] = useState(secureTextEntry);
  return (
    <View className="">
      <Text className="text-lg font-manrope-semibold pb-2 text-slate-900">{label}</Text>
      <Controller
        control={control}
        rules={{
          ...rules,
          required: rules?.required === false ? false : rules?.required || `${label} is required`,
        }}
        render={({ field: { onChange, onBlur, value } }) => (
          <View
            className={`flex-row justify-between items-center rounded-xl border bg-white px-5 text-lg outline-none  ${
              error || backendError ? "border-red-500" : "border-slate-200"
            } ${Platform.OS === "ios" ? "py-3" : "py-px"}`}
          >
            <TextInput
              placeholder={placeholder || label}
              onBlur={onBlur}
              onChangeText={onChange}
              value={value}
              keyboardType={keyboardType}
              className={`flex-1 ${secureTextEntry ? "pr-4 " : ""} placeholder:text-slate-400 text-slate-700 ${multiline ? "min-h-[120px] pt-4" : ""}`}
              style={{ fontSize: 18, lineHeight: 24 }}
              secureTextEntry={showPassword}
              multiline={multiline}
              numberOfLines={numberOfLines || (multiline ? 4 : 1)}
              textAlignVertical={multiline ? "top" : "center"}
            />

            {secureTextEntry && (
              <Pressable onPress={() => setShowPassword(!showPassword)} className="justify-center">
                <Ionicons name={showPassword ? "eye-off-outline" : "eye-outline"} size={20} color="#14141466" />
              </Pressable>
            )}
          </View>
        )}
        name={name}
      />
      {error && <Text className="text-red-500 text-sm">{error?.message || `${label} is required.`}</Text>}
      {backendError && <Text className="text-red-500 text-sm">{backendError}</Text>}
    </View>
  );
}
