import React, { useState, useEffect, useRef } from 'react';
import {
  View, Text, StyleSheet, Share,
  Animated, ActivityIndicator,
} from 'react-native';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Planet from '../components/Planet';
import Button from '../components/Button';
import useIdentityStore from '../store/useIdentityStore';
import useHabitStore from '../store/useHabitStore';
import useAuthStore from '../store/useAuthStore';
import { generateTransformationStory } from '../services/storyService';
import { trackJourneyCompleted, trackShare } from '../services/analytics';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

export default function CompletionScreen({ navigation }) {
  const identity = useIdentityStore((s) => s.identity);
  const loadStats = useIdentityStore((s) => s.loadStats);
  const loadDailyLogs = useIdentityStore((s) => s.loadDailyLogs);
  const habits = useHabitStore((s) => s.habits);
  const logout = useAuthStore((s) => s.logout);
  const resetIdentity = useIdentityStore((s) => s.reset);
  const resetHabits = useHabitStore((s) => s.reset);

  const [stats, setStats] = useState(null);
  const [logs, setLogs] = useState([]);
  const [story, setStory] = useState(null);
  const [loadingStory, setLoadingStory] = useState(true);

  const fadeAnim = useRef(new Animated.Value(0)).current;
  const storyFade = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(fadeAnim, { toValue: 1, duration: 800, delay: 300, useNativeDriver: true }).start();

    const load = async () => {
      const [s, l] = await Promise.all([loadStats(), loadDailyLogs()]);
      setStats(s);
      setLogs(l);

      // Generate transformation story
      try {
        const result = await generateTransformationStory(identity, habits, l, s);
        setStory(result);
      } catch (_) {
        // fallback is handled inside the service
      }
      setLoadingStory(false);
      Animated.timing(storyFade, { toValue: 1, duration: 600, useNativeDriver: true }).start();

      // Track completion
      const total = (s?.discipline_score || 0) + (s?.focus_score || 0) + (s?.consistency_score || 0);
      trackJourneyCompleted(total, l.length);
    };
    load();
  }, []);

  const yesCount = logs.filter((l) => l.identity_check === 'yes').length;
  const totalScore =
    (stats?.discipline_score || 0) + (stats?.focus_score || 0) + (stats?.consistency_score || 0);

  const handleShare = async () => {
    const storyText = story
      ? `${story.title}\n\n${story.paragraphs.join('\n\n')}\n\n${story.closing_line}`
      : '';

    try {
      await Share.share({
        message: `I completed Nova40!\n\n${storyText}\n\n---\n"${identity?.title}"\n${yesCount}/40 days aligned | Score: ${totalScore}\n\n#Nova40 #Transformation`,
      });
      trackShare('completion_story');
    } catch (_) { /* cancelled */ }
  };

  const handleNewJourney = () => {
    showAlert('Ready for another round?', 'Want to start fresh with a new identity?', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Begin',
        onPress: async () => {
          resetIdentity();
          resetHabits();
          await logout();
          navigation.reset({ index: 0, routes: [{ name: 'Login' }] });
        },
      },
    ]);
  };

  return (
    <ScreenWrapper>
      <Animated.ScrollView
        style={[styles.scroll, { opacity: fadeAnim }]}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View style={styles.header}>
          <Planet size={70} glowIntensity={1} />
          <Text style={styles.congrats}>You did it</Text>
          <Text style={styles.headerTitle}>40 days. You showed up. You changed.</Text>
        </View>

        {/* Transformation Story */}
        {loadingStory ? (
          <View style={styles.storyLoading}>
            <ActivityIndicator size="small" color={colors.primary} />
            <Text style={styles.storyLoadingText}>Putting your journey into words...</Text>
          </View>
        ) : story ? (
          <Animated.View style={[styles.storyCard, { opacity: storyFade }]}>
            <Text style={styles.storyBadge}>
              {story.source === 'ai' ? '✦ AI-Written Story' : '✦ Your Story'}
            </Text>
            <Text style={styles.storyTitle}>{story.title}</Text>
            {story.paragraphs.map((p, i) => (
              <Text key={i} style={styles.storyParagraph}>{p}</Text>
            ))}
            <Text style={styles.closingLine}>{story.closing_line}</Text>
          </Animated.View>
        ) : null}

        {/* Identity Card */}
        <View style={styles.card}>
          <Text style={styles.cardLabel}>Your identity</Text>
          <Text style={styles.cardTitle}>{identity?.title}</Text>
        </View>

        {/* Stats Card */}
        <View style={styles.card}>
          <Text style={styles.cardLabel}>Your final stats</Text>
          <View style={styles.statGrid}>
            <View style={styles.statItem}>
              <Text style={[styles.statValue, { color: colors.primary }]}>
                {stats?.discipline_score || 0}
              </Text>
              <Text style={styles.statLabel}>Discipline</Text>
            </View>
            <View style={styles.statItem}>
              <Text style={[styles.statValue, { color: colors.accent }]}>
                {stats?.focus_score || 0}
              </Text>
              <Text style={styles.statLabel}>Focus</Text>
            </View>
            <View style={styles.statItem}>
              <Text style={[styles.statValue, { color: colors.success }]}>
                {stats?.consistency_score || 0}
              </Text>
              <Text style={styles.statLabel}>Consistency</Text>
            </View>
          </View>

          <View style={styles.divider} />

          <StatRow label="Days Logged" value={`${logs.length} / 40`} />
          <StatRow label="Fully Aligned" value={`${yesCount} days`} />
          <StatRow label="Total Score" value={totalScore} color={colors.accent} />
        </View>

        {/* Actions */}
        <View style={styles.actions}>
          <Button title="Share My Story" onPress={handleShare} style={styles.actionBtn} />
          <Button
            title="Begin Again"
            variant="secondary"
            onPress={handleNewJourney}
            style={styles.actionBtn}
          />
        </View>
      </Animated.ScrollView>
    </ScreenWrapper>
  );
}

