import React, { useRef, useEffect } from 'react';
import {
  View, Text, StyleSheet, Animated, Platform,
} from 'react-native';
import { showAlert } from '../components/NovaAlert';
import ViewShot from 'react-native-view-shot';
import * as Sharing from 'expo-sharing';
import * as MediaLibrary from 'expo-media-library';
import * as Print from 'expo-print';
import ScreenWrapper from '../components/ScreenWrapper';
import Button from '../components/Button';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

export default function JournalResultScreen({ navigation, route }) {
  const {
    aiTitle, aiSummary, aiQuote,
    source, dayNumber, date, mood, identityTitle,
  } = route.params;

  const viewShotRef = useRef(null);
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const cardScale = useRef(new Animated.Value(0.9)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, { toValue: 1, duration: 600, useNativeDriver: true }),
      Animated.spring(cardScale, { toValue: 1, useNativeDriver: true, speed: 10, bounciness: 8 }),
    ]).start();
  }, []);

  const moodEmojis = { great: '😄', good: '🙂', okay: '😐', bad: '😔', terrible: '😞' };

  // --- Share image ---
  const handleShare = async () => {
    try {
      const uri = await viewShotRef.current.capture();
      await Sharing.shareAsync(uri, { mimeType: 'image/png' });
    } catch (e) {
      showAlert('Error', 'Could not share image.');
    }
  };

  // --- Save to gallery ---
  const handleSaveImage = async () => {
    try {
      const { status } = await MediaLibrary.requestPermissionsAsync();
      if (status !== 'granted') {
        showAlert('Permission needed', 'Allow access to save images.');
        return;
      }
      const uri = await viewShotRef.current.capture();
      await MediaLibrary.saveToLibraryAsync(uri);
      showAlert('Saved', 'Journal card saved to your gallery.');
    } catch (e) {
      showAlert('Error', 'Could not save image.');
    }
  };

  // --- Export PDF ---
  const handleExportPDF = async () => {
    try {
      const html = `
        <html>
        <head>
          <style>
            body { font-family: -apple-system, sans-serif; padding: 40px; background: #0A0E1A; color: #FFFFFF; }
            .header { text-align: center; color: #6C63FF; font-size: 14px; letter-spacing: 4px; margin-bottom: 30px; }
            .title { font-size: 28px; font-weight: bold; margin-bottom: 20px; text-align: center; }
            .summary { font-size: 16px; line-height: 1.8; color: #8A8FB5; margin-bottom: 30px; text-align: center; }
            .quote { font-size: 18px; font-style: italic; color: #00E5FF; text-align: center; margin-bottom: 30px; }
            .meta { text-align: center; color: #4A5078; font-size: 13px; }
            .divider { border-top: 1px solid #1E2548; margin: 20px 0; }
          </style>
        </head>
        <body>
          <div class="header">NOVA40 — DAILY JOURNAL</div>
          <div class="title">${aiTitle}</div>
          <div class="summary">${aiSummary}</div>
          <div class="divider"></div>
          <div class="quote">"${aiQuote}"</div>
          <div class="divider"></div>
          <div class="meta">Day ${dayNumber} — ${date}</div>
          <div class="meta">${identityTitle || ''}</div>
        </body>
        </html>
      `;

      const { uri } = await Print.printToFileAsync({ html });

      if (Platform.OS === 'ios') {
        await Sharing.shareAsync(uri);
      } else {
        await Sharing.shareAsync(uri, { mimeType: 'application/pdf' });
      }
    } catch (e) {
      showAlert('Error', 'Could not generate PDF.');
    }
  };

  return (
    <ScreenWrapper>
      <Animated.ScrollView
        style={[styles.scroll, { opacity: fadeAnim }]}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* Source badge */}
        <View style={styles.badge}>
          <Text style={styles.badgeText}>
            {source === 'ai' ? '✦ AI Reflection' : '✦ Daily Reflection'}
          </Text>
        </View>

        {/* Shareable card */}
        <Animated.View style={{ transform: [{ scale: cardScale }] }}>
          <ViewShot
            ref={viewShotRef}
            options={{ format: 'png', quality: 1 }}
          >
            <View style={styles.card}>
              {/* Card header */}
              <Text style={styles.cardBrand}>NOVA40</Text>

              {/* Mood */}
              <Text style={styles.moodEmoji}>{moodEmojis[mood] || '✦'}</Text>

              {/* Title */}
              <Text style={styles.cardTitle}>{aiTitle}</Text>

              {/* Summary */}
              <Text style={styles.cardSummary}>{aiSummary}</Text>

              {/* Divider */}
              <View style={styles.cardDivider} />

              {/* Quote */}
              <Text style={styles.cardQuote}>"{aiQuote}"</Text>

              {/* Footer */}
              <View style={styles.cardFooter}>
                <Text style={styles.cardDay}>Day {dayNumber}</Text>
                <Text style={styles.cardDate}>{date}</Text>
              </View>

              {identityTitle && (
                <Text style={styles.cardIdentity}>{identityTitle}</Text>
              )}
            </View>
          </ViewShot>
        </Animated.View>

        {/* Actions */}
        <View style={styles.actions}>
          <Button title="Share" onPress={handleShare} style={styles.actionBtn} />

          <View style={styles.actionRow}>
            <Button
              title="Save Image"
              onPress={handleSaveImage}
              variant="secondary"
              style={styles.halfBtn}
            />
            <Button
              title="Export PDF"
              onPress={handleExportPDF}
              variant="secondary"
              style={styles.halfBtn}
            />
          </View>

          <Button
            title="Done"
            onPress={() => navigation.goBack()}
            variant="secondary"
            style={styles.actionBtn}
          />
        </View>
      </Animated.ScrollView>
    </ScreenWrapper>
  );
}

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

  badge: {
    alignSelf: 'center',
    backgroundColor: 'rgba(108, 99, 255, 0.08)',
    borderRadius: borderRadius.full,
    paddingVertical: spacing.xs,
    paddingHorizontal: spacing.md,
    borderWidth: 1,
    borderColor: 'rgba(108, 99, 255, 0.2)',
    marginBottom: spacing.lg,
  },
  badgeText: {
    color: colors.primaryLight,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.medium,
  },

  // Card
  card: {
    backgroundColor: colors.background,
    borderRadius: borderRadius.xl,
    padding: spacing.xl,
    borderWidth: 1,
    borderColor: 'rgba(108, 99, 255, 0.25)',
    alignItems: 'center',
    width: '100%',
  },
  cardBrand: {
    color: colors.primary,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.bold,
    letterSpacing: 5,
    marginBottom: spacing.lg,
  },
  moodEmoji: {
    fontSize: 36,
    marginBottom: spacing.md,
  },
  cardTitle: {
    color: colors.text,
    fontSize: fonts.sizes.xl,
    fontWeight: fonts.weights.bold,
    textAlign: 'center',
    lineHeight: 30,
    marginBottom: spacing.md,
  },
  cardSummary: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    textAlign: 'center',
    lineHeight: 24,
    marginBottom: spacing.lg,
    paddingHorizontal: spacing.sm,
  },
  cardDivider: {
    width: 40,
    height: 2,
    backgroundColor: colors.primary,
    borderRadius: 1,
    marginBottom: spacing.lg,
  },
  cardQuote: {
    color: colors.accent,
    fontSize: fonts.sizes.md,
    fontStyle: 'italic',
    textAlign: 'center',
    lineHeight: 24,
    marginBottom: spacing.lg,
    paddingHorizontal: spacing.sm,
  },
  cardFooter: {
    flexDirection: 'row',
    justifyContent: 'center',
    gap: spacing.md,
    marginBottom: spacing.sm,
  },
  cardDay: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.semibold,
  },
  cardDate: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
  },
  cardIdentity: {
    color: colors.textMuted,
    fontSize: fonts.sizes.xs,
    fontStyle: 'italic',
  },

  // Actions
  actions: {
    width: '100%',
    marginTop: spacing.xl,
  },
  actionBtn: {
    marginBottom: spacing.sm,
  },
  actionRow: {
    flexDirection: 'row',
    gap: spacing.sm,
    marginBottom: spacing.sm,
  },
  halfBtn: {
    flex: 1,
  },
});
