import React from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useTheme } from '../theme/ThemeProvider';
import { textStyle, space } from '../theme';

export type TabKey = 'today' | 'sections' | 'saved' | 'settings';

/**
 * The tab bar.
 *
 * Four destinations, text and a small glyph. No icon library: a
 * dependency for four shapes is weight the app does not need, and
 * bundled icon fonts are one of the quiet causes of slow first launch.
 */
const GLYPH: Record<TabKey, string> = {
  today: '◎',
  sections: '⊞',
  saved: '★',
  settings: '⚙',
};

export function TabBar({
  active,
  onChange,
  labels,
}: {
  active: TabKey;
  onChange: (key: TabKey) => void;
  labels: Record<TabKey, string>;
}) {
  const { palette, locale, rtl } = useTheme();
  const insets = useSafeAreaInsets();

  const keys: TabKey[] = ['today', 'sections', 'saved', 'settings'];

  return (
    <View
      style={[
        styles.bar,
        {
          flexDirection: rtl ? 'row-reverse' : 'row',
          backgroundColor: palette.surface,
          borderTopColor: palette.border,
          paddingBottom: insets.bottom || space.s2,
        },
      ]}
    >
      {keys.map((key) => {
        const on = key === active;
        return (
          <Pressable
            key={key}
            onPress={() => onChange(key)}
            accessibilityRole="tab"
            accessibilityState={{ selected: on }}
            accessibilityLabel={labels[key]}
            style={styles.tab}
          >
            <Text style={[styles.glyph, { color: on ? palette.accent : palette.text3 }]}>
              {GLYPH[key]}
            </Text>
            <Text
              style={[
                textStyle('label', locale),
                { color: on ? palette.accent : palette.text3, marginTop: 2 },
              ]}
              numberOfLines={1}
            >
              {locale === 'ar' ? labels[key] : labels[key].toUpperCase()}
            </Text>
          </Pressable>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  bar: {
    borderTopWidth: StyleSheet.hairlineWidth,
    paddingTop: space.s2,
  },
  tab: {
    flex: 1,
    alignItems: 'center',
    paddingVertical: space.s1,
  },
  glyph: {
    fontSize: 17,
    lineHeight: 20,
  },
});
