import { Pressable, StyleSheet, Text, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useTranslation } from 'react-i18next';
import type { LucideIcon } from 'lucide-react-native';
import {
  Bookmark,
  CalendarCheck,
  Clock3,
  Home,
  Search,
  Settings,
  ShoppingBag,
  Store,
  UserRound,
} from 'lucide-react-native';
import { naviTheme } from '../../theme';

export type NaviTabVariant = 'customer' | 'food' | 'translator' | 'grocery';

interface RouterTabBarProps {
  state: {
    index: number;
    routes: Array<{ key: string; name: string }>;
  };
  descriptors: Record<string, { options: { title?: string; tabBarLabel?: unknown } } | undefined>;
  navigation: {
    emit: (event: { type: string; target: string; canPreventDefault: boolean }) => { defaultPrevented: boolean };
    navigate: (name: string) => void;
  };
  variant?: NaviTabVariant;
}

const customerIcons: Record<string, LucideIcon> = {
  home: Home,
  discover: Search,
  bookings: CalendarCheck,
  saved: Bookmark,
  profile: UserRound,
};

export const naviBottomTabSets: Record<NaviTabVariant, Array<{ label: string; route: string; icon: LucideIcon; center?: boolean }>> = {
  customer: [
    { label: 'Home', route: '/(tabs)/home', icon: Home },
    { label: 'Discover', route: '/(tabs)/discover', icon: Search },
    { label: 'Bookings', route: '/(tabs)/bookings', icon: CalendarCheck },
    { label: 'Saved', route: '/(tabs)/saved', icon: Bookmark },
    { label: 'Profile', route: '/(tabs)/profile', icon: UserRound },
  ],
  food: [
    { label: 'Home', route: '/(tabs)/home', icon: Home },
    { label: 'Orders', route: '/(tabs)/bookings', icon: ShoppingBag },
    { label: 'Search', route: '/services/food', icon: Search, center: true },
    { label: 'Favorites', route: '/(tabs)/saved', icon: Bookmark },
    { label: 'Profile', route: '/(tabs)/profile', icon: UserRound },
  ],
  translator: [
    { label: 'Hub', route: '/(tabs)/home', icon: Home },
    { label: 'Translate', route: '/translator', icon: Search },
    { label: 'History', route: '/translator/history', icon: Clock3 },
    { label: 'Settings', route: '/settings/language', icon: Settings },
  ],
  grocery: [
    { label: 'Shop', route: '/services/grocery', icon: Store },
    { label: 'Explore', route: '/(tabs)/discover', icon: Search },
    { label: 'Orders', route: '/(tabs)/bookings', icon: ShoppingBag },
    { label: 'Profile', route: '/(tabs)/profile', icon: UserRound },
  ],
};

export function NaviBottomTabs({ state, descriptors, navigation, variant = 'customer' }: RouterTabBarProps) {
  const { t } = useTranslation();
  const insets = useSafeAreaInsets();

  return (
    <View style={[styles.shell, { paddingBottom: Math.max(insets.bottom, 10), minHeight: 76 + Math.max(insets.bottom, 10) }]}>
      {state.routes.map((route, index) => {
        const descriptor = descriptors[route.key];
        const rawLabel = descriptor?.options.tabBarLabel;
        const label = typeof rawLabel === 'string' ? rawLabel : descriptor?.options.title ?? labelForRoute(route.name, t);
        const isFocused = state.index === index;
        const Icon = iconForRoute(route.name, variant);

        return (
          <Pressable
            key={route.key}
            accessibilityRole="button"
            accessibilityState={isFocused ? { selected: true } : {}}
            accessibilityLabel={`${label} tab`}
            onPress={() => {
              const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true });
              if (!isFocused && !event.defaultPrevented) navigation.navigate(route.name);
            }}
            style={styles.item}
          >
            <View style={[styles.iconBubble, isFocused ? styles.iconBubbleActive : null]}>
              <Icon
                color={isFocused ? naviTheme.colors.primaryBlue : naviTheme.colors.lightText}
                size={21}
                strokeWidth={2.3}
              />
            </View>
            <Text style={[styles.label, isFocused ? styles.labelActive : null]} numberOfLines={1}>
              {label}
            </Text>
          </Pressable>
        );
      })}
    </View>
  );
}

function iconForRoute(routeName: string, variant: NaviTabVariant): LucideIcon {
  if (variant === 'customer') return customerIcons[routeName] ?? Home;
  const configured = naviBottomTabSets[variant].find((tab) => tab.route.endsWith(routeName));
  return configured?.icon ?? customerIcons[routeName] ?? Home;
}

function labelForRoute(routeName: string, t: (key: string) => string): string {
  if (routeName === 'home') return t('tabs.home');
  if (routeName === 'discover') return t('tabs.discover');
  if (routeName === 'bookings') return t('tabs.bookings');
  if (routeName === 'saved') return t('tabs.saved');
  if (routeName === 'profile') return t('tabs.profile');
  return routeName;
}

const styles = StyleSheet.create({
  shell: {
    alignItems: 'center',
    backgroundColor: naviTheme.colors.surface,
    borderTopColor: naviTheme.colors.border,
    borderTopWidth: 1,
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingHorizontal: naviTheme.spacing.sm,
    paddingTop: 8,
    ...naviTheme.shadows.card,
  },
  item: {
    alignItems: 'center',
    flex: 1,
    gap: 3,
    justifyContent: 'center',
    minWidth: 0,
  },
  iconBubble: {
    alignItems: 'center',
    borderRadius: naviTheme.radius.pill,
    height: 34,
    justifyContent: 'center',
    width: 44,
  },
  iconBubbleActive: {
    backgroundColor: naviTheme.colors.softBlue,
  },
  label: {
    color: naviTheme.colors.lightText,
    fontSize: 11,
    fontWeight: '800',
  },
  labelActive: {
    color: naviTheme.colors.primaryBlue,
  },
});
