import React from 'react';
import {Pressable, ScrollView, StyleSheet, Text, View} from 'react-native';
import {Colors, PlatformMeta} from '@app/theme/colors';
import type {PlatformKey} from '@app/config';

export type TabKey = 'all' | PlatformKey;

type Props = {
  active: TabKey;
  onChange: (k: TabKey) => void;
  /** プラットフォーム別の件数。0件のタブは薄く表示する */
  counts: Record<PlatformKey, number>;
};

export const PlatformTabs: React.FC<Props> = ({active, onChange, counts}) => {
  const total = Object.values(counts).reduce((a, b) => a + b, 0);

  const renderTab = (key: TabKey, label: string, count: number, color?: string) => {
    const isActive = active === key;
    const isEmpty = count === 0;
    return (
      <Pressable
        key={key}
        onPress={() => onChange(key)}
        style={[
          styles.tab,
          isActive && {borderColor: color ?? Colors.primary, backgroundColor: color ?? Colors.primary},
          isEmpty && !isActive && styles.tabEmpty,
        ]}
      >
        <Text style={[styles.tabText, isActive && styles.tabTextActive]} numberOfLines={1}>
          {label} <Text style={styles.count}>{count}</Text>
        </Text>
      </Pressable>
    );
  };

  return (
    <View style={styles.wrap}>
      <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.row}>
        {renderTab('all', '全件', total)}
        {(Object.keys(PlatformMeta) as PlatformKey[]).map(k =>
          renderTab(k, PlatformMeta[k].label, counts[k] ?? 0, PlatformMeta[k].color),
        )}
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  wrap: {
    backgroundColor: Colors.card,
    borderBottomWidth: 1,
    borderBottomColor: Colors.border,
  },
  row: {paddingHorizontal: 8, paddingVertical: 8, gap: 8},
  tab: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 999,
    borderWidth: 1,
    borderColor: Colors.border,
    backgroundColor: Colors.card,
  },
  tabEmpty: {opacity: 0.4},
  tabText: {color: Colors.text, fontSize: 13, fontWeight: '500'},
  tabTextActive: {color: '#FFFFFF', fontWeight: '700'},
  count: {fontSize: 11, fontWeight: '400', opacity: 0.9},
});