function StatRow({ label, value, color }) {
  return (
    <View style={styles.summaryRow}>
      <Text style={styles.summaryLabel}>{label}</Text>
      <Text style={[styles.summaryValue, color && { color }]}>{value}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  scroll: { flex: 1 },
  scrollContent: {
    padding: spacing.lg,
    paddingBottom: spacing.xxl * 2,
    alignItems: 'center',
  },

  // Header
  header: {
    alignItems: 'center',
    marginBottom: spacing.xl,
    paddingTop: spacing.lg,
  },
  congrats: {
    color: colors.accent,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.bold,
    letterSpacing: 3,
    marginTop: spacing.lg,
    marginBottom: spacing.sm,
  },
  headerTitle: {
    color: colors.text,
    fontSize: fonts.sizes.xl,
    fontWeight: fonts.weights.bold,
    textAlign: 'center',
  },

  // Story
  storyLoading: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: spacing.xl,
    gap: spacing.sm,
  },
  storyLoadingText: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.sm,
  },
  storyCard: {
    backgroundColor: colors.surface,
    borderRadius: borderRadius.lg,
    padding: spacing.xl,
    width: '100%',
    marginBottom: spacing.lg,
    borderWidth: 1,
    borderColor: 'rgba(108, 99, 255, 0.3)',
  },
  storyBadge: {
    color: colors.primaryLight,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.medium,
    marginBottom: spacing.lg,
  },
  storyTitle: {
    color: colors.text,
    fontSize: fonts.sizes.xl,
    fontWeight: fonts.weights.bold,
    marginBottom: spacing.lg,
    lineHeight: 30,
  },
  storyParagraph: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    lineHeight: 26,
    marginBottom: spacing.md,
  },
  closingLine: {
    color: colors.accent,
    fontSize: fonts.sizes.md,
    fontWeight: fonts.weights.semibold,
    fontStyle: 'italic',
    marginTop: spacing.md,
    lineHeight: 24,
  },

  // Cards
  card: {
    backgroundColor: colors.surface,
    borderRadius: borderRadius.lg,
    padding: spacing.lg,
    width: '100%',
    marginBottom: spacing.md,
    borderWidth: 1,
    borderColor: colors.border,
  },
  cardLabel: {
    color: colors.primary,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.bold,
    letterSpacing: 2,
    marginBottom: spacing.sm,
  },
  cardTitle: {
    color: colors.text,
    fontSize: fonts.sizes.lg,
    fontWeight: fonts.weights.semibold,
  },

  // Stats
  statGrid: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: spacing.md,
  },
  statItem: { alignItems: 'center' },
  statValue: {
    fontSize: fonts.sizes.xxl,
    fontWeight: fonts.weights.bold,
  },
  statLabel: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.xs,
    marginTop: spacing.xs,
  },
  divider: {
    height: 1,
    backgroundColor: colors.border,
    marginVertical: spacing.md,
  },
  summaryRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: spacing.sm,
  },
  summaryLabel: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.sm,
  },
  summaryValue: {
    color: colors.text,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.semibold,
  },

  // Actions
  actions: {
    width: '100%',
    marginTop: spacing.lg,
  },
  actionBtn: {
    marginBottom: spacing.sm,
  },
});
