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

import {
  aggiungiGiocatore, aggiungiMinuto, nuovaPartita, spiePer, togliGiocatore, togliMinuto,
} from '../../gioco.ts';
import { preparaNotifiche } from '../../notifica.ts';
import { useAcquisti } from '../acquisti.tsx';
import { COLORI, Contatore, FONT, Pulsante, Riquadro, SceltaStile, Sfondo, testi, vibra } from '../componenti.tsx';
import type { Schermate } from '../navigazione.ts';
import { useStato } from '../stato.tsx';

export function Impostazioni({ navigation }: NativeStackScreenProps<Schermate, 'Impostazioni'>) {
  const { t, imp, setImp, recenti, setRecenti, setPartita } = useStato();
  const { sbloccato } = useAcquisti();
  // Evita che un doppio tap su "Inizia" faccia partire due partite.
  const inCorso = useRef(false);
  useFocusEffect(useCallback(() => { inCorso.current = false; }, []));

  const inizia = async () => {
    if (inCorso.current) return;
    inCorso.current = true;
    // Il permesso si chiede qui, alla prima partita, e non all'apertura dell'app.
    await preparaNotifiche(t('notifica.canale')).catch(() => {});
    const r = nuovaPartita(imp, recenti, Math.random, sbloccato);
    setPartita(r.partita);
    setRecenti(r.recenti);
    navigation.navigate('Giro');
  };

  return (
    <Sfondo>
      <ScrollView contentContainerStyle={st.lista} showsVerticalScrollIndicator={false}>
        <Riquadro>
          <Text style={testi.desc}>{t('config.desc')}</Text>
        </Riquadro>
        <Riquadro style={st.config}>
          <Riga etichetta={t('config.giocatori')}>
            <Contatore
              valore={imp.giocatori}
              etichetta={t('config.giocatori')}
              meno={() => setImp((prev) => togliGiocatore(prev))}
              piu={() => setImp((prev) => aggiungiGiocatore(prev))}
            />
          </Riga>
          <Riga etichetta={t('config.spie')}>
            <Text style={testi.grande}>{spiePer(imp.giocatori)}</Text>
          </Riga>
          <Riga etichetta={t('config.minuti')}>
            <Contatore
              valore={imp.minuti}
              etichetta={t('config.minuti')}
              meno={() => setImp((prev) => togliMinuto(prev))}
              piu={() => setImp((prev) => aggiungiMinuto(prev))}
            />
          </Riga>
          <Riga etichetta={t('config.ruoli')}>
            {sbloccato ? (
              <View style={st.scelta}>
                {[true, false].map((v) => (
                  <Pressable
                    key={String(v)}
                    accessibilityRole="button"
                    accessibilityState={{ selected: imp.ruoli === v }}
                    hitSlop={12}
                    onPress={() => {
                      vibra();
                      setImp((prev) => ({ ...prev, ruoli: v }));
                    }}
                  >
                    <Text style={[st.opzione, { color: imp.ruoli === v ? COLORI.arancio : COLORI.spento }]}>
                      {t(v ? 'config.si' : 'config.no')}
                    </Text>
                  </Pressable>
                ))}
              </View>
            ) : (
              <Pressable accessibilityRole="button" hitSlop={12} onPress={() => { vibra(); navigation.navigate('Sblocca'); }}>
                <Text style={[st.opzione, { color: COLORI.arancio }]}>{t('config.bloccato')}</Text>
              </Pressable>
            )}
          </Riga>
          <Riga etichetta={t('config.stile')}>
            <SceltaStile />
          </Riga>
        </Riquadro>
      </ScrollView>
      <Pulsante titolo={t('config.inizia')} onPress={inizia} />
      <View style={st.coppia}>
        <Pulsante style={st.meta} titolo={t('config.luoghi')} suono="page" onPress={() => navigation.navigate('Luoghi')} />
        <Pulsante style={st.meta} titolo={t('config.regole')} suono="page" onPress={() => navigation.navigate('Regole')} />
      </View>
    </Sfondo>
  );
}

function Riga({ etichetta, children }: { etichetta: string; children: ReactNode }) {
  return (
    <View style={st.riga}>
      <Text style={st.etichetta}>{etichetta}</Text>
      {children}
    </View>
  );
}

const st = StyleSheet.create({
  lista: { gap: 12, flexGrow: 1, justifyContent: 'center' },
  config: { gap: 16 },
  riga: { alignItems: 'center', gap: 6 },
  etichetta: { fontFamily: FONT, fontSize: 20, color: COLORI.bluScuro },
  scelta: { flexDirection: 'row', justifyContent: 'center', gap: 24 },
  opzione: { fontFamily: FONT, fontSize: 20 },
  coppia: { flexDirection: 'row', gap: 12 },
  meta: { flex: 1 },
});
