import React, { useCallback, useState } from 'react';
import { RefreshControl, ScrollView, StyleSheet, Text, View } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { ps } from '@/api/client';
import { useTheme } from '@/theme/ThemeContext';
import type { ActiveSession, PastSession } from 'parksmarter-client';

export function SessionsScreen() {
  const { colors } = useTheme();
  const [active, setActive] = useState<ActiveSession[]>([]);
  const [past, setPast] = useState<PastSession[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    setRefreshing(true);
    try {
      const [a, p] = await Promise.all([
        ps.getActiveParkingSessions(),
        ps.getPastParkingSessions({ currentPage: 1, pageSize: 20 }),
      ]);
      setActive(a.ParkingSession ?? []);
      setPast(p.Session ?? []);
    } finally {
      setRefreshing(false);
    }
  }, []);

  useFocusEffect(
    useCallback(() => {
      void load();
    }, [load]),
  );

  return (
    <ScrollView
      style={{ backgroundColor: colors.bg }}
      contentContainerStyle={{ padding: 16 }}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={load} />}
    >
      <Text style={[styles.header, { color: colors.text }]}>Active</Text>
      {active.length === 0 ? (
        <Text style={[styles.empty, { color: colors.subtext }]}>No active sessions.</Text>
      ) : (
        active.map((s, i) => (
          <View key={i} style={[styles.card, { backgroundColor: colors.primary + '22' }]}>
            <Text style={[styles.zone, { color: colors.text }]}>{s.ZoneName ?? 'Session'}</Text>
            <Text style={[styles.meta, { color: colors.subtext }]}>
              {s.SpaceName ?? s.Space ?? ''} · ends {s.EndTimeDisplay ?? s.EndTime ?? ''}
            </Text>
          </View>
        ))
      )}

      <Text style={[styles.header, { color: colors.text, marginTop: 20 }]}>History</Text>
      {past.length === 0 ? (
        <Text style={[styles.empty, { color: colors.subtext }]}>No past sessions.</Text>
      ) : (
        past.map((s, i) => (
          <View key={i} style={[styles.card, { backgroundColor: colors.card }]}>
            <Text style={[styles.zone, { color: colors.text }]}>{s.ZoneName ?? 'Session'}</Text>
            <Text style={[styles.meta, { color: colors.subtext }]}>
              {s.StartTime ?? ''} · {s.Amount != null ? `$${s.Amount}` : ''}
            </Text>
          </View>
        ))
      )}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  header: { fontSize: 18, fontWeight: '700', marginBottom: 8 },
  empty: { marginBottom: 8 },
  card: { borderRadius: 10, padding: 14, marginBottom: 10 },
  zone: { fontSize: 16, fontWeight: '600' },
  meta: { fontSize: 13, marginTop: 2 },
});
