import React, { useState, useCallback, useRef } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  FlatList,
  Modal,
  Animated,
  Dimensions,
  StyleSheet,
  TextInput,
} from "react-native";
import R from "../../assets/R";
import { WIDTH, HEIGHT, getFontSize } from "../../config/Functions";

const DropdownItem = ({
  item,
  isSelected,
  onSelect,
  buildItemStyles,
  buildItemTextStyles,
  itemStyle,
  itemTextStyle,
  labelKey,
}) => {
  const [isItemPressed, setIsItemPressed] = useState(false);

  return (
    <TouchableOpacity
      style={[buildItemStyles(item, isSelected, isItemPressed), itemStyle]}
      onPress={() => onSelect(item)}
      onPressIn={() => setIsItemPressed(true)}
      onPressOut={() => setIsItemPressed(false)}
      activeOpacity={0.7}
    >
      <Text
        style={[
          buildItemTextStyles(item, isSelected, isItemPressed),
          itemTextStyle,
        ]}
      >
        {item[labelKey]}
      </Text>
    </TouchableOpacity>
  );
};

const DropdownSelect = ({
  title,
  titleStyle,
  titleRequiredStyle,

  data = [],
  value,
  onSelect,
  placeholder = "Select an option",
  searchable = false,
  searchPlaceholder = "Search...",

  titleColor, // Màu chữ title
  titleFontSize, // Kích thước font title
  titleFontWeight, // Độ đậm font title (normal, bold, 100-900)
  titleFontFamily, // Font family title
  titleFontStyle, // Font style title (normal, italic)
  titleTextAlign, // Text align title (left, center, right)
  titleLineHeight, // Line height title
  titleLetterSpacing, // Letter spacing title
  titleTextTransform, // Text transform (none, uppercase, lowercase, capitalize)
  titleTextDecorationLine, // Text decoration (none, underline, line-through)
  titleTextDecorationColor, // Màu decoration
  titleTextDecorationStyle, // Style decoration (solid, double, dotted, dashed)

  // TITLE: Title spacing props
  titleMarginBottom, // Margin bottom của title
  titleMarginTop, // Margin top của title
  titleMarginLeft, // Margin left của title
  titleMarginRight, // Margin right của title
  titleMarginHorizontal, // Margin horizontal của title
  titleMarginVertical, // Margin vertical của title
  titlePaddingBottom, // Padding bottom của title
  titlePaddingTop, // Padding top của title
  titlePaddingLeft, // Padding left của title
  titlePaddingRight, // Padding right của title
  titlePaddingHorizontal, // Padding horizontal của title
  titlePaddingVertical, // Padding vertical của title

  // TITLE: Required symbol styling props
  requiredSymbolColor, // Màu ký tự * required
  requiredSymbolFontSize, // Kích thước font ký tự *
  requiredSymbolFontWeight, // Độ đậm font ký tự *
  requiredSymbolFontFamily, // Font family ký tự *
  requiredSymbolText,

  labelKey = "label",
  valueKey = "value",
  renderItem,
  renderSelectedItem,
  keyExtractor,

  width,
  height,
  paddingHorizontal,
  paddingVertical,
  paddingTop,
  paddingBottom,
  paddingLeft,
  paddingRight,
  margin,
  marginHorizontal,
  marginVertical,
  marginTop,
  marginBottom,
  marginLeft,
  marginRight,

  backgroundColor,
  pressedBackgroundColor,
  disabledBackgroundColor,

  borderRadius,
  borderTopLeftRadius,
  borderTopRightRadius,
  borderBottomLeftRadius,
  borderBottomRightRadius,
  borderWidth,
  borderTopWidth,
  borderBottomWidth,
  borderLeftWidth,
  borderRightWidth,
  borderColor,
  borderTopColor,
  borderBottomColor,
  borderLeftColor,
  borderRightColor,
  borderStyle,

  textColor,
  pressedTextColor,
  disabledTextColor,
  fontSize,
  fontWeight,
  fontFamily,
  fontStyle,
  textAlign,
  lineHeight,
  letterSpacing,
  numberOfLines,

  placeholderColor,
  placeholderFontSize,
  placeholderFontWeight,
  placeholderFontFamily,

  iconComponent,
  iconSize,
  iconColor,
  pressedIconColor,
  disabledIconColor,
  iconPosition = "right",

  iconSpacing,
  iconSpacingHorizontal,
  iconSpacingLeft,
  iconSpacingRight,

  dropdownMaxHeight,
  dropdownBackgroundColor,
  dropdownBorderRadius,
  dropdownBorderWidth,
  dropdownBorderColor,
  dropdownShadowColor,
  dropdownShadowOffset,
  dropdownShadowOpacity,
  dropdownShadowRadius,
  dropdownElevation,

  itemHeight,
  itemPaddingHorizontal,
  itemPaddingVertical,
  itemBackgroundColor,
  itemPressedBackgroundColor,
  itemSelectedBackgroundColor,
  itemTextColor,
  itemPressedTextColor,
  itemSelectedTextColor,
  itemFontSize,
  itemFontWeight,
  itemFontFamily,
  itemBorderBottomWidth,
  itemBorderBottomColor,

  searchInputHeight,
  searchInputBackgroundColor,
  searchInputBorderRadius,
  searchInputBorderWidth,
  searchInputBorderColor,
  searchInputTextColor,
  searchInputFontSize,
  searchInputFontFamily,
  searchInputPaddingHorizontal,
  searchInputPaddingVertical,

  disabled = false,

  justifyContent,
  alignItems,
  alignSelf,
  flexDirection,
  flex,
  flexWrap,
  flexGrow,
  flexShrink,
  flexBasis,

  position,
  top,
  bottom,
  left,
  right,
  zIndex,

  shadowColor,
  shadowOffset,
  shadowOpacity,
  shadowRadius,
  elevation,

  opacity,
  transform,

  containerStyle = {},
  textStyle = {},
  iconStyle = {},
  dropdownStyle = {},
  itemStyle = {},
  itemTextStyle = {},
  searchInputStyle = {},

  animationDuration = 200,
  animationType = "fade",

  accessible,
  accessibilityLabel,
  accessibilityHint,
  accessibilityRole,
  testID,

  activeOpacity,
  delayPressIn,
  delayPressOut,
  delayLongPress,
  onPressIn,
  onPressOut,
  onLongPress,

  hitSlop,
  pressRetentionOffset,

  modalAnimationType = "none",
  modalTransparent = true,
  modalVisible,
  onModalShow,
  onModalHide,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [isPressed, setIsPressed] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [dropdownLayout, setDropdownLayout] = useState({
    x: 0,
    y: 0,
    width: 0,
    height: 0,
  });

  const [rotateAnimation] = useState(new Animated.Value(0));
  const dropdownRef = useRef(null);

  const handleToggle = useCallback(() => {
    if (disabled) return;
    if (!isOpen) {
      dropdownRef.current?.measure((x, y, width, height, pageX, pageY) => {
        setDropdownLayout({ x: pageX, y: pageY + height, width, height });
      });
    }
    setIsOpen(!isOpen);
    Animated.timing(rotateAnimation, {
      toValue: !isOpen ? 1 : 0,
      duration: animationDuration,
      useNativeDriver: true,
    }).start();
  }, [disabled, isOpen, animationDuration, rotateAnimation]);

  const handleItemSelect = useCallback(
    (item) => {
      onSelect && onSelect(item);
      setIsOpen(false);
      setSearchQuery("");
      Animated.timing(rotateAnimation, {
        toValue: 0,
        duration: animationDuration,
        useNativeDriver: true,
      }).start();
    },
    [onSelect, animationDuration, rotateAnimation]
  );

  const handlePressIn = useCallback(
    (event) => {
      setIsPressed(true);
      onPressIn && onPressIn(event);
    },
    [onPressIn]
  );
  const handlePressOut = useCallback(
    (event) => {
      setIsPressed(false);
      onPressOut && onPressOut(event);
    },
    [onPressOut]
  );

  const filteredData = useCallback(() => {
    if (!searchable || !searchQuery.trim()) return data;
    return data.filter((item) => {
      const label = item[labelKey]?.toString().toLowerCase() || "";
      return label.includes(searchQuery.toLowerCase());
    });
  }, [data, searchQuery, searchable, labelKey]);

  const getSelectedItem = useCallback(() => {
    return data.find((item) => item[valueKey] === value);
  }, [data, value, valueKey]);

  const getIconSpacing = useCallback(() => {
    if (iconPosition === "left" && iconSpacingLeft !== undefined)
      return iconSpacingLeft;
    if (iconPosition === "right" && iconSpacingRight !== undefined)
      return iconSpacingRight;
    if (iconSpacingHorizontal !== undefined) return iconSpacingHorizontal;
    if (iconSpacing !== undefined) return iconSpacing;
    return WIDTH(10);
  }, [
    iconPosition,
    iconSpacingLeft,
    iconSpacingRight,
    iconSpacingHorizontal,
    iconSpacing,
  ]);

  const buildOuterContainerStyles = useCallback(() => {
    const marginStyles = {};

    if (margin !== undefined) {
      if (typeof margin === "number") {
        marginStyles.margin = margin;
      } else if (Array.isArray(margin)) {
        switch (margin.length) {
          case 1:
            marginStyles.margin = margin[0];
            break;
          case 2:
            marginStyles.marginVertical = margin[0];
            marginStyles.marginHorizontal = margin[1];
            break;
          case 3:
            marginStyles.marginTop = margin[0];
            marginStyles.marginHorizontal = margin[1];
            marginStyles.marginBottom = margin[2];
            break;
          case 4:
            marginStyles.marginTop = margin[0];
            marginStyles.marginLeft = margin[1];
            marginStyles.marginBottom = margin[2];
            marginStyles.marginRight = margin[3];
            break;
        }
      }
    }

    if (marginVertical !== undefined)
      marginStyles.marginVertical = marginVertical;
    if (marginHorizontal !== undefined)
      marginStyles.marginHorizontal = marginHorizontal;

    if (marginTop !== undefined) marginStyles.marginTop = marginTop;
    if (marginBottom !== undefined) marginStyles.marginBottom = marginBottom;
    if (marginLeft !== undefined) marginStyles.marginLeft = marginLeft;
    if (marginRight !== undefined) marginStyles.marginRight = marginRight;

    return marginStyles;
  }, [
    margin,
    marginHorizontal,
    marginVertical,
    marginTop,
    marginBottom,
    marginLeft,
    marginRight,
  ]);

  const buildInnerContainerStyles = useCallback(() => {
    const styles = {
      width: width !== undefined ? width : "100%",
      height: height !== undefined ? height : HEIGHT(50),
      backgroundColor:
        backgroundColor !== undefined ? backgroundColor : R.colors.white,
      borderRadius: borderRadius !== undefined ? borderRadius : 8,
      borderWidth: borderWidth !== undefined ? borderWidth : 1,
      borderColor: borderColor !== undefined ? borderColor : R.colors.grey,
      paddingHorizontal:
        paddingHorizontal !== undefined ? paddingHorizontal : WIDTH(15),
      flexDirection: flexDirection !== undefined ? flexDirection : "row",
      alignItems: alignItems !== undefined ? alignItems : "center",
      justifyContent:
        justifyContent !== undefined ? justifyContent : "space-between",
    };
    if (disabled && disabledBackgroundColor !== undefined)
      styles.backgroundColor = disabledBackgroundColor;
    else if (isPressed && pressedBackgroundColor !== undefined)
      styles.backgroundColor = pressedBackgroundColor;
    if (paddingVertical !== undefined) {
      styles.paddingTop = paddingVertical;
      styles.paddingBottom = paddingVertical;
    }
    if (paddingTop !== undefined) styles.paddingTop = paddingTop;
    if (paddingBottom !== undefined) styles.paddingBottom = paddingBottom;
    if (paddingLeft !== undefined) styles.paddingLeft = paddingLeft;
    if (paddingRight !== undefined) styles.paddingRight = paddingRight;
    if (borderTopLeftRadius !== undefined)
      styles.borderTopLeftRadius = borderTopLeftRadius;
    if (borderTopRightRadius !== undefined)
      styles.borderTopRightRadius = borderTopRightRadius;
    if (borderBottomLeftRadius !== undefined)
      styles.borderBottomLeftRadius = borderBottomLeftRadius;
    if (borderBottomRightRadius !== undefined)
      styles.borderBottomRightRadius = borderBottomRightRadius;
    if (borderTopWidth !== undefined) styles.borderTopWidth = borderTopWidth;
    if (borderBottomWidth !== undefined)
      styles.borderBottomWidth = borderBottomWidth;
    if (borderLeftWidth !== undefined) styles.borderLeftWidth = borderLeftWidth;
    if (borderRightWidth !== undefined)
      styles.borderRightWidth = borderRightWidth;
    if (borderTopColor !== undefined) styles.borderTopColor = borderTopColor;
    if (borderBottomColor !== undefined)
      styles.borderBottomColor = borderBottomColor;
    if (borderLeftColor !== undefined) styles.borderLeftColor = borderLeftColor;
    if (borderRightColor !== undefined)
      styles.borderRightColor = borderRightColor;
    if (borderStyle !== undefined) styles.borderStyle = borderStyle;
    if (alignSelf !== undefined) styles.alignSelf = alignSelf;
    if (flex !== undefined) styles.flex = flex;
    if (flexWrap !== undefined) styles.flexWrap = flexWrap;
    if (flexGrow !== undefined) styles.flexGrow = flexGrow;
    if (flexShrink !== undefined) styles.flexShrink = flexShrink;
    if (flexBasis !== undefined) styles.flexBasis = flexBasis;
    if (position !== undefined) styles.position = position;
    if (top !== undefined) styles.top = top;
    if (bottom !== undefined) styles.bottom = bottom;
    if (left !== undefined) styles.left = left;
    if (right !== undefined) styles.right = right;
    if (zIndex !== undefined) styles.zIndex = zIndex;
    if (shadowColor !== undefined) styles.shadowColor = shadowColor;
    if (shadowOffset !== undefined) styles.shadowOffset = shadowOffset;
    if (shadowOpacity !== undefined) styles.shadowOpacity = shadowOpacity;
    if (shadowRadius !== undefined) styles.shadowRadius = shadowRadius;
    if (elevation !== undefined) styles.elevation = elevation;
    if (opacity !== undefined) styles.opacity = opacity;
    if (transform !== undefined) styles.transform = transform;
    return styles;
  }, [
    width,
    height,
    backgroundColor,
    pressedBackgroundColor,
    disabledBackgroundColor,
    borderRadius,
    borderWidth,
    borderColor,
    paddingHorizontal,
    flexDirection,
    alignItems,
    justifyContent,
    disabled,
    isPressed,
    paddingVertical,
    paddingTop,
    paddingBottom,
    paddingLeft,
    paddingRight,
    borderTopLeftRadius,
    borderTopRightRadius,
    borderBottomLeftRadius,
    borderBottomRightRadius,
    borderTopWidth,
    borderBottomWidth,
    borderLeftWidth,
    borderRightWidth,
    borderTopColor,
    borderBottomColor,
    borderLeftColor,
    borderRightColor,
    borderStyle,
    alignSelf,
    flex,
    flexWrap,
    flexGrow,
    flexShrink,
    flexBasis,
    position,
    top,
    bottom,
    left,
    right,
    zIndex,
    shadowColor,
    shadowOffset,
    shadowOpacity,
    shadowRadius,
    elevation,
    opacity,
    transform,
  ]);

  const buildTextStyles = useCallback(() => {
    const selectedItem = getSelectedItem();
    const isPlaceholder = !selectedItem;
    const styles = {
      flex: 1,
      fontSize: fontSize !== undefined ? fontSize : getFontSize(14),
      color: textColor !== undefined ? textColor : R.colors.black,
      fontFamily: fontFamily !== undefined ? fontFamily : R.fonts.InterRegular,
    };
    if (isPlaceholder) {
      if (placeholderColor !== undefined) styles.color = placeholderColor;
      if (placeholderFontSize !== undefined)
        styles.fontSize = placeholderFontSize;
      if (placeholderFontWeight !== undefined)
        styles.fontWeight = placeholderFontWeight;
      if (placeholderFontFamily !== undefined)
        styles.fontFamily = placeholderFontFamily;
    } else {
      if (disabled && disabledTextColor !== undefined)
        styles.color = disabledTextColor;
      else if (isPressed && pressedTextColor !== undefined)
        styles.color = pressedTextColor;
    }
    if (fontWeight !== undefined && !isPlaceholder)
      styles.fontWeight = fontWeight;
    if (fontStyle !== undefined) styles.fontStyle = fontStyle;
    if (textAlign !== undefined) styles.textAlign = textAlign;
    if (lineHeight !== undefined) styles.lineHeight = lineHeight;
    if (letterSpacing !== undefined) styles.letterSpacing = letterSpacing;
    return styles;
  }, [
    fontSize,
    textColor,
    fontFamily,
    placeholderColor,
    placeholderFontSize,
    placeholderFontWeight,
    placeholderFontFamily,
    disabled,
    isPressed,
    disabledTextColor,
    pressedTextColor,
    fontWeight,
    fontStyle,
    textAlign,
    lineHeight,
    letterSpacing,
    getSelectedItem,
  ]);

  const buildDropdownStyles = useCallback(() => {
    const screenHeight = Dimensions.get("window").height;
    const maxHeight =
      dropdownMaxHeight !== undefined ? dropdownMaxHeight : HEIGHT(200);
    const styles = {
      position: "absolute",
      left: dropdownLayout.x,
      top: dropdownLayout.y,
      width: dropdownLayout.width,
      maxHeight: maxHeight,
      backgroundColor:
        dropdownBackgroundColor !== undefined
          ? dropdownBackgroundColor
          : R.colors.white,
      borderRadius:
        dropdownBorderRadius !== undefined ? dropdownBorderRadius : 8,
      borderWidth: dropdownBorderWidth !== undefined ? dropdownBorderWidth : 1,
      borderColor:
        dropdownBorderColor !== undefined ? dropdownBorderColor : R.colors.grey,
      shadowColor:
        dropdownShadowColor !== undefined ? dropdownShadowColor : "#000",
      shadowOffset:
        dropdownShadowOffset !== undefined
          ? dropdownShadowOffset
          : { width: 0, height: 2 },
      shadowOpacity:
        dropdownShadowOpacity !== undefined ? dropdownShadowOpacity : 0.25,
      shadowRadius:
        dropdownShadowRadius !== undefined ? dropdownShadowRadius : 3.84,
      elevation: dropdownElevation !== undefined ? dropdownElevation : 5,
      zIndex: 1000,
    };
    if (dropdownLayout.y + maxHeight > screenHeight - HEIGHT(50)) {
      styles.top = dropdownLayout.y - dropdownLayout.height - maxHeight;
    }
    return styles;
  }, [
    dropdownLayout,
    dropdownMaxHeight,
    dropdownBackgroundColor,
    dropdownBorderRadius,
    dropdownBorderWidth,
    dropdownBorderColor,
    dropdownShadowColor,
    dropdownShadowOffset,
    dropdownShadowOpacity,
    dropdownShadowRadius,
    dropdownElevation,
  ]);

  const buildItemStyles = useCallback(
    (item, isSelected, isItemPressed) => {
      const styles = {
        height: itemHeight !== undefined ? itemHeight : HEIGHT(45),
        paddingHorizontal:
          itemPaddingHorizontal !== undefined
            ? itemPaddingHorizontal
            : WIDTH(15),
        paddingVertical:
          itemPaddingVertical !== undefined ? itemPaddingVertical : HEIGHT(12),
        justifyContent: "center",
        borderBottomWidth:
          itemBorderBottomWidth !== undefined ? itemBorderBottomWidth : 0.5,
        borderBottomColor:
          itemBorderBottomColor !== undefined
            ? itemBorderBottomColor
            : R.colors.lightGrey,
      };
      if (isSelected && itemSelectedBackgroundColor !== undefined)
        styles.backgroundColor = itemSelectedBackgroundColor;
      else if (isItemPressed && itemPressedBackgroundColor !== undefined)
        styles.backgroundColor = itemPressedBackgroundColor;
      else if (itemBackgroundColor !== undefined)
        styles.backgroundColor = itemBackgroundColor;
      return styles;
    },
    [
      itemHeight,
      itemPaddingHorizontal,
      itemPaddingVertical,
      itemBorderBottomWidth,
      itemBorderBottomColor,
      itemSelectedBackgroundColor,
      itemPressedBackgroundColor,
      itemBackgroundColor,
    ]
  );

  const buildItemTextStyles = useCallback(
    (item, isSelected, isItemPressed) => {
      const styles = {
        fontSize: itemFontSize !== undefined ? itemFontSize : getFontSize(14),
        fontFamily:
          itemFontFamily !== undefined ? itemFontFamily : R.fonts.InterRegular,
        color: itemTextColor !== undefined ? itemTextColor : R.colors.black,
      };
      if (isSelected && itemSelectedTextColor !== undefined)
        styles.color = itemSelectedTextColor;
      else if (isItemPressed && itemPressedTextColor !== undefined)
        styles.color = itemPressedTextColor;
      if (itemFontWeight !== undefined) styles.fontWeight = itemFontWeight;
      return styles;
    },
    [
      itemFontSize,
      itemFontFamily,
      itemTextColor,
      itemSelectedTextColor,
      itemPressedTextColor,
      itemFontWeight,
    ]
  );

  const getCurrentIconColor = useCallback(() => {
    if (disabled && disabledIconColor !== undefined) return disabledIconColor;
    if (isPressed && pressedIconColor !== undefined) return pressedIconColor;
    if (iconColor !== undefined) return iconColor;
    return R.colors.grey;
  }, [disabled, isPressed, disabledIconColor, pressedIconColor, iconColor]);

  const renderIcon = useCallback(() => {
    const spacing = getIconSpacing();
    const currentIconColor = getCurrentIconColor();
    const DefaultIcon =
      iconComponent ||
      (() => (
        <View
          style={{
            width: iconSize !== undefined ? iconSize : 12,
            height: iconSize !== undefined ? iconSize : 12,
            borderRightWidth: 1,
            borderBottomWidth: 1,
            borderColor: currentIconColor,
            transform: [{ rotate: "45deg" }],
          }}
        />
      ));
    const iconContainerStyles = {
      marginLeft: iconPosition === "right" ? spacing : 0,
      marginRight: iconPosition === "left" ? spacing : 0,
      transform: [
        {
          rotate: rotateAnimation.interpolate({
            inputRange: [0, 1],
            outputRange: ["0deg", "90deg"],
          }),
        },
      ],
    };
    return (
      <Animated.View style={iconContainerStyles}>
        {typeof DefaultIcon === "function" ? (
          <DefaultIcon
            size={iconSize}
            color={currentIconColor}
            style={iconStyle}
          />
        ) : (
          React.cloneElement(DefaultIcon, {
            size: iconSize,
            color: currentIconColor,
            style: [DefaultIcon.props?.style, iconStyle],
          })
        )}
      </Animated.View>
    );
  }, [
    iconComponent,
    iconSize,
    iconPosition,
    iconStyle,
    getIconSpacing,
    getCurrentIconColor,
    rotateAnimation,
  ]);

  const renderSelectedText = useCallback(() => {
    const selectedItem = getSelectedItem();
    if (renderSelectedItem && selectedItem) {
      return renderSelectedItem(selectedItem);
    }
    const displayText = selectedItem ? selectedItem[labelKey] : placeholder;
    return (
      <Text
        style={[buildTextStyles(), textStyle]}
        numberOfLines={numberOfLines !== undefined ? numberOfLines : 1}
      >
        {displayText}
      </Text>
    );
  }, [
    getSelectedItem,
    renderSelectedItem,
    labelKey,
    placeholder,
    buildTextStyles,
    textStyle,
    numberOfLines,
  ]);

  const renderSearchInput = useCallback(() => {
    if (!searchable) return null;
    const searchStyles = {
      height: searchInputHeight !== undefined ? searchInputHeight : HEIGHT(40),
      backgroundColor:
        searchInputBackgroundColor !== undefined
          ? searchInputBackgroundColor
          : R.colors.lightGrey,
      borderRadius:
        searchInputBorderRadius !== undefined ? searchInputBorderRadius : 6,
      borderWidth:
        searchInputBorderWidth !== undefined ? searchInputBorderWidth : 1,
      borderColor:
        searchInputBorderColor !== undefined
          ? searchInputBorderColor
          : R.colors.grey,
      color:
        searchInputTextColor !== undefined
          ? searchInputTextColor
          : R.colors.black,
      fontSize:
        searchInputFontSize !== undefined
          ? searchInputFontSize
          : getFontSize(14),
      fontFamily:
        searchInputFontFamily !== undefined
          ? searchInputFontFamily
          : R.fonts.InterRegular,
      paddingHorizontal:
        searchInputPaddingHorizontal !== undefined
          ? searchInputPaddingHorizontal
          : WIDTH(12),
      paddingVertical:
        searchInputPaddingVertical !== undefined
          ? searchInputPaddingVertical
          : HEIGHT(8),
      margin: WIDTH(10),
    };
    return (
      <TextInput
        style={[searchStyles, searchInputStyle]}
        placeholder={searchPlaceholder}
        value={searchQuery}
        onChangeText={setSearchQuery}
        autoFocus={true}
      />
    );
  }, [
    searchable,
    searchInputHeight,
    searchInputBackgroundColor,
    searchInputBorderRadius,
    searchInputBorderWidth,
    searchInputBorderColor,
    searchInputTextColor,
    searchInputFontSize,
    searchInputFontFamily,
    searchInputPaddingHorizontal,
    searchInputPaddingVertical,
    searchInputStyle,
    searchPlaceholder,
    searchQuery,
  ]);

  const renderDropdownItem = useCallback(
    ({ item, index }) => {
      const isSelected = item[valueKey] === value;
      if (renderItem) {
        return renderItem(item, index, isSelected);
      }
      return (
        <DropdownItem
          item={item}
          isSelected={isSelected}
          onSelect={handleItemSelect}
          buildItemStyles={buildItemStyles}
          buildItemTextStyles={buildItemTextStyles}
          itemStyle={itemStyle}
          itemTextStyle={itemTextStyle}
          labelKey={labelKey}
        />
      );
    },
    [
      value,
      valueKey,
      renderItem,
      handleItemSelect,
      buildItemStyles,
      buildItemTextStyles,
      itemStyle,
      itemTextStyle,
      labelKey,
    ]
  );

  const renderDropdownContent = useCallback(() => {
    const filtered = filteredData();
    return (
      <View style={[buildDropdownStyles(), dropdownStyle]}>
        {renderSearchInput()}
        <FlatList
          data={filtered}
          renderItem={renderDropdownItem}
          keyExtractor={
            keyExtractor ||
            ((item, index) => item[valueKey]?.toString() || index.toString())
          }
          showsVerticalScrollIndicator={false}
          nestedScrollEnabled={true}
        />
      </View>
    );
  }, [
    filteredData,
    buildDropdownStyles,
    dropdownStyle,
    renderSearchInput,
    renderDropdownItem,
    keyExtractor,
    valueKey,
  ]);

  const buildTitleStyles = useCallback(() => {
    const styles = {
      // Default styles
      marginBottom: titleMarginBottom !== undefined ? titleMarginBottom : 3,
      fontSize: titleFontSize !== undefined ? titleFontSize : R.fontsize.fontsSize12,
      color: titleColor !== undefined ? titleColor : R.colors.black,
      fontFamily:
        titleFontFamily !== undefined ? titleFontFamily : R.fonts.InterRegular,
    };

    // PERFORMANCE: Apply conditional styles efficiently
    if (titleFontWeight !== undefined) styles.fontWeight = titleFontWeight;
    if (titleFontStyle !== undefined) styles.fontStyle = titleFontStyle;
    if (titleTextAlign !== undefined) styles.textAlign = titleTextAlign;
    if (titleLineHeight !== undefined) styles.lineHeight = titleLineHeight;
    if (titleLetterSpacing !== undefined)
      styles.letterSpacing = titleLetterSpacing;
    if (titleTextTransform !== undefined)
      styles.textTransform = titleTextTransform;
    if (titleTextDecorationLine !== undefined)
      styles.textDecorationLine = titleTextDecorationLine;
    if (titleTextDecorationColor !== undefined)
      styles.textDecorationColor = titleTextDecorationColor;
    if (titleTextDecorationStyle !== undefined)
      styles.textDecorationStyle = titleTextDecorationStyle;

    // FUNCTIONALITY: Margin styles
    if (titleMarginTop !== undefined) styles.marginTop = titleMarginTop;
    if (titleMarginLeft !== undefined) styles.marginLeft = titleMarginLeft;
    if (titleMarginRight !== undefined) styles.marginRight = titleMarginRight;
    if (titleMarginHorizontal !== undefined) {
      styles.marginLeft = titleMarginHorizontal;
      styles.marginRight = titleMarginHorizontal;
    }
    if (titleMarginVertical !== undefined) {
      styles.marginTop = titleMarginVertical;
      styles.marginBottom = titleMarginVertical;
    }

    // FUNCTIONALITY: Padding styles
    if (titlePaddingTop !== undefined) styles.paddingTop = titlePaddingTop;
    if (titlePaddingBottom !== undefined)
      styles.paddingBottom = titlePaddingBottom;
    if (titlePaddingLeft !== undefined) styles.paddingLeft = titlePaddingLeft;
    if (titlePaddingRight !== undefined)
      styles.paddingRight = titlePaddingRight;
    if (titlePaddingHorizontal !== undefined) {
      styles.paddingLeft = titlePaddingHorizontal;
      styles.paddingRight = titlePaddingHorizontal;
    }
    if (titlePaddingVertical !== undefined) {
      styles.paddingTop = titlePaddingVertical;
      styles.paddingBottom = titlePaddingVertical;
    }

    return styles;
  }, [
    titleMarginBottom,
    titleFontSize,
    titleColor,
    titleFontFamily,
    titleFontWeight,
    titleFontStyle,
    titleTextAlign,
    titleLineHeight,
    titleLetterSpacing,
    titleTextTransform,
    titleTextDecorationLine,
    titleTextDecorationColor,
    titleTextDecorationStyle,
    titleMarginTop,
    titleMarginLeft,
    titleMarginRight,
    titleMarginHorizontal,
    titleMarginVertical,
    titlePaddingTop,
    titlePaddingBottom,
    titlePaddingLeft,
    titlePaddingRight,
    titlePaddingHorizontal,
    titlePaddingVertical,
  ]);

  // FUNCTIONALITY: Build required symbol styles
  const buildRequiredSymbolStyles = useCallback(() => {
    const styles = {
      color: requiredSymbolColor !== undefined ? requiredSymbolColor : "red",
    };

    if (requiredSymbolFontSize !== undefined)
      styles.fontSize = requiredSymbolFontSize;
    if (requiredSymbolFontWeight !== undefined)
      styles.fontWeight = requiredSymbolFontWeight;
    if (requiredSymbolFontFamily !== undefined)
      styles.fontFamily = requiredSymbolFontFamily;

    return styles;
  }, [
    requiredSymbolColor,
    requiredSymbolFontSize,
    requiredSymbolFontWeight,
    requiredSymbolFontFamily,
  ]);

  // UI/UX: Enhanced title rendering with better required symbol handling
  const renderTitle = useCallback(() => {
    if (!title) return null;

    // FUNCTIONALITY: Check for required marker (supports * hoặc custom marker)
    const hasRequiredMarker = title.includes("*") || title.includes("required");

    if (hasRequiredMarker) {
      // PERFORMANCE: Efficient string processing
      const cleanTitle = title.replace(/\*|required/g, "").trim();
      const requiredText =
        requiredSymbolText !== undefined ? requiredSymbolText : " *";

      return (
        <Text style={[buildTitleStyles(), titleStyle]}>
          {cleanTitle}
          <Text style={[buildRequiredSymbolStyles(), titleRequiredStyle]}>
            {requiredText}
          </Text>
        </Text>
      );
    }

    return <Text style={[buildTitleStyles(), titleStyle]}>{title}</Text>;
  }, [
    title,
    buildTitleStyles,
    titleStyle,
    buildRequiredSymbolStyles,
    titleRequiredStyle,
    requiredSymbolText,
  ]);

  const outerContainerStyles = buildOuterContainerStyles();
  const innerContainerStyles = [buildInnerContainerStyles(), containerStyle];

  return (
    <>
      <View style={outerContainerStyles}>
        {renderTitle()}
        <TouchableOpacity
          ref={dropdownRef}
          style={innerContainerStyles}
          onPress={handleToggle}
          onPressIn={handlePressIn}
          onPressOut={handlePressOut}
          onLongPress={onLongPress}
          disabled={disabled}
          activeOpacity={activeOpacity}
          delayPressIn={delayPressIn}
          delayPressOut={delayPressOut}
          delayLongPress={delayLongPress}
          hitSlop={hitSlop}
          pressRetentionOffset={pressRetentionOffset}
          accessible={accessible}
          accessibilityLabel={accessibilityLabel}
          accessibilityHint={accessibilityHint}
          accessibilityRole={accessibilityRole}
          testID={testID}
        >
          {iconPosition === "left" && renderIcon()}
          {renderSelectedText()}
          {iconPosition === "right" && renderIcon()}
        </TouchableOpacity>
      </View>

      <Modal
        visible={modalVisible !== undefined ? modalVisible : isOpen}
        transparent={modalTransparent}
        animationType={modalAnimationType}
        onShow={onModalShow}
        onRequestClose={() => {
          setIsOpen(false);
          Animated.timing(rotateAnimation, {
            toValue: 0,
            duration: animationDuration,
            useNativeDriver: true,
          }).start();
          onModalHide && onModalHide();
        }}
      >
        <TouchableOpacity
          style={styles.backdrop}
          activeOpacity={1}
          onPress={() => {
            setIsOpen(false);
            Animated.timing(rotateAnimation, {
              toValue: 0,
              duration: animationDuration,
              useNativeDriver: true,
            }).start();
          }}
        >
          {renderDropdownContent()}
        </TouchableOpacity>
      </Modal>
    </>
  );
};

export default DropdownSelect;

const styles = StyleSheet.create({
  backdrop: {
    flex: 1,
    backgroundColor: "transparent",
  },

  requiredSymbol: {
    color: "red",
  },
});
