import React, { useState, useRef, useCallback } from 'react';
import { View, Text, StyleSheet, Animated } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import ScreenWrapper from '../components/ScreenWrapper';
import useIdentityStore from '../store/useIdentityStore';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';
import { getDayPhase } from '../utils/helpers';

function StatCard({ label, value, maxValue, color }) {
  const percentage = maxValue > 0 ? Math.min((value / maxValue) * 100, 100) : 0;
  return (
    <View style={styles.statCard}>
      <View style={styles.statHeader}>
        <Text style={styles.statLabel}>{label}</Text>
        <Text style={[styles.statValue, { color }]}>{value}</Text>
      </View>
      <View style={styles.barBg}>
        <View style={[styles.barFill, { width: `${percentage}%`, backgroundColor: color }]} />
      </View>
    </View>
  );
}

export default function StatsScreen() {
  const currentDay = useIdentityStore((s) => s.currentDay);
  const loadStats = useIdentityStore((s) => s.loadStats);
  const loadDailyLogs = useIdentityStore((s) => s.loadDailyLogs);
  const [stats, setStats] = useState(null);
  const [dailyLogs, setDailyLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const fadeAnim = useRef(new Animated.Value(0)).current;

  useFocusEffect(
    useCallback(() => {
      let active = true;
      const load = async () => {
        setLoading(true);
        const [s, logs] = await Promise.all([loadStats(), loadDailyLogs()]);
        if (active) {
          setStats(s);
          setDailyLogs(logs);
          setLoading(false);
          Animated.timing(fadeAnim, { toValue: 1, duration: 500, useNativeDriver: true }).start();
        }
      };
      load();
      return () => { active = false; };
    }, [])
  );

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

  const maxScore = currentDay * 3;
  const yesCount = dailyLogs.filter((l) => l.identity_check === 'yes').length;
  const almostCount = dailyLogs.filter((l) => l.identity_check === 'almost').length;
  const noCount = dailyLogs.filter((l) => l.identity_check === 'no').length;
  const totalScore = (stats?.discipline_score || 0) + (stats?.focus_score || 0) + (stats?.consistency_score || 0);

  const sorted = [...dailyLogs].sort((a, b) => b.day_number - a.day_number);
  let streakDays = 0;
  for (const log of sorted) {
    if (log.identity_check === 'yes' || log.identity_check === 'almost') streakDays++;
    else break;
  }

  return (
    <ScreenWrapper>
      <Animated.ScrollView
        style={[styles.scroll, { opacity: fadeAnim }]}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        <Text style={styles.title}>Your Journey</Text>
        <Text style={styles.subtitle}>
          {getDayPhase(currentDay).toUpperCase()} PHASE — Day {currentDay}/40
        </Text>

        <StatCard label="Discipline" value={stats?.discipline_score || 0} maxValue={maxScore} color={colors.primary} />
        <StatCard label="Focus" value={stats?.focus_score || 0} maxValue={maxScore} color={colors.accent} />
        <StatCard label="Consistency" value={stats?.consistency_score || 0} maxValue={currentDay * 2} color={colors.success} />

        {/* Total */}
        <View style={styles.totalCard}>
          <Text style={styles.totalLabel}>Total Score</Text>
          <Text style={styles.totalValue}>{totalScore}</Text>
        </View>

        {/* Identity Check Summary */}
        <View style={styles.summaryCard}>
          <Text style={styles.summaryTitle}>Identity Check Summary</Text>
          <View style={styles.summaryRow}>
            <View style={styles.summaryItem}>
              <Text style={[styles.summaryValue, { color: colors.success }]}>{yesCount}</Text>
              <Text style={styles.summaryLabel}>Yes</Text>
            </View>
            <View style={styles.summaryItem}>
              <Text style={[styles.summaryValue, { color: colors.warning }]}>{almostCount}</Text>
              <Text style={styles.summaryLabel}>Almost</Text>
            </View>
            <View style={styles.summaryItem}>
              <Text style={[styles.summaryValue, { color: colors.error }]}>{noCount}</Text>
              <Text style={styles.summaryLabel}>No</Text>
            </View>
          </View>
        </View>

        {/* Streak */}
        <View style={styles.streakCard}>
          <Text style={styles.streakNumber}>{streakDays}</Text>
          <Text style={styles.streakLabel}>Day Streak</Text>
        </View>
      </Animated.ScrollView>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  scroll: { flex: 1 },
  scrollContent: { padding: spacing.lg, paddingBottom: spacing.xxl },
  loadingContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  loadingText: { color: colors.textSecondary, fontSize: fonts.sizes.md },
  title: { color: colors.text, fontSize: fonts.sizes.xxl, fontWeight: fonts.weights.bold, marginBottom: spacing.xs },
  subtitle: { color: colors.accent, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.bold, letterSpacing: 2, marginBottom: spacing.xl },

  statCard: { backgroundColor: colors.surface, borderRadius: borderRadius.md, padding: spacing.md, marginBottom: spacing.md, borderWidth: 1, borderColor: colors.border },
  statHeader: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: spacing.sm },
  statLabel: { color: colors.textSecondary, fontSize: fonts.sizes.md, fontWeight: fonts.weights.medium },
  statValue: { fontSize: fonts.sizes.lg, fontWeight: fonts.weights.bold },
  barBg: { height: 6, backgroundColor: colors.surfaceLight, borderRadius: 3, overflow: 'hidden' },
  barFill: { height: '100%', borderRadius: 3 },

  totalCard: { backgroundColor: colors.surface, borderRadius: borderRadius.md, padding: spacing.lg, marginBottom: spacing.md, borderWidth: 1, borderColor: colors.accent, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  totalLabel: { color: colors.textSecondary, fontSize: fonts.sizes.md, fontWeight: fonts.weights.medium },
  totalValue: { color: colors.accent, fontSize: fonts.sizes.xxl, fontWeight: fonts.weights.bold },

  summaryCard: { backgroundColor: colors.surface, borderRadius: borderRadius.md, padding: spacing.lg, marginBottom: spacing.md, borderWidth: 1, borderColor: colors.border },
  summaryTitle: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.semibold, marginBottom: spacing.md },
  summaryRow: { flexDirection: 'row', justifyContent: 'space-around' },
  summaryItem: { alignItems: 'center' },
  summaryValue: { fontSize: fonts.sizes.xxl, fontWeight: fonts.weights.bold },
  summaryLabel: { color: colors.textSecondary, fontSize: fonts.sizes.sm, marginTop: spacing.xs },

  streakCard: { backgroundColor: colors.surface, borderRadius: borderRadius.md, padding: spacing.xl, alignItems: 'center', borderWidth: 1, borderColor: colors.primary },
  streakNumber: { color: colors.primary, fontSize: fonts.sizes.hero, fontWeight: fonts.weights.bold },
  streakLabel: { color: colors.textSecondary, fontSize: fonts.sizes.md, marginTop: spacing.xs },
});
