import { router } from 'expo-router';
import { FlatList, Pressable, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useLocations } from '@/api/exploitation';
import { EnteteFiche } from '@/composants/ui';
import { useTokens } from '@/theme/tokens';

/** Sites — R6.2 (Parc). Liste plate → sites de premier niveau seulement
 *  (une zone n'a jamais de fiche propre, elle suit son site — même règle
 *  que le web, sites.tsx). */
export default function PageSites() {
  const t = useTokens();
  const { data: locations } = useLocations();
  const sites = (locations ?? []).filter((l) => l.parentId === null);

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: t.fond }} edges={['top']}>
      <View style={{ flex: 1, padding: 14, gap: 10 }}>
        <EnteteFiche titre="Sites" />
        <FlatList
          data={sites}
          keyExtractor={(s) => s.id}
          contentContainerStyle={{ gap: 8, paddingBottom: 12 }}
          ListEmptyComponent={
            <Text style={{ color: t.encre3, fontFamily: 'Manrope_600SemiBold', padding: 16, textAlign: 'center' }}>
              Aucun site accessible.
            </Text>
          }
          renderItem={({ item: s }) => (
            <Pressable
              accessibilityRole="button"
              onPress={() => router.push(`/sites/${s.id}`)}
              style={{
                backgroundColor: t.surface,
                borderColor: t.bordure,
                borderWidth: 1,
                borderRadius: 12,
                padding: 12,
                gap: 2,
              }}
            >
              <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
                <Text style={{ flex: 1, fontFamily: 'Manrope_700Bold', fontSize: 14, color: t.encre }}>
                  {s.name}
                </Text>
                <Text
                  style={{
                    fontFamily: 'Manrope_700Bold',
                    fontSize: 10.5,
                    color: t.encre2,
                    backgroundColor: t.surface2,
                    paddingHorizontal: 8,
                    paddingVertical: 2,
                    borderRadius: 999,
                  }}
                >
                  {s.assetCount} appareil{s.assetCount > 1 ? 's' : ''}
                </Text>
              </View>
              <Text style={{ fontFamily: 'Manrope_400Regular', fontSize: 12, color: t.encre2 }}>
                {[s.address, s.city].filter(Boolean).join(' — ') || '—'}
              </Text>
            </Pressable>
          )}
        />
      </View>
    </SafeAreaView>
  );
}
