import React from 'react';
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  ListRenderItemInfo,
} from 'react-native';
import { StatusDot } from '../components/StatusDot';
import { useLiveFeed, FeedEvent } from '../hooks/useLiveFeed';

function formatTime(ts: string): string {
  try {
    const d = new Date(ts);
    return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  } catch {
    return ts;
  }
}

function EventRow({ item }: { item: FeedEvent }): React.JSX.Element {
  const savingColor =
    item.saving_pct !== null && item.saving_pct >= 50 ? '#22c55e' : '#c9cdd8';

  return (
    <View style={styles.row}>
      <Text style={styles.rowTime}>{formatTime(item.timestamp)}</Text>
      <Text style={styles.rowSkill} numberOfLines={1}>
        {item.skill_id ?? '—'}
      </Text>
      <Text style={[styles.rowSaving, { color: savingColor }]}>
        {item.saving_pct !== null ? `${item.saving_pct.toFixed(0)}%` : '—'}
      </Text>
      <Text style={styles.rowLatency}>
        {item.latency_ms !== null ? `${item.latency_ms}ms` : '—'}
      </Text>
    </View>
  );
}

function ListHeader(): React.JSX.Element {
  return (
    <View style={styles.tableHeader}>
      <Text style={styles.headerCell}>Time</Text>
      <Text style={styles.headerCell}>Skill</Text>
      <Text style={styles.headerCell}>Saved</Text>
      <Text style={styles.headerCell}>Latency</Text>
    </View>
  );
}

function EmptyState(): React.JSX.Element {
  return (
    <View style={styles.empty}>
      <Text style={styles.emptyIcon}>⏳</Text>
      <Text style={styles.emptyText}>Waiting for requests…</Text>
      <Text style={styles.emptySubtext}>
        Events will appear here as the proxy handles traffic.
      </Text>
    </View>
  );
}

export function LiveFeedScreen(): React.JSX.Element {
  const { events, connected } = useLiveFeed();

  return (
    <View style={styles.container}>
      {/* Status bar */}
      <View style={styles.statusBar}>
        <StatusDot connected={connected} />
        <Text style={styles.eventCount}>
          {events.length > 0 ? `${events.length} events` : 'No events yet'}
        </Text>
      </View>

      <FlatList<FeedEvent>
        data={events}
        keyExtractor={(item, index) => item.id ?? String(index)}
        renderItem={({ item }: ListRenderItemInfo<FeedEvent>) => (
          <EventRow item={item} />
        )}
        ListHeaderComponent={events.length > 0 ? <ListHeader /> : null}
        ListEmptyComponent={<EmptyState />}
        contentContainerStyle={events.length === 0 ? styles.emptyContainer : styles.listContent}
        showsVerticalScrollIndicator={false}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0f1117',
  },
  statusBar: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#2a2d3a',
    backgroundColor: '#1a1d27',
  },
  eventCount: {
    color: '#6b7280',
    fontSize: 12,
  },
  tableHeader: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderBottomWidth: 1,
    borderBottomColor: '#2a2d3a',
  },
  headerCell: {
    flex: 1,
    color: '#6b7280',
    fontSize: 10,
    textTransform: 'uppercase',
    letterSpacing: 0.6,
    fontWeight: '600',
  },
  listContent: {
    paddingBottom: 32,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#1a1d27',
  },
  rowTime: {
    flex: 1,
    color: '#6b7280',
    fontSize: 12,
    fontVariant: ['tabular-nums'],
  },
  rowSkill: {
    flex: 1,
    color: '#c9cdd8',
    fontSize: 12,
  },
  rowSaving: {
    flex: 1,
    fontSize: 13,
    fontWeight: '600',
  },
  rowLatency: {
    flex: 1,
    color: '#6b7280',
    fontSize: 12,
    textAlign: 'right',
  },
  emptyContainer: {
    flex: 1,
  },
  empty: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 80,
    gap: 8,
  },
  emptyIcon: {
    fontSize: 40,
    marginBottom: 8,
  },
  emptyText: {
    color: '#c9cdd8',
    fontSize: 16,
    fontWeight: '600',
  },
  emptySubtext: {
    color: '#6b7280',
    fontSize: 13,
    textAlign: 'center',
    paddingHorizontal: 32,
  },
});
