import { useRef, useState } from 'react';
import { FlatList, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';

import type { Chiave } from '../../testi/index.ts';
import { COLORI, FONT, FONT_TESTO, Pulsante, Riquadro, Sfondo } from '../componenti.tsx';
import type { Schermate } from '../navigazione.ts';
import { useStato } from '../stato.tsx';

/** Le cinque pagine della 1.5, con i loro paragrafi. */
const PAGINE: { titolo?: Chiave; testo: Chiave }[][] = [
  [
    { testo: 'regole.p1.txt1' },
    { titolo: 'regole.p1.tit1', testo: 'regole.p1.txt2' },
    { titolo: 'regole.p1.tit2', testo: 'regole.p1.txt3' },
  ],
  [
    { titolo: 'regole.p2.tit1', testo: 'regole.p2.txt1' },
    { titolo: 'regole.p2.tit2', testo: 'regole.p2.txt2' },
  ],
  [{ titolo: 'regole.p3.tit1', testo: 'regole.p3.txt1' }],
  [{ titolo: 'regole.p4.tit1', testo: 'regole.p4.txt1' }],
  [{ titolo: 'regole.p5.tit1', testo: 'regole.p5.txt1' }],
];

export function Regole({ navigation }: NativeStackScreenProps<Schermate, 'Regole'>) {
  const { t } = useStato();
  const lista = useRef<FlatList<(typeof PAGINE)[number]>>(null);
  const [pagina, setPagina] = useState(0);
  const [larghezza, setLarghezza] = useState(0);
  const ultima = pagina === PAGINE.length - 1;

  const vai = (p: number) => {
    lista.current?.scrollToIndex({ index: p, animated: true });
    setPagina(p);
  };

  return (
    <Sfondo>
      <View style={st.pieno} onLayout={(e) => setLarghezza(e.nativeEvent.layout.width)}>
        {larghezza > 0 && (
          <FlatList
            ref={lista}
            data={PAGINE}
            horizontal
            pagingEnabled
            showsHorizontalScrollIndicator={false}
            keyExtractor={(_, i) => String(i)}
            getItemLayout={(_, i) => ({ length: larghezza, offset: larghezza * i, index: i })}
            onMomentumScrollEnd={(e) => setPagina(Math.round(e.nativeEvent.contentOffset.x / larghezza))}
            renderItem={({ item }) => (
              <ScrollView style={{ width: larghezza }} contentContainerStyle={st.pagina}>
                <Riquadro style={st.riquadro}>
                  {item.map((p) => (
                    <View key={p.testo} style={st.paragrafo}>
                      {p.titolo && <Text style={st.titolo}>{t(p.titolo)}</Text>}
                      <Text style={st.testo}>{t(p.testo)}</Text>
                    </View>
                  ))}
                </Riquadro>
              </ScrollView>
            )}
          />
        )}
      </View>
      <View style={st.punti}>
        {PAGINE.map((_, i) => (
          <View key={i} style={[st.punto, i === pagina && st.puntoAttivo]} />
        ))}
      </View>
      <View style={st.coppia}>
        {pagina > 0 && <Pulsante style={st.meta} titolo={t('regole.indietro')} suono="page" onPress={() => vai(pagina - 1)} />}
        <Pulsante
          style={st.meta}
          titolo={ultima ? t('regole.chiudi') : t('regole.avanti')}
          suono="page"
          onPress={() => (ultima ? navigation.goBack() : vai(pagina + 1))}
        />
      </View>
    </Sfondo>
  );
}

const st = StyleSheet.create({
  pieno: { flex: 1 },
  pagina: { paddingBottom: 8 },
  riquadro: { gap: 14 },
  paragrafo: { gap: 4 },
  titolo: { fontFamily: FONT, fontSize: 24, color: COLORI.blu },
  testo: { fontFamily: FONT_TESTO, fontSize: 19, lineHeight: 25, color: COLORI.bluScuro },
  punti: { flexDirection: 'row', justifyContent: 'center', gap: 8 },
  punto: { width: 8, height: 8, borderRadius: 4, backgroundColor: COLORI.spento },
  puntoAttivo: { backgroundColor: COLORI.arancio },
  coppia: { flexDirection: 'row', gap: 12 },
  meta: { flex: 1 },
});
