import React, { useState, useRef, useCallback } from 'react';
import { View, Text, StyleSheet, Animated, Pressable } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import ScreenWrapper from '../components/ScreenWrapper';
import NovaAd from '../components/NovaAd';
import useAuthStore from '../store/useAuthStore';
import * as offline from '../services/offlineStorage';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

const MOOD_EMOJIS = { great: '😄', good: '🙂', okay: '😐', bad: '😔', terrible: '😞' };
const CHECK_COLORS = { yes: colors.success, almost: colors.warning, no: colors.error };
const CHECK_LABELS = { yes: 'Aligned', almost: 'Almost', no: 'Missed' };

function HistoryCard({ entry, isFirst }) {
  const [expanded, setExpanded] = useState(isFirst);
  const hasJournal = entry.win || entry.struggle || entry.highlight || entry.note;
  const hasAI = entry.ai_title;

  return (
    <Pressable style={styles.card} onPress={() => setExpanded((p) => !p)}>
      {/* Timeline dot + line */}
      <View style={styles.timeline}>
        <View style={[
          styles.timelineDot,
          { backgroundColor: CHECK_COLORS[entry.identity_check] || colors.primary },
        ]} />
        <View style={styles.timelineLine} />
      </View>

      <View style={styles.cardContent}>
        {/* Header row */}
        <View style={styles.cardHeader}>
          <View style={styles.cardHeaderLeft}>
            <Text style={styles.dayNum}>Day {entry.day_number}</Text>
            {entry._identityTitle && (
              <Text style={styles.identityTag}>{entry._identityTitle}</Text>
            )}
          </View>
          <View style={styles.cardHeaderRight}>
            <Text style={styles.moodEmoji}>{MOOD_EMOJIS[entry.mood] || '•'}</Text>
            <Text style={styles.dateText}>{formatDate(entry.date)}</Text>
          </View>
        </View>

        {/* Identity check badge */}
        {entry.identity_check && (
          <View style={[styles.checkBadge, { borderColor: CHECK_COLORS[entry.identity_check] }]}>
            <View style={[styles.checkDot, { backgroundColor: CHECK_COLORS[entry.identity_check] }]} />
            <Text style={[styles.checkText, { color: CHECK_COLORS[entry.identity_check] }]}>
              {CHECK_LABELS[entry.identity_check]}
            </Text>
            {entry.habits_completed > 0 && (
              <Text style={styles.habitsBadge}>{entry.habits_completed} habits done</Text>
            )}
          </View>
        )}

        {/* AI reflection (always visible) */}
        {hasAI && (
          <View style={styles.aiSection}>
            <Text style={styles.aiTitle}>{entry.ai_title}</Text>
            {entry.ai_quote && (
              <Text style={styles.aiQuote}>"{entry.ai_quote}"</Text>
            )}
          </View>
        )}

        {/* Expanded: full details */}
        {expanded && (
          <View style={styles.expandedSection}>
            {entry.ai_summary && (
              <Text style={styles.aiSummary}>{entry.ai_summary}</Text>
            )}

            {hasJournal && (
              <View style={styles.journalSection}>
                <View style={styles.journalDivider}>
                  <View style={styles.journalDividerLine} />
                  <Text style={styles.journalDividerText}>Your words</Text>
                  <View style={styles.journalDividerLine} />
                </View>

                {entry.win && (
                  <JournalEntry icon="🏆" label="Win" value={entry.win} />
                )}
                {entry.struggle && (
                  <JournalEntry icon="💪" label="Struggle" value={entry.struggle} />
                )}
                {entry.highlight && (
                  <JournalEntry icon="✨" label="Highlight" value={entry.highlight} />
                )}
                {entry.note && (
                  <JournalEntry icon="💭" label="Reflection" value={entry.note} />
                )}
              </View>
            )}
          </View>
        )}

        {/* Expand hint */}
        {(hasAI || hasJournal) && (
          <Text style={styles.expandHint}>{expanded ? 'Tap to collapse' : 'Tap to read more'}</Text>
        )}
      </View>
    </Pressable>
  );
}

function JournalEntry({ icon, label, value }) {
  return (
    <View style={styles.journalRow}>
      <Text style={styles.journalIcon}>{icon}</Text>
      <View style={styles.journalBody}>
        <Text style={styles.journalLabel}>{label}</Text>
        <Text style={styles.journalValue}>{value}</Text>
      </View>
    </View>
  );
}

function formatDate(dateStr) {
  if (!dateStr) return '';
  try {
    const d = new Date(dateStr);
    return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  } catch (_) {
    return dateStr;
  }
}

