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

import { SectionLabel } from '@/components/section-label';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { MaxContentWidth, Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { useStore } from '@/lib/store';
import type { ScoringMode } from '@/lib/types';

export default function AddGameScreen() {
  const theme = useTheme();
  const { actions } = useStore();
  const [name, setName] = useState('');
  const [emoji, setEmoji] = useState('');
  const [scoring, setScoring] = useState<ScoringMode>('highWins');
  const [saving, setSaving] = useState(false);

  const save = async () => {
    if (!name.trim() || saving) return;
    setSaving(true);
    try {
      await actions.addGame(name.trim(), emoji.trim(), scoring);
      router.back();
    } catch (err) {
      Alert.alert('Could not add game', err instanceof Error ? err.message : 'Server unreachable.');
      setSaving(false);
    }
  };

  const inputStyle = [
    styles.input,
    { color: theme.text, backgroundColor: theme.backgroundElement, borderColor: theme.border },
  ];

  return (
    <ThemedView style={styles.container}>
      <View style={styles.content}>
        <SectionLabel>Name</SectionLabel>
        <TextInput
          value={name}
          onChangeText={setName}
          placeholder="Yahtzee, darts, mini golf…"
          placeholderTextColor={theme.textSecondary}
          autoFocus
          style={inputStyle}
        />

        <SectionLabel>Emoji</SectionLabel>
        <TextInput
          value={emoji}
          onChangeText={setEmoji}
          placeholder="🎯 (optional)"
          placeholderTextColor={theme.textSecondary}
          style={inputStyle}
        />

        <SectionLabel>Who wins</SectionLabel>
        <View style={[styles.segmented, { backgroundColor: theme.backgroundSelected }]}>
          {(
            [
              { value: 'highWins', label: 'Highest score' },
              { value: 'lowWins', label: 'Lowest score' },
            ] as const
          ).map((option) => {
            const selected = scoring === option.value;
            return (
              <Pressable
                key={option.value}
                onPress={() => setScoring(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>
        <ThemedText type="small" themeColor="textSecondary" style={styles.tip}>
          Five Crowns and golf are “lowest score” games. Win/loss-only games like Jenga work as
          1–0.
        </ThemedText>

        <Pressable
          onPress={save}
          disabled={!name.trim() || saving}
          style={({ pressed }) => [
            styles.saveBtn,
            { backgroundColor: name.trim() ? theme.felt : theme.backgroundSelected },
            pressed && { opacity: 0.8 },
          ]}>
          <ThemedText
            style={[styles.saveText, { color: name.trim() ? '#FFFFFF' : theme.textSecondary }]}>
            Add game
          </ThemedText>
        </Pressable>
      </View>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  content: {
    width: '100%',
    maxWidth: MaxContentWidth,
    alignSelf: 'center',
    padding: Spacing.three,
    gap: Spacing.one,
  },
  input: {
    borderWidth: 1.5,
    borderRadius: 11,
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 15,
  },
  segmented: { flexDirection: 'row', borderRadius: 11, padding: 3 },
  segment: { flex: 1, borderRadius: 9, paddingVertical: 8, alignItems: 'center' },
  tip: { marginHorizontal: 4, fontSize: 12 },
  saveBtn: {
    borderRadius: 13,
    paddingVertical: 14,
    alignItems: 'center',
    marginTop: Spacing.three,
  },
  saveText: { fontWeight: '800', fontSize: 15 },
});
