import React, { useMemo, useState } from "react";
import { StyleSheet, TouchableOpacity, View } from "react-native";
import { Item, ItemProps } from "./Item";
import { ItemIcon, ItemIconProps } from "./ItemIcon";
import { ItemLabel, ItemLabelProps } from "./ItemLabel";
import { defaultSelectedAsset } from "./assets";
import * as assets from "./assets";

type ButtonProps = {
  configuration: any;
  width: number;
  selectedItem?: any;
  item: any; // Adjust type as needed
  onPress: (item: any) => void; // Adjust type as needed
  iconBaseProps?: ItemIconProps;
  itemBaseProps?: ItemProps;
  labelBaseProps?: ItemLabelProps;
  disabled?: boolean;
  label?: string | Record<string, string>;
};

const styles = StyleSheet.create({
  label_icon_container: {
    flexDirection: "row",
    alignItems: "center",
  },
});

export function Button({
  selectedItem,
  item,
  onPress,
  configuration,
  width,
  iconBaseProps,
  itemBaseProps,
  labelBaseProps,
  label,
  disabled = false,
}: ButtonProps) {
  const [focused, setFocused] = useState(false);

  const selected = useMemo(
    () => selectedItem && item.value === selectedItem?.value,
    [selectedItem, selectedItem]
  );

  const itemProps = useMemo<ItemProps>(
    () => ({
      ...itemBaseProps,
      width,
    }),
    [configuration, width]
  );

  const itemIconProps = useMemo<ItemIconProps>(
    () => ({
      ...iconBaseProps,
      asset: configuration[item.asset] ?? assets[item.asset] ?? item.asset,
    }),
    [configuration, item.asset]
  );

  const selectedItemIconProps = useMemo<ItemIconProps>(
    () => ({
      ...iconBaseProps,
      asset:
        configuration["modal_bottom_sheet_item_selected_icon"] ||
        defaultSelectedAsset,
      marginRight: 10,
    }),
    [configuration]
  );

  const itemLabelProps = useMemo<ItemLabelProps>(
    () => ({
      ...labelBaseProps,
      label: label ?? configuration[item?.label] ?? item?.label ?? null,
    }),
    [configuration, item?.label]
  );

  if (disabled) return null;

  return (
    <View style={{ maxWidth: width }}>
      <TouchableOpacity
        activeOpacity={1}
        onPress={() => onPress(item)}
        onPressIn={() => setFocused(true)}
        onPressOut={() => setFocused(false)}
      >
        <Item {...itemProps} focused={focused} selected={selected}>
          <View style={styles.label_icon_container}>
            {itemIconProps.asset && itemIconProps.asset.length > 0 && (
              <ItemIcon {...itemIconProps} />
            )}
            {itemLabelProps.label && (
              <ItemLabel
                {...itemLabelProps}
                focused={focused}
                selected={selected}
              />
            )}
          </View>
          {selected && <ItemIcon {...selectedItemIconProps} />}
        </Item>
      </TouchableOpacity>
    </View>
  );
}
