import React, { useRef } from 'react';
import {
  View,
  Text,
  TouchableWithoutFeedback,
  Animated,
  StyleSheet,
  Platform,
} from 'react-native';
import { BottomTabBarProps } from '@react-navigation/bottom-tabs';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { COLORS, SPACING, RADIUS, FONT_SIZE, FONT, SHADOWS } from '../theme';
import { useTheme } from '../theme';

const TAB_CONFIG: Record<string, { icon: string; label: string }> = {
  MarketplaceTab: { icon: '🧭', label: 'Explore'  },
  DashboardTab:   { icon: '⊞',  label: 'Chatbots' },
  InboxTab:       { icon: '✉',  label: 'Inbox'    },
  AccountTab:     { icon: '◎',  label: 'Account'  },
};

export function CustomTabBar({ state, descriptors, navigation }: BottomTabBarProps) {
  const { theme, isDark } = useTheme();
  const insets = useSafeAreaInsets();

  return (
    <View
      style={[
        styles.wrapper,
        { paddingBottom: insets.bottom || SPACING.sm, backgroundColor: theme.tabBar },
      ]}>
      <View style={[styles.tabBar, isDark ? styles.tabBarDark : styles.tabBarLight]}>
        {state.routes.map((route, index) => {
          const isFocused = state.index === index;
          const config = TAB_CONFIG[route.name] ?? { icon: '•', label: route.name };

          const onPress = () => {
            const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true });
            if (!isFocused && !event.defaultPrevented) {
              navigation.navigate(route.name);
            }
          };

          return (
            <TabItem
              key={route.key}
              icon={config.icon}
              label={config.label}
              isFocused={isFocused}
              onPress={onPress}
            />
          );
        })}
      </View>
    </View>
  );
}

function TabItem({
  icon,
  label,
  isFocused,
  onPress,
}: {
  icon: string;
  label: string;
  isFocused: boolean;
  onPress: () => void;
}) {
  const { theme } = useTheme();
  const scale = useRef(new Animated.Value(1)).current;
  const bgOpacity = useRef(new Animated.Value(isFocused ? 1 : 0)).current;

  React.useEffect(() => {
    Animated.timing(bgOpacity, {
      toValue: isFocused ? 1 : 0,
      duration: 200,
      useNativeDriver: false,
    }).start();
  }, [isFocused, bgOpacity]);

  const onPressIn = () =>
    Animated.spring(scale, { toValue: 0.88, useNativeDriver: true, speed: 60, bounciness: 0 }).start();

  const onPressOut = () =>
    Animated.spring(scale, { toValue: 1, useNativeDriver: true, speed: 30, bounciness: 6 }).start();

  const pillBg = bgOpacity.interpolate({
    inputRange: [0, 1],
    outputRange: ['rgba(99,102,241,0)', 'rgba(99,102,241,0.1)'],
  });

  return (
    <TouchableWithoutFeedback onPress={onPress} onPressIn={onPressIn} onPressOut={onPressOut}>
      <Animated.View style={[styles.tabItem, { transform: [{ scale }] }]}>
        <Animated.View style={[styles.pill, { backgroundColor: pillBg }]}>
          <Text style={[styles.icon, { opacity: isFocused ? 1 : 0.45 }]}>{icon}</Text>
          <Text
            style={[
              styles.label,
              {
                color: isFocused ? COLORS.primary : theme.textMuted,
                fontWeight: isFocused ? (FONT.semibold as any) : (FONT.regular as any),
              },
            ]}>
            {label}
          </Text>
        </Animated.View>
      </Animated.View>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    borderTopWidth: 1,
    borderTopColor: 'transparent',
  },
  tabBar: {
    flexDirection: 'row',
    marginHorizontal: SPACING.md,
    marginTop: SPACING.xs,
    borderRadius: RADIUS.xl,
    padding: SPACING.xs,
    ...SHADOWS.md,
  },
  tabBarLight: {
    backgroundColor: COLORS.white,
    borderWidth: 1,
    borderColor: COLORS.light.border,
    ...Platform.select({
      ios: { shadowColor: '#6366f1', shadowOpacity: 0.12, shadowRadius: 20, shadowOffset: { width: 0, height: 6 } },
      android: { elevation: 8 },
    }),
  },
  tabBarDark: {
    backgroundColor: COLORS.dark.surface,
    borderWidth: 1,
    borderColor: COLORS.dark.border,
    ...Platform.select({
      ios: { shadowColor: '#000', shadowOpacity: 0.4, shadowRadius: 20, shadowOffset: { width: 0, height: 6 } },
      android: { elevation: 8 },
    }),
  },
  tabItem: {
    flex: 1,
    alignItems: 'center',
  },
  pill: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: SPACING.sm,
    paddingHorizontal: SPACING.sm,
    borderRadius: RADIUS.lg,
    width: '100%',
    gap: 3,
  },
  icon: { fontSize: 22 },
  label: { fontSize: FONT_SIZE.xs, letterSpacing: 0.2 },
});
