import { Alert, Pressable, StyleSheet, TextInput, View } from 'react-native';

import { Card } from '@/components/card';
import { PlayerAvatar } from '@/components/player-avatar';
import { SectionLabel } from '@/components/section-label';
import { Screen } from '@/components/screen';
import { ThemedText } from '@/components/themed-text';
import { useTheme } from '@/hooks/use-theme';
import { useStore } from '@/lib/store';
import type { ChaosLevel, PlayerId } from '@/lib/types';

const CHAOS_LEVELS: { value: ChaosLevel; label: string }[] = [
  { value: 'off', label: 'Off' },
  { value: 'mild', label: 'Mild' },
  { value: 'medium', label: 'Medium' },
  { value: 'spicy', label: 'Spicy' },
];

function PlayerEditor({ playerId }: { playerId: PlayerId }) {
  const theme = useTheme();
  const { state, actions } = useStore();
  const player = state.players[playerId];

  // Type locally, persist to the server when the field loses focus.
  const save = () => {
    actions.savePlayer(playerId).catch(() => {
      Alert.alert('Not saved', 'Could not reach the server — name change is local only.');
    });
  };

  return (
    <View style={styles.playerRow}>
      <PlayerAvatar playerId={playerId} initial={player.name.charAt(0) || '?'} size={34} />
      <View style={styles.playerFields}>
        <TextInput
          value={player.name}
          onChangeText={(name) => actions.patchPlayerLocal(playerId, { name })}
          onEndEditing={save}
          placeholder="Name"
          placeholderTextColor={theme.textSecondary}
          style={[styles.nameInput, { color: theme.text }]}
        />
        <TextInput
          value={player.alias}
          onChangeText={(alias) => actions.patchPlayerLocal(playerId, { alias })}
          onEndEditing={save}
          placeholder="Pseudonym (optional)"
          placeholderTextColor={theme.textSecondary}
          style={[styles.aliasInput, { color: theme.textSecondary }]}
        />
      </View>
    </View>
  );
}

function Segmented<T extends string>({
  options,
  value,
  onChange,
}: {
  options: { value: T; label: string }[];
  value: T;
  onChange: (next: T) => void;
}) {
  const theme = useTheme();
  return (
    <View style={[styles.segmented, { backgroundColor: theme.backgroundSelected }]}>
      {options.map((option) => {
        const selected = option.value === value;
        return (
          <Pressable
            key={option.value}
            onPress={() => onChange(option.value)}
            style={[
              styles.segment,
              selected && { backgroundColor: theme.backgroundElement },
            ]}>
            <ThemedText
              type="smallBold"
              style={{ color: selected ? theme.felt : theme.textSecondary, fontSize: 13 }}>
              {option.label}
            </ThemedText>
          </Pressable>
        );
      })}
    </View>
  );
}

export default function SettingsScreen() {
  const { state, actions } = useStore();
  const { players, settings } = state;

  const setChaos = (chaos: ChaosLevel) => {
    actions.setChaos(chaos).catch(() => {
      Alert.alert('Not saved', 'Could not reach the server — chaos level unchanged there.');
    });
  };

  return (
    <Screen title="Settings" subtitle="the fine print">
      <SectionLabel>Players</SectionLabel>
      <Card style={styles.playersCard}>
        <PlayerEditor playerId="p1" />
        <PlayerEditor playerId="p2" />
      </Card>

      <SectionLabel>This phone belongs to</SectionLabel>
      <Segmented
        options={[
          { value: 'p1', label: players.p1.name || 'Player 1' },
          { value: 'p2', label: players.p2.name || 'Player 2' },
        ]}
        value={settings.currentPlayerId}
        onChange={(playerId) => actions.setCurrentPlayer(playerId)}
      />

      <SectionLabel>Cheat-check</SectionLabel>
      <Card style={styles.chaosCard}>
        <ThemedText type="smallBold">Chaos level</ThemedText>
        <ThemedText type="small" themeColor="textSecondary">
          How often the app randomly demands the other player confirm a score.
        </ThemedText>
        <Segmented options={CHAOS_LEVELS} value={settings.chaos} onChange={setChaos} />
      </Card>

      <ThemedText type="small" themeColor="textSecondary" style={styles.footer}>
        Scores sync through your server. Device-to-device push needs a dev build (Expo Go can't
        receive remote push). AI-powered suspicion is next.
      </ThemedText>
    </Screen>
  );
}

const styles = StyleSheet.create({
  playersCard: { gap: 14 },
  playerRow: { flexDirection: 'row', alignItems: 'center', gap: 12 },
  playerFields: { flex: 1 },
  nameInput: { fontSize: 16, fontWeight: '700', paddingVertical: 2 },
  aliasInput: { fontSize: 13, paddingVertical: 2 },
  segmented: {
    flexDirection: 'row',
    borderRadius: 11,
    padding: 3,
  },
  segment: {
    flex: 1,
    borderRadius: 9,
    paddingVertical: 8,
    alignItems: 'center',
  },
  chaosCard: { gap: 8 },
  footer: { textAlign: 'center', marginTop: 12, paddingHorizontal: 12, fontSize: 12 },
});
