import { useEffect, useState } from 'react';
import {
  View, Text, ScrollView, TouchableOpacity, StyleSheet,
  ActivityIndicator, RefreshControl,
} from 'react-native';
import { useRouter } from 'expo-router';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/api/client';
import { adaptPassagePayload } from '@/api/passageAdapter';
import { getTodayPassage, cachePassage, getDueCards } from '@/db/local';
import { Colors, Spacing, Typography, Radius } from '@/theme';
import type { Passage, SrsCard } from '@/types';

export default function TodayScreen() {
  const router = useRouter();
  const [offlinePassage, setOfflinePassage] = useState<Passage | null>(null);
  const [dueCount, setDueCount] = useState(0);

  // Fetch today's passage from server
  const { data: passage, isLoading, isError, refetch, isRefetching } = useQuery<Passage>({
    queryKey: ['today-passage'],
    queryFn: async () => {
      const raw = await api.get('/api/passage/today');
      const passage = adaptPassagePayload(raw);
      await cachePassage(passage);
      return passage;
    },
    retry: 1,
  });

  // Load due count from local DB
  useEffect(() => {
    getDueCards(999).then((cards) => setDueCount(cards.length));
  }, []);

  // Fallback: first cached passage if server unreachable
  useEffect(() => {
    if (isError && !passage) {
      getTodayPassage(1).then((p) => {
        if (p) setOfflinePassage(p);
      });
    }
  }, [isError, passage]);

  const displayPassage = passage ?? offlinePassage;

  return (
    <ScrollView
      style={styles.container}
      contentContainerStyle={styles.content}
      refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} />}
    >
      {/* Daily stats bar */}
      <View style={styles.statsRow}>
        <StatChip label="Due" value={dueCount} onPress={() => router.push('/review')} />
        <OfflineBadge show={isError && !isLoading} />
      </View>

      {isLoading && !displayPassage && (
        <View style={styles.centered}>
          <ActivityIndicator color={Colors.primary} size="large" />
          <Text style={styles.loadingText}>Loading today's passage…</Text>
        </View>
      )}

      {displayPassage && (
        <PassageCard passage={displayPassage} />
      )}

      {isError && !displayPassage && (
        <View style={styles.centered}>
          <Text style={styles.errorTitle}>Offline</Text>
          <Text style={styles.errorText}>
            No cached passage available. Connect to sync.
          </Text>
          <TouchableOpacity style={styles.retryButton} onPress={() => refetch()}>
            <Text style={styles.retryText}>Retry</Text>
          </TouchableOpacity>
        </View>
      )}
    </ScrollView>
  );
}

function PassageCard({ passage }: { passage: Passage }) {
  const router = useRouter();

  return (
    <View style={styles.card}>
      {/* Author / reference */}
      <View style={styles.passageMeta}>
        <Text style={styles.author}>{passage.author}</Text>
        <Text style={styles.work}>
          {passage.work} · {passage.reference}
        </Text>
      </View>

      {/* Passage text — tappable to open full reader */}
      <TouchableOpacity
        onPress={() => router.push(`/read/${passage.id}`)}
        activeOpacity={0.85}
      >
        <Text style={styles.passageText} numberOfLines={6}>
          {passage.passageText}
        </Text>
      </TouchableOpacity>

      {/* Context card */}
      {passage.contextCard?.contextNote && (
        <Text style={styles.context} numberOfLines={3}>
          {passage.contextCard.contextNote}
        </Text>
      )}

      {/* CTA */}
      <TouchableOpacity
        style={styles.readButton}
        onPress={() => router.push(`/read/${passage.id}`)}
      >
        <Text style={styles.readButtonText}>Read & Parse →</Text>
      </TouchableOpacity>
    </View>
  );
}

function StatChip({
  label, value, onPress,
}: { label: string; value: number; onPress?: () => void }) {
  return (
    <TouchableOpacity style={styles.chip} onPress={onPress}>
      <Text style={styles.chipValue}>{value}</Text>
      <Text style={styles.chipLabel}>{label}</Text>
    </TouchableOpacity>
  );
}

function OfflineBadge({ show }: { show: boolean }) {
  if (!show) return null;
  return (
    <View style={styles.offlineBadge}>
      <Text style={styles.offlineBadgeText}>Offline</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.background },
  content: { padding: Spacing.lg, gap: Spacing.md },
  statsRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.sm,
    marginBottom: Spacing.sm,
  },
  chip: {
    backgroundColor: Colors.surface,
    borderWidth: 1,
    borderColor: Colors.border,
    borderRadius: Radius.md,
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.sm,
    alignItems: 'center',
    minWidth: 60,
  },
  chipValue: {
    fontSize: Typography.size.lg,
    fontWeight: Typography.weight.bold,
    color: Colors.primary,
  },
  chipLabel: {
    fontSize: Typography.size.xs,
    color: Colors.textMuted,
    fontWeight: Typography.weight.medium,
  },
  offlineBadge: {
    backgroundColor: Colors.warning + '22',
    borderRadius: Radius.sm,
    paddingHorizontal: Spacing.sm,
    paddingVertical: 3,
  },
  offlineBadgeText: { fontSize: Typography.size.xs, color: Colors.warning },
  card: {
    backgroundColor: Colors.surface,
    borderRadius: Radius.lg,
    borderWidth: 1,
    borderColor: Colors.border,
    padding: Spacing.xl,
    gap: Spacing.md,
  },
  passageMeta: { gap: 2 },
  author: {
    fontSize: Typography.size.sm,
    fontWeight: Typography.weight.semibold,
    color: Colors.primary,
    textTransform: 'uppercase',
    letterSpacing: 0.8,
  },
  work: { fontSize: Typography.size.xs, color: Colors.textMuted },
  passageText: {
    fontSize: Typography.size.lg,
    lineHeight: Typography.size.lg * Typography.lineHeight.relaxed,
    color: Colors.text,
    fontStyle: 'italic',
  },
  context: {
    fontSize: Typography.size.sm,
    color: Colors.textMuted,
    lineHeight: Typography.size.sm * Typography.lineHeight.normal,
    borderLeftWidth: 2,
    borderLeftColor: Colors.parchment,
    paddingLeft: Spacing.sm,
  },
  readButton: {
    backgroundColor: Colors.primary,
    borderRadius: Radius.md,
    paddingVertical: Spacing.md,
    alignItems: 'center',
    marginTop: Spacing.sm,
  },
  readButtonText: {
    color: '#ffffff',
    fontWeight: Typography.weight.semibold,
    fontSize: Typography.size.base,
  },
  centered: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: Spacing['3xl'],
    gap: Spacing.md,
  },
  loadingText: { color: Colors.textMuted, fontSize: Typography.size.sm },
  errorTitle: {
    fontSize: Typography.size.xl,
    fontWeight: Typography.weight.semibold,
    color: Colors.text,
  },
  errorText: {
    fontSize: Typography.size.sm,
    color: Colors.textMuted,
    textAlign: 'center',
  },
  retryButton: {
    backgroundColor: Colors.primary,
    borderRadius: Radius.md,
    paddingHorizontal: Spacing.xl,
    paddingVertical: Spacing.sm,
  },
  retryText: { color: '#fff', fontWeight: Typography.weight.semibold },
});
