import { useState, type ReactElement } from 'react';
import { FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import { Image } from 'expo-image';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { LUOGHI } from '../gioco.ts';
import { FOTO_LUOGHI } from '../immagini.ts';
import { nomeLuogo } from '../testi/index.ts';
import { FONT, vibra } from './componenti.tsx';
import { useStato } from './stato.tsx';

const SPAZIO = 4;

/**
 * I luoghi con foto e nome: 3 colonne sul telefono, 5 dai 600 punti in su.
 * Quelli bloccati (versione gratis) sono scuri, col lucchetto, e portano allo sblocco.
 */
export function GrigliaLuoghi({
  luoghi = LUOGHI, onScegli, bloccato, onBloccato, intestazione,
}: {
  luoghi?: readonly number[];
  onScegli?: (id: number) => void;
  bloccato?: (id: number) => boolean;
  onBloccato?: () => void;
  intestazione?: ReactElement;
}) {
  const { lingua, imp } = useStato();
  const insets = useSafeAreaInsets();
  const [larghezza, setLarghezza] = useState(0);
  const colonne = larghezza >= 600 ? 5 : 3;
  const lato = larghezza > 0 ? (larghezza - SPAZIO * (colonne + 1)) / colonne : 0;

  return (
    <View style={st.pieno} onLayout={(e) => setLarghezza(e.nativeEvent.layout.width)}>
      {lato > 0 && (
        <FlatList
          key={colonne}
          data={luoghi}
          ListHeaderComponent={intestazione}
          numColumns={colonne}
          keyExtractor={(id) => String(id)}
          contentContainerStyle={{ padding: SPAZIO / 2, paddingBottom: SPAZIO / 2 + insets.bottom }}
          renderItem={({ item: id }) => {
            const chiuso = bloccato?.(id) ?? false;
            const azione = chiuso ? onBloccato : onScegli && (() => onScegli(id));
            return (
              <Pressable
                disabled={!azione}
                accessibilityRole={azione ? 'button' : undefined}
                accessibilityLabel={nomeLuogo(lingua, id)}
                accessibilityState={{ disabled: chiuso }}
                onPress={() => {
                  vibra();
                  azione?.();
                }}
                style={({ pressed }) => [{ width: lato, margin: SPAZIO / 2 }, pressed && st.premuto]}
              >
                <View>
                  <Image source={FOTO_LUOGHI[imp.stile][id]} style={{ width: lato, height: (lato * 3) / 4 }} contentFit="cover" />
                  {chiuso && (
                    <View style={st.velo}>
                      <Text style={st.lucchetto}>🔒</Text>
                    </View>
                  )}
                </View>
                <Text style={[st.nome, chiuso && st.nomeChiuso]} numberOfLines={1} adjustsFontSizeToFit>
                  {nomeLuogo(lingua, id)}
                </Text>
              </Pressable>
            );
          }}
        />
      )}
    </View>
  );
}

const st = StyleSheet.create({
  pieno: { flex: 1 },
  premuto: { opacity: 0.6 },
  nome: { fontFamily: FONT, fontSize: 15, color: '#FFFFFF', textAlign: 'center', paddingVertical: 4 },
  nomeChiuso: { color: '#8A9099' },
  velo: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.6)', alignItems: 'center', justifyContent: 'center' },
  lucchetto: { fontSize: 26 },
});
