import type { ReactNode } from 'react';
import { ScrollView, StyleSheet, Text, View } from 'react-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 { COLORI, Contatore, FONT, Pulsante, Riquadro, SceltaStile, Sfondo, testi } 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 inizia = async () => {
    // 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);
    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} meno={() => setImp(togliGiocatore(imp))} piu={() => setImp(aggiungiGiocatore(imp))} />
          </Riga>
          <Riga etichetta={t('config.spie')}>
            <Text style={testi.grande}>{spiePer(imp.giocatori)}</Text>
          </Riga>
          <Riga etichetta={t('config.minuti')}>
            <Contatore valore={imp.minuti} meno={() => setImp(togliMinuto(imp))} piu={() => setImp(aggiungiMinuto(imp))} />
          </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 },
  coppia: { flexDirection: 'row', gap: 12 },
  meta: { flex: 1 },
});
