import { useCallback, useEffect, useState } from 'react';
import {
  View, Text, TouchableOpacity, StyleSheet, ActivityIndicator,
} from 'react-native';
import { getDueCards, upsertSrsCard } from '@/db/local';
import { applyGrade } from '@/lib/sm2';
import { useSync } from '@/hooks/useSync';
import { Colors, Spacing, Typography, Radius } from '@/theme';
import type { SrsCard, SrsGrade } from '@/types';

export default function ReviewScreen() {
  const [queue, setQueue] = useState<SrsCard[]>([]);
  const [current, setCurrent] = useState(0);
  const [showAnswer, setShowAnswer] = useState(false);
  const [loading, setLoading] = useState(true);
  const [sessionStats, setSessionStats] = useState({ correct: 0, total: 0 });
  const { syncSrs } = useSync();

  const loadQueue = useCallback(async () => {
    setLoading(true);
    const cards = await getDueCards(50);
    setQueue(cards);
    setCurrent(0);
    setShowAnswer(false);
    setLoading(false);
  }, []);

  useEffect(() => { loadQueue(); }, [loadQueue]);

  const card = queue[current];
  const done = !loading && (!card || current >= queue.length);

  async function grade(g: SrsGrade) {
    if (!card) return;
    const updated = applyGrade(card, g);
    await upsertSrsCard({ ...card, ...updated });
    setSessionStats((s) => ({
      correct: s.correct + (g >= 3 ? 1 : 0),
      total: s.total + 1,
    }));
    setCurrent((c) => c + 1);
    setShowAnswer(false);
    if (current === queue.length - 1) {
      await syncSrs();
    }
  }

  if (loading) {
    return (
      <View style={styles.centered}>
        <ActivityIndicator color={Colors.primary} />
      </View>
    );
  }

  if (done) {
    return (
      <View style={styles.centered}>
        <Text style={styles.doneEmoji}>✓</Text>
        <Text style={styles.doneTitle}>All caught up!</Text>
        {sessionStats.total > 0 && (
          <Text style={styles.doneStats}>
            {sessionStats.correct}/{sessionStats.total} correct this session
          </Text>
        )}
        <TouchableOpacity style={styles.doneButton} onPress={loadQueue}>
          <Text style={styles.doneButtonText}>Check again</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {/* Progress */}
      <View style={styles.progressRow}>
        <View style={styles.progressBar}>
          <View
            style={[
              styles.progressFill,
              { width: `${(current / queue.length) * 100}%` },
            ]}
          />
        </View>
        <Text style={styles.progressText}>
          {current + 1}/{queue.length}
        </Text>
      </View>

      {/* Card */}
      <View style={styles.card}>
        <Text style={styles.language}>{card.language.toUpperCase()}</Text>
        <Text style={styles.headword}>{card.headword}</Text>

        {showAnswer ? (
          <>
            <Text style={styles.divider}>—</Text>
            <Text style={styles.definition}>{card.shortDef}</Text>
          </>
        ) : (
          <TouchableOpacity
            style={styles.showButton}
            onPress={() => setShowAnswer(true)}
          >
            <Text style={styles.showButtonText}>Show answer</Text>
          </TouchableOpacity>
        )}
      </View>

      {/* Grade buttons */}
      {showAnswer && (
        <View style={styles.gradeRow}>
          <GradeButton label="Again" color={Colors.error} onPress={() => grade(1)} />
          <GradeButton label="Hard" color={Colors.warning} onPress={() => grade(3)} />
          <GradeButton label="Good" color={Colors.success} onPress={() => grade(4)} />
          <GradeButton label="Easy" color={Colors.accent} onPress={() => grade(5)} />
        </View>
      )}
    </View>
  );
}

function GradeButton({
  label, color, onPress,
}: { label: string; color: string; onPress: () => void }) {
  return (
    <TouchableOpacity
      style={[styles.gradeButton, { borderColor: color }]}
      onPress={onPress}
    >
      <Text style={[styles.gradeButtonText, { color }]}>{label}</Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.background,
    padding: Spacing.lg,
    gap: Spacing.lg,
  },
  centered: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: Spacing.md },
  progressRow: { flexDirection: 'row', alignItems: 'center', gap: Spacing.sm },
  progressBar: {
    flex: 1, height: 4, backgroundColor: Colors.border,
    borderRadius: Radius.full, overflow: 'hidden',
  },
  progressFill: { height: '100%', backgroundColor: Colors.primary, borderRadius: Radius.full },
  progressText: { fontSize: Typography.size.xs, color: Colors.textMuted, minWidth: 40, textAlign: 'right' },
  card: {
    flex: 1,
    backgroundColor: Colors.surface,
    borderRadius: Radius.lg,
    borderWidth: 1,
    borderColor: Colors.border,
    padding: Spacing['2xl'],
    alignItems: 'center',
    justifyContent: 'center',
    gap: Spacing.lg,
  },
  language: {
    fontSize: Typography.size.xs,
    letterSpacing: 1.5,
    color: Colors.textMuted,
    fontWeight: Typography.weight.medium,
  },
  headword: {
    fontSize: 36,
    fontWeight: Typography.weight.semibold,
    color: Colors.primary,
    textAlign: 'center',
  },
  divider: { fontSize: Typography.size.xl, color: Colors.parchment },
  definition: {
    fontSize: Typography.size.base,
    color: Colors.text,
    textAlign: 'center',
    lineHeight: Typography.size.base * Typography.lineHeight.normal,
  },
  showButton: {
    backgroundColor: Colors.accentLight,
    borderRadius: Radius.md,
    paddingHorizontal: Spacing.xl,
    paddingVertical: Spacing.md,
  },
  showButtonText: {
    color: Colors.accent,
    fontWeight: Typography.weight.semibold,
    fontSize: Typography.size.base,
  },
  gradeRow: { flexDirection: 'row', gap: Spacing.sm },
  gradeButton: {
    flex: 1,
    borderWidth: 1.5,
    borderRadius: Radius.md,
    paddingVertical: Spacing.md,
    alignItems: 'center',
  },
  gradeButtonText: { fontWeight: Typography.weight.semibold, fontSize: Typography.size.sm },
  doneEmoji: { fontSize: 48 },
  doneTitle: {
    fontSize: Typography.size['2xl'],
    fontWeight: Typography.weight.bold,
    color: Colors.primary,
  },
  doneStats: { fontSize: Typography.size.sm, color: Colors.textMuted },
  doneButton: {
    backgroundColor: Colors.primary,
    borderRadius: Radius.md,
    paddingHorizontal: Spacing.xl,
    paddingVertical: Spacing.md,
  },
  doneButtonText: { color: '#fff', fontWeight: Typography.weight.semibold },
});
