import { useQueryClient } from '@tanstack/react-query';
import { useLocalSearchParams } from 'expo-router';
import { Pressable, ScrollView, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useWorkOrder } from '@/api/exploitation';
import { useHorsLigne } from '@/auth/session';
import { EnteteFiche } from '@/composants/ui';
import { enfilerCoche } from '@/file/actions';
import { useFile } from '@/file/store';
import { prochainEtat, progression } from '@/lib/checklist';
import { useTokens } from '@/theme/tokens';

/** Écran 6 de la maquette R4 : la grille au pouce. Appui simple = coche,
 *  appui long = non-applicable. Chaque coche part en file INDIVIDUELLEMENT
 *  (D1) : 7 coches faites = 7 coches sauvées, réseau ou pas. */
export default function PageGrille() {
  const t = useTokens();
  const horsLigne = useHorsLigne();
  const { id } = useLocalSearchParams<{ id: string }>();
  const { data: ot } = useWorkOrder(id);
  const queryClient = useQueryClient();
  const file = useFile();

  if (!ot) return null;
  const { faits, total, pct } = progression(ot.checklist);
  const enFile = new Set(
    file.flatMap((s) => (s.otId === ot.id && s.type === 'COCHE' ? [s.payload.itemId] : [])),
  );

  const basculer = (item: { id: string; label: string }, etat: Parameters<typeof prochainEtat>[0], versNA = false) => {
    enfilerCoche(
      queryClient,
      ot,
      item,
      versNA ? (etat === 'NA' ? 'PENDING' : 'NA') : prochainEtat(etat),
    );
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: t.fond }} edges={['top']}>
      <ScrollView contentContainerStyle={{ padding: 14, gap: 10 }}>
        <EnteteFiche
          titre={`Grille — ${ot.assetReference}`}
          apres={
            <Text style={{ fontFamily: 'Manrope_800ExtraBold', fontSize: 13, color: t.encre2 }}>
              {faits}/{total}
            </Text>
          }
        />
        <View style={{ height: 8, borderRadius: 999, backgroundColor: t.surface2, overflow: 'hidden' }}>
          <View
            style={{ width: `${Math.round(pct * 100)}%`, height: '100%', backgroundColor: t.succes }}
          />
        </View>
        {horsLigne ? (
          <View
            style={{
              backgroundColor: t.stAttenteFond,
              borderColor: t.stAttente,
              borderWidth: 1,
              borderRadius: 10,
              padding: 9,
            }}
          >
            <Text style={{ color: t.stAttente, fontFamily: 'Manrope_700Bold', fontSize: 12 }}>
              ⚠ Hors-ligne — chaque coche part en file et se synchronisera au retour du réseau.
            </Text>
          </View>
        ) : null}
        {ot.checklist.map((item) => (
          <Pressable
            key={item.id}
            accessibilityRole="checkbox"
            aria-checked={item.state === 'DONE'}
            accessibilityLabel={item.label}
            onPress={() => basculer(item, item.state)}
            onLongPress={() => basculer(item, item.state, true)}
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 10,
              backgroundColor: t.surface,
              borderColor: t.bordure,
              borderWidth: 1,
              borderRadius: 10,
              paddingHorizontal: 12,
              paddingVertical: 11,
            }}
          >
            <View
              style={{
                width: 22,
                height: 22,
                borderRadius: 6,
                borderWidth: 2,
                borderColor: item.state === 'DONE' ? t.succes : t.bordureForte,
                backgroundColor: item.state === 'DONE' ? t.succes : 'transparent',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              {item.state === 'DONE' ? (
                <Text style={{ color: '#fff', fontSize: 13, fontFamily: 'Manrope_800ExtraBold' }}>✓</Text>
              ) : item.state === 'NA' ? (
                <Text style={{ color: t.encre3, fontSize: 10, fontFamily: 'Manrope_800ExtraBold' }}>NA</Text>
              ) : null}
            </View>
            <Text
              style={{
                flex: 1,
                fontFamily: 'Manrope_600SemiBold',
                fontSize: 13,
                color: item.state === 'PENDING' ? t.encre : t.encre2,
              }}
            >
              {item.label}
            </Text>
            {enFile.has(item.id) ? (
              <Text
                style={{
                  fontFamily: 'Manrope_800ExtraBold',
                  fontSize: 9,
                  color: t.stAttente,
                  backgroundColor: t.stAttenteFond,
                  paddingHorizontal: 6,
                  borderRadius: 999,
                  overflow: 'hidden',
                }}
              >
                en file
              </Text>
            ) : item.doneBy ? (
              <Text style={{ fontFamily: 'Manrope_400Regular', fontSize: 10.5, color: t.encre3 }}>
                {item.doneBy.displayName.split(' ')[0]}
              </Text>
            ) : null}
          </Pressable>
        ))}
        <Text style={{ color: t.encre3, fontFamily: 'Manrope_400Regular', fontSize: 11.5 }}>
          Appui simple : cocher / décocher · appui long : non-applicable.
        </Text>
      </ScrollView>
    </SafeAreaView>
  );
}
