import { View } from 'react-native';
import { useLinkBuilder } from '@react-navigation/native';
import { PlatformPressable } from '@react-navigation/elements';
import React, { ReactNode } from 'react';
import MenuItem from './menu-item';

interface BottomNavigationProps {
  state: any;
  descriptors: any;
  navigation: any;
  config: {
    [key: string]: {
      active: ReactNode;
      inactive: ReactNode;
      title: string;
      order: number;
      badge?: {
        variant: 'dot' | 'new' | 'number';
        count?: number;
      };
    };
  };
  shadow?: boolean;
  divider?: boolean;
  height?: number;
}

const BottomNavigation = ({
  state,
  descriptors,
  navigation,
  config,
  shadow = false,
  divider = false,
  height = 86
}: BottomNavigationProps) => {
  const { buildHref } = useLinkBuilder();
  const dividerClassFlag = divider ? 'border-t border-gray-100' : '';
  const dynamicPaddingBottom = Math.max(10, height * 0.2); // 높이의 20% 또는 최소 10px

  // order 기준으로 routes 정렬
  const sortedRoutes = [...state.routes].sort(
    (a, b) => config[a.name].order - config[b.name].order,
  );

  return (
      <View
          className="bg-background"
          style={{
              flexDirection: 'row',
              height: height
          }}
      >
      {sortedRoutes.map((route, index) => {
        const routeConfig = config[route.name];
        const isFocused =
          state.index === state.routes.findIndex((r) => r.key === route.key);

        const onPress = () => {
          const event = navigation.emit({
            type: 'tabPress',
            target: route.key,
            canPreventDefault: true,
          });

          if (!isFocused && !event.defaultPrevented) {
            navigation.navigate(route.name, route.params);
          }
        };

        return (
          <PlatformPressable
            key={route.key}
            pressOpacity={1}
            href={buildHref(route.name, route.params)}
            accessibilityState={isFocused ? { selected: true } : {}}
            testID={`${route.name}-tab`}
            onPress={onPress}
            className={`flex-1 ${dividerClassFlag} justify-center items-center`}
            style={{ paddingBottom: dynamicPaddingBottom }}
          >
            <MenuItem
              activeIcon={routeConfig.active}
              idleIcon={routeConfig.inactive}
              menuTitle={routeConfig.title}
              selected={isFocused}
              badge={routeConfig.badge}
            />
          </PlatformPressable>
        );
      })}
    </View>
  );
};

export default BottomNavigation;
