import React, { useCallback, useState } from 'react';
import { FlatList, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { ps } from '@/api/client';
import { useTheme } from '@/theme/ThemeContext';
import {
  listKiosks,
  removeKiosk,
  shareKiosk,
  type SavedKiosk,
} from '@/features/favorites/favoritesStore';
import type { RootStackParamList } from '@/navigation/RootNavigator';

type Nav = NativeStackNavigationProp<RootStackParamList>;

export function FavoritesScreen() {
  const navigation = useNavigation<Nav>();
  const { colors } = useTheme();
  const [items, setItems] = useState<SavedKiosk[]>([]);

  useFocusEffect(
    useCallback(() => {
      void listKiosks().then(setItems);
    }, []),
  );

  const open = async (k: SavedKiosk) => {
    // Re-fetch the live zone (rates/occupancy change) before showing detail.
    const res = k.scannerCode
      ? await ps.getMetersByScannerCode(k.scannerCode)
      : k.terminalSerNo
        ? await ps.getMetersBySerialNumber(k.terminalSerNo)
        : null;
    const zone = res?.Zones?.[0];
    if (zone) navigation.navigate('MeterDetail', { zone });
  };

  const remove = async (k: SavedKiosk) => setItems(await removeKiosk(k.key));

  return (
    <FlatList
      style={{ backgroundColor: colors.bg }}
      contentContainerStyle={{ padding: 16 }}
      data={items}
      keyExtractor={(k) => k.key}
      ListEmptyComponent={
        <Text style={[styles.empty, { color: colors.subtext }]}>
          No saved kiosks yet. Scan a kiosk QR and tap “Save kiosk”.
        </Text>
      }
      renderItem={({ item }) => (
        <View style={[styles.card, { backgroundColor: colors.card }]}>
          <TouchableOpacity style={{ flex: 1 }} onPress={() => open(item)}>
            <Text style={[styles.name, { color: colors.text }]}>{item.zoneName ?? item.key}</Text>
            <Text style={[styles.meta, { color: colors.subtext }]}>
              {item.scannerCode ? `Code ${item.scannerCode}` : `Serial ${item.terminalSerNo}`}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.action} onPress={() => shareKiosk(item)}>
            <Text style={[styles.actionText, { color: colors.primary }]}>Share</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.action} onPress={() => remove(item)}>
            <Text style={[styles.actionText, { color: colors.danger }]}>Remove</Text>
          </TouchableOpacity>
        </View>
      )}
    />
  );
}

const styles = StyleSheet.create({
  empty: { textAlign: 'center', marginTop: 48 },
  card: {
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: 10,
    padding: 14,
    marginBottom: 10,
    gap: 10,
  },
  name: { fontSize: 16, fontWeight: '600' },
  meta: { fontSize: 12, marginTop: 2 },
  action: { paddingHorizontal: 6, paddingVertical: 4 },
  actionText: { fontWeight: '600' },
});
