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

import { Card } from '@/components/card';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { Fonts, MaxContentWidth, Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { useStore } from '@/lib/store';

export default function DisputeScreen() {
  const theme = useTheme();
  const { matchId } = useLocalSearchParams<{ matchId: string }>();
  const { state, actions } = useStore();
  const [statement, setStatement] = useState('');
  const [filing, setFiling] = useState(false);

  const match = state.matches.find((m) => m.id === matchId);
  const game = match && state.games.find((g) => g.id === match.gameId);

  if (!match || !game) {
    return (
      <ThemedView style={styles.missing}>
        <ThemedText themeColor="textSecondary">Match not found.</ThemedText>
      </ThemedView>
    );
  }

  const winner = match.winnerId ? state.players[match.winnerId] : null;
  const canFile = statement.trim().length >= 10 && !filing;

  const file = async () => {
    if (filing) return;
    setFiling(true);
    try {
      await actions.fileDispute(match.id, statement);
      router.back();
    } catch (err) {
      Alert.alert(
        'Could not file',
        err instanceof Error ? err.message : 'Server unreachable. Your grievance remains unheard.',
      );
      setFiling(false);
    }
  };

  return (
    <ThemedView style={styles.container}>
      <View style={styles.content}>
        <ThemedText style={styles.flag}>🚩</ThemedText>
        <ThemedText style={styles.title}>Care to dispute?</ThemedText>
        <Card>
          <ThemedText type="small">
            {game.emoji} {game.name} ·{' '}
            <ThemedText type="smallBold" style={styles.mono}>
              {match.scores.p1}–{match.scores.p2}
            </ThemedText>
            {winner ? ` · ${winner.name} claims victory` : ' · a tie, allegedly'}
          </ThemedText>
        </Card>
        <ThemedText type="small" themeColor="textSecondary" style={styles.explain}>
          Disputes require a written statement, for the record. It will be saved forever and may
          be read aloud at future game nights.
        </ThemedText>
        <TextInput
          value={statement}
          onChangeText={setStatement}
          placeholder="He counted his crib twice. I watched him do it. I have witnesses (the cat)."
          placeholderTextColor={theme.textSecondary}
          multiline
          autoFocus
          style={[
            styles.statement,
            {
              color: theme.text,
              backgroundColor: theme.backgroundElement,
              borderColor: theme.border,
            },
          ]}
        />
        <View style={styles.btnRow}>
          <Pressable
            onPress={() => router.back()}
            style={({ pressed }) => [
              styles.ghostBtn,
              { borderColor: theme.border },
              pressed && { opacity: 0.6 },
            ]}>
            <ThemedText type="smallBold" themeColor="textSecondary">
              Fine, it stands
            </ThemedText>
          </Pressable>
          <Pressable
            onPress={file}
            disabled={!canFile}
            style={({ pressed }) => [
              styles.fileBtn,
              { backgroundColor: canFile ? theme.danger : theme.backgroundSelected },
              pressed && { opacity: 0.8 },
            ]}>
            <ThemedText
              type="smallBold"
              style={{ color: canFile ? '#FFFFFF' : theme.textSecondary }}>
              File dispute
            </ThemedText>
          </Pressable>
        </View>
      </View>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  missing: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  content: {
    width: '100%',
    maxWidth: MaxContentWidth,
    alignSelf: 'center',
    padding: Spacing.three,
    gap: Spacing.two,
  },
  flag: { fontSize: 30 },
  title: { fontSize: 22, fontWeight: '800' },
  mono: { fontFamily: Fonts?.mono },
  explain: { fontSize: 12 },
  statement: {
    borderWidth: 1.5,
    borderRadius: 11,
    padding: 12,
    minHeight: 90,
    fontSize: 14,
    textAlignVertical: 'top',
  },
  btnRow: { flexDirection: 'row', gap: 8 },
  ghostBtn: {
    flex: 1,
    borderWidth: 1.5,
    borderRadius: 11,
    paddingVertical: 12,
    alignItems: 'center',
  },
  fileBtn: {
    flex: 1,
    borderRadius: 11,
    paddingVertical: 12,
    alignItems: 'center',
  },
});
