import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Platform } from 'react-native';
import { useConnectionStore } from '../../stores/connectionStore';
import { useDeviceStore } from '../../stores/deviceStore';
import { useDataStore } from '../../stores/dataStore';
import { formatBattery, formatTemperature } from '../../utils/format';
import { useTheme, type ThemeColors } from '../../design/tokens';

function Pill({
  label,
  value,
  color,
  theme,
  onPress,
}: {
  label: string;
  value: string;
  color: string;
  theme: ThemeColors;
  onPress?: () => void;
}) {
  const inner = (
    <View style={[styles.pill, { backgroundColor: theme.bg.raised, borderColor: color + '44' }]}>
      <View style={[styles.dot, { backgroundColor: color }]} />
      <Text style={[styles.pillLabel, { color: theme.text.ghost }]}>{label}</Text>
      <Text style={[styles.pillValue, { color }]}>{value}</Text>
    </View>
  );
  if (onPress) return <TouchableOpacity onPress={onPress} activeOpacity={0.7}>{inner}</TouchableOpacity>;
  return inner;
}

export function GlobalStatusBar() {
  const theme = useTheme();
  const { status, showModal }       = useConnectionStore();
  const { deviceStatus, batteryVolt, temperature, gpsStatus, sdStatus } = useDeviceStore();
  const frame = useDataStore((s) => s.currentFrame);
  const meta  = frame?.meta;

  const connected   = status === 'connected';
  const connColor   = connected ? theme.green.fg : status === 'connecting' ? theme.amber.fg : theme.text.ghost;
  const connLabel   = connected ? '已连接' : status === 'connecting' ? '连接中' : status === 'reconnecting' ? '重连' : '未连接';

  const hasGps      = gpsStatus > 0 || (meta?.gpsStatus ?? 0) > 0;
  const hasSd       = sdStatus === 0;

  const running     = deviceStatus === 'running';
  const single      = deviceStatus === 'single';
  const stateColor  = running ? theme.green.fg : single ? theme.teal.fg : theme.text.ghost;
  const stateLabel  = running ? '● 运行' : single ? '◎ 单次' : '○ 停止';

  return (
    <View style={[styles.bar, { backgroundColor: theme.bg.void, borderBottomColor: theme.bg.border }]}>
      {/* Connection — tappable */}
      <Pill label="TCP" value={connLabel} color={connColor} theme={theme} onPress={showModal} />

      {/* Device run state */}
      {connected && (
        <View style={[styles.pill, { backgroundColor: theme.bg.raised, borderColor: stateColor + '44' }]}>
          <Text style={[styles.stateText, { color: stateColor }]}>{stateLabel}</Text>
        </View>
      )}

      {/* GPS */}
      <Pill label="GPS" value={hasGps ? '定位' : '--'} color={hasGps ? theme.green.fg : theme.text.ghost} theme={theme} />

      {/* SD */}
      <Pill label="SD" value={hasSd ? 'OK' : '--'} color={hasSd ? theme.blue.fg : theme.text.ghost} theme={theme} />

      {/* Battery */}
      {batteryVolt > 0 && (
        <Pill label="电量" value={formatBattery(batteryVolt)} color={theme.text.muted} theme={theme} />
      )}

      {/* Temperature */}
      {temperature > 0 && (
        <Pill label="温度" value={formatTemperature(temperature)} color={theme.text.muted} theme={theme} />
      )}

      {/* Frame counter — right-aligned */}
      {frame && (
        <View style={styles.frameCount}>
          <Text style={[styles.frameCountText, { color: theme.text.ghost }]}>#{frame.frameId}</Text>
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  bar: {
    flexDirection:   'row',
    paddingHorizontal: 10,
    paddingVertical: 7,
    alignItems:      'center',
    flexWrap:        'wrap',
    gap:             5,
    borderBottomWidth: 1,
  },
  pill: {
    flexDirection:   'row',
    alignItems:      'center',
    gap:             4,
    borderRadius:    5,
    borderWidth:     1,
    paddingHorizontal: 6,
    paddingVertical: 2,
  },
  dot:        { width: 5, height: 5, borderRadius: 3 },
  pillLabel:  { fontSize: 9, fontWeight: '600', letterSpacing: 0.5 },
  pillValue:  { fontSize: 9, fontWeight: '700', fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace' },
  stateText:  { fontSize: 10, fontWeight: '700', letterSpacing: 0.3 },
  frameCount: { marginLeft: 'auto' as any },
  frameCountText: {
    fontSize: 10,
    fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace',
  },
});
