import React from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import type { BottomTabBarProps } from '@react-navigation/bottom-tabs';
import { useTheme } from '../../theme';
import { useNumpadUiStore } from '../../store/numpadUiStore';
import type { IoniconName } from '../category/categoryIcons';

/** 路由名 → 图标（与 (tabs)/_layout.tsx 的 4 个 Screen 对应）。 */
const TAB_ICONS: Record<string, IoniconName> = {
  index: 'home-outline',
  transactions: 'list-outline',
  report: 'pie-chart-outline',
  settings: 'settings-outline',
};

/**
 * 自定义底部导航：4 个内容 Tab + 中央凸起＋。
 * ＋不是路由——P2 暂跳转 /transaction/new，P3 改为唤起全局 NumpadSheet。
 */
export function AppTabBar({ state, descriptors, navigation }: BottomTabBarProps) {
  const { theme } = useTheme();
  const insets = useSafeAreaInsets();
  const openNumpad = useNumpadUiStore(s => s.open);

  const renderTab = (route: (typeof state.routes)[number]) => {
    const routeIndex = state.routes.indexOf(route);
    const focused = state.index === routeIndex;
    const options = descriptors[route.key].options;
    const label = (options.title ?? route.name) as string;
    const color = focused ? theme.colors.accent : theme.colors.fgSecondary;
    const onPress = () => {
      const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true });
      if (!focused && !event.defaultPrevented) navigation.navigate(route.name);
    };
    return (
      <Pressable
        key={route.key}
        onPress={onPress}
        style={styles.tab}
        accessibilityRole="button"
        accessibilityState={{ selected: focused }}
        accessibilityLabel={label}
      >
        <Ionicons name={TAB_ICONS[route.name] ?? 'ellipse-outline'} size={22} color={color} />
        <Text style={{ fontSize: theme.typography.caption.fontSize - 2, fontWeight: '600', color }}>{label}</Text>
      </Pressable>
    );
  };

  return (
    <View
      style={[styles.bar, {
        backgroundColor: theme.colors.bgSecondary,
        borderTopColor: theme.colors.border,
        paddingBottom: Math.max(insets.bottom, 8),
      }]}
    >
      {state.routes.slice(0, 2).map(renderTab)}
      <View style={styles.plusSlot}>
        <Pressable
          onPress={() => openNumpad()}
          style={[styles.plus, {
            backgroundColor: theme.colors.accent,
            borderColor: theme.colors.bgPrimary,
          }, theme.shadows.lg]}
          accessibilityRole="button"
          accessibilityLabel="记一笔"
        >
          <Ionicons name="add" size={30} color={theme.colors.fgInverse} />
        </Pressable>
      </View>
      {state.routes.slice(2).map(renderTab)}
    </View>
  );
}

const styles = StyleSheet.create({
  bar: { flexDirection: 'row', alignItems: 'center', borderTopWidth: StyleSheet.hairlineWidth },
  tab: { flex: 1, alignItems: 'center', paddingTop: 8, gap: 2, minHeight: 44 },
  plusSlot: { width: 64, alignItems: 'center' },
  plus: { width: 52, height: 52, borderRadius: 26, alignItems: 'center', justifyContent: 'center', marginTop: -24, borderWidth: 4 },
});
