import React, { useState } from 'react';
import { View, Text, StyleSheet, useWindowDimensions, ScrollView } from 'react-native';
import { DeviceStatusBar } from '../../src/components/DeviceStatusBar';
import { WaveformChart } from '../../src/components/WaveformChart';
import { ChannelSelector } from '../../src/components/ChannelSelector';
import { useWaveform } from '../../src/hooks/useWaveform';
import { useDataStore } from '../../src/stores/dataStore';
import { useDeviceStore } from '../../src/stores/deviceStore';
import { formatUV, formatUtc, formatCoord } from '../../src/utils/format';

export default function WaveformScreen() {
  const { width } = useWindowDimensions();
  const channelNum = useDeviceStore((s) => s.config.channelNum);
  const [visible, setVisible] = useState(() => Array(6).fill(true));

  const frame = useDataStore((s) => s.currentFrame);
  const data = useWaveform(visible);

  const toggleChannel = (idx: number) => {
    setVisible((prev) => prev.map((v, i) => (i === idx ? !v : v)));
  };

  const CHART_HEIGHT = 280;

  return (
    <View style={styles.container}>
      <DeviceStatusBar />

      <ChannelSelector maxChannels={channelNum} visible={visible} onToggle={toggleChannel} />

      {/* Waveform chart */}
      <View style={styles.chartWrap}>
        {data ? (
          <WaveformChart
            data={data}
            visibleChannels={visible}
            width={width}
            height={CHART_HEIGHT}
          />
        ) : (
          <View style={[styles.placeholder, { height: CHART_HEIGHT }]}>
            <Text style={styles.placeholderText}>等待采样数据...</Text>
          </View>
        )}
      </View>

      {/* Channel peak values */}
      {frame && (
        <ScrollView style={styles.peakScroll}>
          <View style={styles.peakRow}>
            {frame.adcUV.map((ch, idx) => {
              if (!visible[idx] || idx >= channelNum) return null;
              const absMax = ch.reduce((mx, v) => Math.max(mx, Math.abs(v)), 0);
              const peak = ch[0] < 0 ? -absMax : absMax;
              return (
                <View key={idx} style={styles.peakCell}>
                  <Text style={styles.peakLabel}>CH{idx + 1}</Text>
                  <Text style={styles.peakValue}>{formatUV(absMax)}</Text>
                </View>
              );
            })}
          </View>

          {/* Frame metadata */}
          {frame.meta && (
            <View style={styles.metaBlock}>
              <Text style={styles.metaText}>
                帧 #{frame.frameId}  UTC: {formatUtc(frame.meta.utc)}
              </Text>
              <Text style={styles.metaText}>
                {formatCoord(frame.meta.latitude, false)}  {formatCoord(frame.meta.longitude, true)}  海拔 {frame.meta.altitude.toFixed(1)} m
              </Text>
              <Text style={styles.metaText}>
                Roll {frame.meta.roll.toFixed(1)}°  Pitch {frame.meta.pitch.toFixed(1)}°  Yaw {frame.meta.yaw.toFixed(1)}°
              </Text>
            </View>
          )}
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#0d0d0d' },
  chartWrap: { borderBottomWidth: 1, borderBottomColor: '#222' },
  placeholder: {
    backgroundColor: '#1a1a1a',
    justifyContent: 'center',
    alignItems: 'center',
  },
  placeholderText: { color: '#444', fontSize: 14 },
  peakScroll: { flex: 1 },
  peakRow: { flexDirection: 'row', flexWrap: 'wrap', padding: 12, gap: 10 },
  peakCell: {
    backgroundColor: '#1a1a1a',
    borderRadius: 8,
    padding: 10,
    minWidth: 90,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#2a2a2a',
  },
  peakLabel: { color: '#888', fontSize: 11 },
  peakValue: { color: '#eee', fontSize: 13, fontWeight: '600', marginTop: 2, fontFamily: 'monospace' },
  metaBlock: {
    margin: 12,
    backgroundColor: '#111',
    borderRadius: 8,
    padding: 10,
    gap: 3,
  },
  metaText: { color: '#555', fontSize: 10, fontFamily: 'monospace' },
});
