import { useQueryClient } from '@tanstack/react-query';
import * as ImageManipulator from 'expo-image-manipulator';
import * as ImagePicker from 'expo-image-picker';
import { Alert, Pressable, Text, View } from 'react-native';
import type { WorkOrderDetail } from '@siop/shared';
import { useDocumentsOT } from '@/api/exploitation';
import { Carte } from '@/composants/ui';
import { enfilerPhoto } from '@/file/actions';
import { useFile } from '@/file/store';
import { useTokens } from '@/theme/tokens';

/** Photos d'intervention (D5) : compressées côté app (~1 600 px) puis mises
 *  EN FILE comme le reste — rattachées à l'OT dans la bibliothèque R3.
 *  Ni audio ni géolocalisation en R4 (loi 09-08, minimisation). */
export function CartePhotos({ ot }: { ot: WorkOrderDetail }) {
  const t = useTokens();
  const queryClient = useQueryClient();
  const file = useFile();
  const { data: documents } = useDocumentsOT(ot.id);

  const photosServeur = (documents ?? []).filter((d) => d.contentType.startsWith('image/'));
  const photosEnFile = file.filter((s) => s.otId === ot.id && s.type === 'PHOTO');

  const prendre = async () => {
    const resultat = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      quality: 0.9,
    });
    const image = resultat.assets?.[0];
    if (!image) return;
    try {
      // Compression D5 : jamais un original de 12 Mo dans la file.
      const contexte = ImageManipulator.ImageManipulator.manipulate(image.uri);
      if (image.width > 1600) contexte.resize({ width: 1600 });
      const rendu = await contexte.renderAsync();
      const sauve = await rendu.saveAsync({
        compress: 0.7,
        format: ImageManipulator.SaveFormat.JPEG,
      });
      enfilerPhoto(queryClient, ot, {
        uri: sauve.uri,
        nom: `intervention-${ot.reference}-${Date.now().toString(36)}.jpg`,
        mime: 'image/jpeg',
      });
    } catch (e) {
      Alert.alert('Photo impossible', e instanceof Error ? e.message : 'Erreur inconnue');
    }
  };

  return (
    <Carte titre={`Photos (${photosServeur.length + photosEnFile.length})`}>
      <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 8 }}>
        {photosServeur.map((d) => (
          <View key={d.id} style={vignette(t.surface2, t.bordure)}>
            <Text style={{ fontSize: 18 }}>🖼</Text>
          </View>
        ))}
        {photosEnFile.map((s) => (
          <View key={s.id} style={vignette(t.stAttenteFond, t.stAttente)}>
            <Text style={{ fontSize: 18 }}>🖼</Text>
            <Text
              style={{
                position: 'absolute',
                bottom: 2,
                fontFamily: 'Manrope_800ExtraBold',
                fontSize: 8,
                color: t.stAttente,
              }}
            >
              en file
            </Text>
          </View>
        ))}
        <Pressable
          accessibilityRole="button"
          accessibilityLabel="Ajouter une photo"
          onPress={() => void prendre()}
          style={vignette('transparent', t.bordureForte, true)}
        >
          <Text style={{ fontSize: 22, color: t.primaire }}>+</Text>
        </Pressable>
      </View>
    </Carte>
  );
}

const vignette = (fond: string, bordure: string, pointille = false) =>
  ({
    width: 56,
    height: 56,
    borderRadius: 9,
    backgroundColor: fond,
    borderWidth: 1.5,
    borderColor: bordure,
    borderStyle: pointille ? ('dashed' as const) : ('solid' as const),
    alignItems: 'center' as const,
    justifyContent: 'center' as const,
  }) as const;
