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

const fmt = new Intl.NumberFormat('fr-FR');

/** Stock — R6.3 (Ressources). Sous-seuil en tête, comme le web (stock.tsx) —
 *  ce qui demande une action passe avant le reste. */
export default function PageStock() {
  const t = useTokens();
  const { data: parts } = useParts();
  const pieces = [...(parts ?? [])].sort((a, b) => {
    if (a.belowThreshold !== b.belowThreshold) return a.belowThreshold ? -1 : 1;
    return a.designation.localeCompare(b.designation);
  });
  const sousSeuil = pieces.filter((p) => p.belowThreshold).length;

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: t.fond }} edges={['top']}>
      <View style={{ flex: 1, padding: 14, gap: 10 }}>
        <EnteteFiche
          titre="Stock & achats"
          apres={
            sousSeuil ? (
              <Text
                style={{
                  fontFamily: 'Manrope_800ExtraBold',
                  fontSize: 10.5,
                  color: t.danger,
                  backgroundColor: t.prioBloqueFond,
                  paddingHorizontal: 8,
                  paddingVertical: 2,
                  borderRadius: 999,
                }}
              >
                {sousSeuil} sous seuil
              </Text>
            ) : undefined
          }
        />
        <FlatList
          data={pieces}
          keyExtractor={(p) => p.id}
          contentContainerStyle={{ gap: 8, paddingBottom: 12 }}
          ListEmptyComponent={
            <Text style={{ color: t.encre3, fontFamily: 'Manrope_600SemiBold', padding: 16, textAlign: 'center' }}>
              Aucune pièce accessible.
            </Text>
          }
          renderItem={({ item: p }) => (
            <Pressable
              accessibilityRole="button"
              onPress={() => router.push(`/stock/${p.id}`)}
              style={{
                backgroundColor: t.surface,
                borderColor: p.belowThreshold ? t.danger : t.bordure,
                borderWidth: p.belowThreshold ? 1.5 : 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 }}>
                  {p.designation}
                </Text>
                <Text
                  style={{
                    fontFamily: 'Manrope_800ExtraBold',
                    fontSize: 13,
                    color: p.belowThreshold ? t.danger : t.encre,
                  }}
                >
                  {fmt.format(p.stock)}
                </Text>
              </View>
              <Text style={{ fontFamily: 'Manrope_400Regular', fontSize: 12, color: t.encre2 }}>
                {p.reference} · seuil {fmt.format(p.threshold)}
                {p.supplierName ? ` · ${p.supplierName}` : ''}
              </Text>
            </Pressable>
          )}
        />
      </View>
    </SafeAreaView>
  );
}
