import React, { useState, useEffect, useRef } from 'react';
import { View, Text, StyleSheet, ScrollView, Animated } from 'react-native';
import ScreenWrapper from '../components/ScreenWrapper';
import useIdentityStore from '../store/useIdentityStore';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';
import { formatDate } from '../utils/helpers';

function DayCard({ label, day, log, color }) {
  return (
    <View style={[styles.dayCard, { borderColor: color }]}>
      <Text style={[styles.dayCardLabel, { color }]}>{label}</Text>
      <Text style={styles.dayCardDay}>Day {day}</Text>
      {log ? (
        <>
          <View style={styles.checkRow}>
            <Text style={styles.checkLabel}>Identity Check:</Text>
            <Text style={[styles.checkValue, {
              color: log.identity_check === 'yes' ? colors.success : log.identity_check === 'almost' ? colors.warning : colors.error,
            }]}>{log.identity_check.toUpperCase()}</Text>
          </View>
          {log.note ? (
            <View style={styles.noteBox}>
              <Text style={styles.noteLabel}>Reflection:</Text>
              <Text style={styles.noteText}>{log.note}</Text>
            </View>
          ) : (
            <Text style={styles.noNote}>No reflection recorded</Text>
          )}
        </>
      ) : (
        <Text style={styles.noData}>No data logged for this day</Text>
      )}
    </View>
  );
}

export default function MirrorScreen() {
  const identity = useIdentityStore((s) => s.identity);
  const currentDay = useIdentityStore((s) => s.currentDay);
  const loadDailyLogs = useIdentityStore((s) => s.loadDailyLogs);
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const fadeAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    const load = async () => {
      const data = await loadDailyLogs();
      setLogs(data);
      setLoading(false);
      Animated.timing(fadeAnim, { toValue: 1, duration: 500, useNativeDriver: true }).start();
    };
    load();
  }, []);

  const day1Log = logs.find((l) => l.day_number === 1);
  const todayLog = logs.find((l) => l.day_number === currentDay);

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

  return (
    <ScreenWrapper>
      <Animated.ScrollView style={[styles.scroll, { opacity: fadeAnim }]} contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
        <Text style={styles.title}>Then vs. Now</Text>
        <Text style={styles.subtitle}>Look at how much you've grown</Text>

        {identity && (
          <View style={styles.identityCard}>
            <Text style={styles.identityLabel}>Your identity</Text>
            <Text style={styles.identityTitle}>{identity.title}</Text>
            <Text style={styles.identityDate}>Started {formatDate(identity.start_date)}</Text>
          </View>
        )}

        <DayCard label="Where you started" day={1} log={day1Log} color={colors.textMuted} />
        <View style={styles.arrow}>
          <Text style={styles.arrowText}>↓</Text>
          <Text style={styles.arrowLabel}>{currentDay - 1} days of becoming</Text>
        </View>
        <DayCard label="Where you are now" day={currentDay} log={todayLog} color={colors.accent} />

        <View style={styles.insightCard}>
          <Text style={styles.insightTitle}>The bigger picture</Text>
          <View style={styles.insightRow}>
            <Text style={styles.insightLabel}>Days you showed up</Text>
            <Text style={styles.insightValue}>{logs.length} / {currentDay}</Text>
          </View>
          <View style={styles.insightRow}>
            <Text style={styles.insightLabel}>Consistency</Text>
            <Text style={styles.insightValue}>{currentDay > 0 ? Math.round((logs.length / currentDay) * 100) : 0}%</Text>
          </View>
          <View style={styles.insightRow}>
            <Text style={styles.insightLabel}>Days fully aligned</Text>
            <Text style={styles.insightValue}>{logs.filter((l) => l.identity_check === 'yes').length} days as your best self</Text>
          </View>
        </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.textSecondary, fontSize: fonts.sizes.md, marginBottom: spacing.xl },
  identityCard: { backgroundColor: colors.surface, borderRadius: borderRadius.md, padding: spacing.lg, marginBottom: spacing.xl, borderWidth: 1, borderColor: colors.primary, alignItems: 'center' },
  identityLabel: { color: colors.primary, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.bold, letterSpacing: 2, marginBottom: spacing.sm },
  identityTitle: { color: colors.text, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.semibold, textAlign: 'center', marginBottom: spacing.xs },
  identityDate: { color: colors.textMuted, fontSize: fonts.sizes.sm },
  dayCard: { backgroundColor: colors.surface, borderRadius: borderRadius.md, padding: spacing.lg, borderWidth: 1 },
  dayCardLabel: { fontSize: fonts.sizes.xs, fontWeight: fonts.weights.bold, letterSpacing: 2, marginBottom: spacing.sm },
  dayCardDay: { color: colors.text, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.bold, marginBottom: spacing.md },
  checkRow: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: spacing.sm },
  checkLabel: { color: colors.textSecondary, fontSize: fonts.sizes.sm },
  checkValue: { fontSize: fonts.sizes.sm, fontWeight: fonts.weights.bold },
  noteBox: { backgroundColor: colors.surfaceLight, borderRadius: borderRadius.sm, padding: spacing.md, marginTop: spacing.sm },
  noteLabel: { color: colors.textSecondary, fontSize: fonts.sizes.xs, marginBottom: spacing.xs },
  noteText: { color: colors.text, fontSize: fonts.sizes.sm, lineHeight: 20 },
  noNote: { color: colors.textMuted, fontSize: fonts.sizes.sm, fontStyle: 'italic' },
  noData: { color: colors.textMuted, fontSize: fonts.sizes.sm, fontStyle: 'italic' },
  arrow: { alignItems: 'center', paddingVertical: spacing.md },
  arrowText: { color: colors.primary, fontSize: 28 },
  arrowLabel: { color: colors.textSecondary, fontSize: fonts.sizes.sm, marginTop: spacing.xs },
  insightCard: { backgroundColor: colors.surface, borderRadius: borderRadius.md, padding: spacing.lg, marginTop: spacing.xl, borderWidth: 1, borderColor: colors.border },
  insightTitle: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.semibold, marginBottom: spacing.md },
  insightRow: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: spacing.sm, borderBottomWidth: 1, borderBottomColor: colors.border },
  insightLabel: { color: colors.textSecondary, fontSize: fonts.sizes.sm },
  insightValue: { color: colors.text, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.medium },
});