export default function HistoryScreen() {
  const user = useAuthStore((s) => s.user);
  const [entries, setEntries] = useState([]);
  const [journeyCount, setJourneyCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const fadeAnim = useRef(new Animated.Value(0)).current;

  useFocusEffect(
    useCallback(() => {
      let active = true;
      const load = async () => {
        setLoading(true);
        if (user?.id) {
          const allIdentities = await offline.getAll('identities', { user_id: user.id });
          if (active) setJourneyCount(allIdentities.length);
          const allLogs = await offline.getAll('daily_logs');
          const identityMap = {};
          allIdentities.forEach((id) => { identityMap[id.id] = id.title; });
          const identityIds = allIdentities.map((id) => id.id);
          const userLogs = allLogs
            .filter((l) => identityIds.includes(l.identity_id))
            .filter((l) => l.identity_check || l.ai_title || l.mood)
            .map((l) => ({ ...l, _identityTitle: identityMap[l.identity_id] || '' }))
            .sort((a, b) => {
              if (a.date !== b.date) return a.date > b.date ? -1 : 1;
              return (b.day_number || 0) - (a.day_number || 0);
            });
          if (active) setEntries(userLogs);
        }
        if (active) {
          setLoading(false);
          Animated.timing(fadeAnim, { toValue: 1, duration: 500, useNativeDriver: true }).start();
        }
      };
      load();
      return () => { active = false; };
    }, [user?.id])
  );

  // Stats summary
  const totalDays = entries.length;
  const yesCount = entries.filter((e) => e.identity_check === 'yes').length;
  const streakCount = (() => {
    let streak = 0;
    for (const e of entries) {
      if (e.identity_check === 'yes' || e.identity_check === 'almost') streak++;
      else break;
    }
    return streak;
  })();

  if (loading) {
    return (
      <ScreenWrapper>
        <View style={styles.loadingContainer}>
          <Text style={styles.loadingText}>Loading your journey...</Text>
        </View>
      </ScreenWrapper>
    );
  }

  return (
    <ScreenWrapper>
      <Animated.ScrollView
        style={[styles.scroll, { opacity: fadeAnim }]}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <Text style={styles.title}>Your Journey</Text>
        <Text style={styles.subtitle}>
          {totalDays > 0
            ? 'Every entry is proof that you showed up.'
            : 'Your story begins when you complete your first day.'}
        </Text>

        {entries.length === 0 ? (
          /* Empty state */
          <View style={styles.emptyState}>
            <Text style={styles.emptyEmoji}>🌱</Text>
            <Text style={styles.emptyTitle}>Your story starts today</Text>
            <Text style={styles.emptyText}>
              Complete your first day on the Daily tab.{'\n'}
              Every small step gets recorded here as part of your transformation.
            </Text>
          </View>
        ) : (
          <>
            {/* Summary stats */}
            <View style={styles.statsRow}>
              <View style={styles.statCard}>
                <Text style={styles.statEmoji}>🚀</Text>
                <Text style={[styles.statValue, { color: colors.primary }]}>{journeyCount}</Text>
                <Text style={styles.statLabel}>{journeyCount === 1 ? 'Journey' : 'Journeys'}</Text>
              </View>
              <View style={styles.statCard}>
                <Text style={styles.statEmoji}>📅</Text>
                <Text style={styles.statValue}>{totalDays}</Text>
                <Text style={styles.statLabel}>Days logged</Text>
              </View>
              <View style={styles.statCard}>
                <Text style={styles.statEmoji}>🎯</Text>
                <Text style={[styles.statValue, { color: colors.success }]}>{yesCount}</Text>
                <Text style={styles.statLabel}>Aligned</Text>
              </View>
              <View style={styles.statCard}>
                <Text style={styles.statEmoji}>🔥</Text>
                <Text style={[styles.statValue, { color: colors.accent }]}>{streakCount}</Text>
                <Text style={styles.statLabel}>Streak</Text>
              </View>
            </View>

            <NovaAd />

            {/* Motivational banner */}
            <View style={styles.motivBanner}>
              <Text style={styles.motivText}>
                {totalDays < 5
                  ? "You're just getting started. The hardest part is showing up — and you did."
                  : totalDays < 15
                  ? "You're building something real. Most people never make it this far."
                  : totalDays < 30
                  ? "Look at this. Look at all these days. You are not the same person who started."
                  : "This is what commitment looks like. You didn't just try — you transformed."}
              </Text>
            </View>

            {/* Timeline */}
            <Text style={styles.timelineTitle}>Timeline</Text>
            {entries.map((entry, i) => (
              <HistoryCard key={entry.id || i} entry={entry} isFirst={i === 0} />
            ))}

            <NovaAd />

            {/* Journey end message */}
            <View style={styles.endMessage}>
              <Text style={styles.endEmoji}>🌟</Text>
              <Text style={styles.endText}>
                {totalDays} days of choosing who you want to be.{'\n'}That's not nothing. That's everything.
              </Text>
            </View>
          </>
        )}
      </Animated.ScrollView>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  scroll: { flex: 1 },
  scrollContent: { padding: spacing.lg, paddingBottom: spacing.xxl * 2 },
  loadingContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  loadingText: { color: colors.textSecondary, fontSize: fonts.sizes.md },

  // Header
  title: { color: colors.text, fontSize: fonts.sizes.xxl, fontWeight: fonts.weights.bold, marginBottom: spacing.xs },
  subtitle: { color: colors.textSecondary, fontSize: fonts.sizes.sm, lineHeight: 20, marginBottom: spacing.lg },

  // Empty state
  emptyState: { alignItems: 'center', paddingTop: spacing.xxl * 2 },
  emptyEmoji: { fontSize: 56, marginBottom: spacing.lg },
  emptyTitle: { color: colors.text, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.bold, marginBottom: spacing.sm },
  emptyText: { color: colors.textMuted, fontSize: fonts.sizes.sm, textAlign: 'center', lineHeight: 22 },

  // Stats
  statsRow: { flexDirection: 'row', gap: spacing.sm, marginBottom: spacing.lg },
  statCard: {
    flex: 1, alignItems: 'center',
    backgroundColor: colors.surface, borderRadius: borderRadius.lg,
    paddingVertical: spacing.md, borderWidth: 1, borderColor: colors.border,
  },
  statEmoji: { fontSize: 20, marginBottom: spacing.xs },
  statValue: { color: colors.text, fontSize: fonts.sizes.xl, fontWeight: fonts.weights.bold },
  statLabel: { color: colors.textMuted, fontSize: 10, marginTop: 2 },

  // Motivational banner
  motivBanner: {
    backgroundColor: 'rgba(108, 99, 255, 0.06)',
    borderRadius: borderRadius.lg,
    padding: spacing.lg,
    borderLeftWidth: 3,
    borderLeftColor: colors.primary,
    marginBottom: spacing.xl,
  },
  motivText: { color: colors.textSecondary, fontSize: fonts.sizes.sm, lineHeight: 22, fontStyle: 'italic' },

  // Timeline
  timelineTitle: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.bold, marginBottom: spacing.md },

  // Card
  card: {
    flexDirection: 'row',
    marginBottom: 0,
  },
  timeline: {
    width: 24,
    alignItems: 'center',
    paddingTop: 6,
  },
  timelineDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
    shadowColor: colors.primary,
    shadowOffset: { width: 0, height: 0 },
    shadowOpacity: 0.5,
    shadowRadius: 4,
    elevation: 3,
  },
  timelineLine: {
    flex: 1,
    width: 2,
    backgroundColor: colors.border,
    marginTop: 4,
  },
  cardContent: {
    flex: 1,
    backgroundColor: colors.surface,
    borderRadius: borderRadius.lg,
    padding: spacing.md,
    marginLeft: spacing.sm,
    marginBottom: spacing.md,
    borderWidth: 1,
    borderColor: colors.border,
  },

  // Card header
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: spacing.sm,
  },
  cardHeaderLeft: {},
  cardHeaderRight: { alignItems: 'flex-end' },
  dayNum: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.bold },
  identityTag: { color: colors.primary, fontSize: 10, fontWeight: fonts.weights.medium, marginTop: 2 },
  moodEmoji: { fontSize: 18, marginBottom: 2 },
  dateText: { color: colors.textMuted, fontSize: 10 },

  // Check badge
  checkBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    borderWidth: 1,
    borderRadius: borderRadius.full,
    paddingVertical: spacing.xs,
    paddingHorizontal: spacing.sm,
    alignSelf: 'flex-start',
    marginBottom: spacing.sm,
    gap: 6,
  },
  checkDot: { width: 6, height: 6, borderRadius: 3 },
  checkText: { fontSize: 11, fontWeight: fonts.weights.semibold },
  habitsBadge: { color: colors.textMuted, fontSize: 10, marginLeft: 4 },

  // AI section
  aiSection: { marginBottom: spacing.sm },
  aiTitle: { color: colors.text, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.semibold, lineHeight: 20, marginBottom: spacing.xs },
  aiQuote: { color: colors.accent, fontSize: fonts.sizes.xs, fontStyle: 'italic', lineHeight: 18 },

  // Expanded
  expandedSection: { marginTop: spacing.sm },
  aiSummary: { color: colors.textSecondary, fontSize: fonts.sizes.sm, lineHeight: 20, marginBottom: spacing.md },

  // Journal section
  journalSection: { marginTop: spacing.xs },
  journalDivider: { flexDirection: 'row', alignItems: 'center', marginBottom: spacing.md },
  journalDividerLine: { flex: 1, height: 1, backgroundColor: colors.border },
  journalDividerText: { color: colors.textMuted, fontSize: 10, marginHorizontal: spacing.sm, fontWeight: fonts.weights.medium },

  journalRow: { flexDirection: 'row', marginBottom: spacing.sm },
  journalIcon: { fontSize: 14, marginRight: spacing.sm, marginTop: 1 },
  journalBody: { flex: 1 },
  journalLabel: { color: colors.textMuted, fontSize: 10, fontWeight: fonts.weights.medium, marginBottom: 1 },
  journalValue: { color: colors.textSecondary, fontSize: fonts.sizes.sm, lineHeight: 20 },

  // Expand hint
  expandHint: { color: colors.textMuted, fontSize: 10, textAlign: 'center', marginTop: spacing.xs },

  // End message
  endMessage: { alignItems: 'center', paddingTop: spacing.xl, paddingBottom: spacing.lg },
  endEmoji: { fontSize: 32, marginBottom: spacing.sm },
  endText: { color: colors.textSecondary, fontSize: fonts.sizes.sm, textAlign: 'center', lineHeight: 22 },
});
