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

import { Card } from '@/components/card';
import { Screen } from '@/components/screen';
import { ThemedText } from '@/components/themed-text';
import { Fonts, Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { relativeDay } from '@/lib/format';
import { useStore } from '@/lib/store';
import type { Match } from '@/lib/types';

function DisputeBlock({ match }: { match: Match }) {
  const theme = useTheme();
  const { state, actions } = useStore();
  if (!match.dispute) return null;
  const filer = state.players[match.dispute.filedBy];

  const resolve = (status: 'score-stands' | 'overturned') => {
    actions.resolveDispute(match.id, status).catch((err) => {
      Alert.alert('Could not resolve', err instanceof Error ? err.message : 'Server unreachable.');
    });
  };

  return (
    <View style={[styles.disputeBlock, { backgroundColor: theme.dangerSoft }]}>
      <ThemedText type="smallBold" style={{ color: theme.danger }}>
        🚩 {filer.name} disputes
        {match.dispute.status === 'score-stands' ? ' (rejected — score stands)' : ''}
        {match.dispute.status === 'overturned' ? ' (upheld — result overturned!)' : ''}
      </ThemedText>
      <ThemedText type="small" style={styles.statement}>
        “{match.dispute.statement}”
      </ThemedText>
      {match.dispute.status === 'open' ? (
        <View style={styles.resolveRow}>
          <Pressable
            onPress={() => resolve('score-stands')}
            style={({ pressed }) => [
              styles.resolveBtn,
              { borderColor: theme.border, backgroundColor: theme.backgroundElement },
              pressed && { opacity: 0.6 },
            ]}>
            <ThemedText type="smallBold">Score stands</ThemedText>
          </Pressable>
          <Pressable
            onPress={() => resolve('overturned')}
            style={({ pressed }) => [
              styles.resolveBtn,
              { backgroundColor: theme.danger, borderColor: theme.danger },
              pressed && { opacity: 0.8 },
            ]}>
            <ThemedText type="smallBold" style={{ color: '#FFFFFF' }}>
              Overturn it
            </ThemedText>
          </Pressable>
        </View>
      ) : null}
    </View>
  );
}

export default function ActivityScreen() {
  const theme = useTheme();
  const { state } = useStore();
  const { players, games, matches } = state;

  return (
    <Screen title="Activity" subtitle="the rivalry record">
      {matches.map((match) => {
        const game = games.find((g) => g.id === match.gameId);
        if (!game) return null;
        const winner = match.winnerId ? players[match.winnerId] : null;
        const disputable = !match.dispute;

        return (
          <Card key={match.id} style={styles.item}>
            <View style={styles.itemHead}>
              <ThemedText type="smallBold" style={styles.itemTitle}>
                {game.emoji} {winner ? `${winner.name} won ${game.name}` : `${game.name} — tie`}
              </ThemedText>
              <ThemedText type="small" themeColor="textSecondary">
                {relativeDay(match.playedAt)}
              </ThemedText>
            </View>
            <ThemedText type="small" themeColor="textSecondary" style={styles.score}>
              {match.scores.p1}–{match.scores.p2}
              {match.cheatCheckFlagged ? '  ·  🤖 cheat-check flagged this one' : ''}
            </ThemedText>
            {match.note ? (
              <ThemedText type="small" themeColor="textSecondary" style={styles.noteText}>
                “{match.note}”
              </ThemedText>
            ) : null}
            <DisputeBlock match={match} />
            {disputable ? (
              <Pressable
                onPress={() => router.push(`/dispute/${match.id}`)}
                style={({ pressed }) => [styles.disputeLink, pressed && { opacity: 0.6 }]}>
                <ThemedText type="smallBold" style={{ color: theme.danger }}>
                  {match.cheatCheckFlagged ? '🚩 Care to dispute?' : 'Dispute'}
                </ThemedText>
              </Pressable>
            ) : null}
          </Card>
        );
      })}
    </Screen>
  );
}

const styles = StyleSheet.create({
  item: { gap: 3 },
  itemHead: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'baseline',
    gap: 8,
  },
  itemTitle: { flexShrink: 1 },
  score: { fontFamily: Fonts?.mono, fontSize: 12 },
  noteText: { fontStyle: 'italic' },
  disputeBlock: {
    borderRadius: 10,
    padding: 10,
    marginTop: 6,
    gap: 4,
  },
  statement: { fontStyle: 'italic' },
  resolveRow: { flexDirection: 'row', gap: 8, marginTop: 4 },
  resolveBtn: {
    flex: 1,
    borderWidth: 1.5,
    borderRadius: 9,
    paddingVertical: 8,
    alignItems: 'center',
  },
  disputeLink: { marginTop: 4, alignSelf: 'flex-start', paddingVertical: Spacing.half },
});
