import React, { useState, useRef, useCallback } from 'react';
import {
  View, Text, StyleSheet, Pressable,
  TouchableOpacity, Animated, KeyboardAvoidingView, Platform,
} from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
let ViewShot, Sharing, MediaLibrary, Print;
try {
  ViewShot = require('react-native-view-shot').default;
  Sharing = require('expo-sharing');
  MediaLibrary = require('expo-media-library');
  Print = require('expo-print');
} catch (_) {
  // Modules unavailable — share features disabled
}
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Button from '../components/Button';
import Input from '../components/Input';
import useIdentityStore from '../store/useIdentityStore';
import useHabitStore from '../store/useHabitStore';
import { generateDailyReflection, saveDailyJournal, getJournalEntry } from '../services/journalService';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';
import { getDayNarrative } from '../utils/helpers';

const MOODS = [
  { key: 'great', emoji: '😄', label: 'Great' },
  { key: 'good', emoji: '🙂', label: 'Good' },
  { key: 'okay', emoji: '😐', label: 'Okay' },
  { key: 'bad', emoji: '😔', label: 'Bad' },
  { key: 'terrible', emoji: '😞', label: 'Awful' },
];

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

function HabitItem({ habit, completed, onToggle, disabled }) {
  return (
    <TouchableOpacity
      style={[styles.habitItem, completed && styles.habitCompleted]}
      onPress={onToggle}
      activeOpacity={0.7}
      disabled={disabled}
    >
      <View style={[styles.checkbox, completed && styles.checkboxChecked]}>
        {completed && <Text style={styles.checkmark}>✓</Text>}
      </View>
      <View style={styles.habitContent}>
        <Text style={[styles.habitTitle, completed && styles.habitTitleDone]}>{habit.title}</Text>
        {habit.description ? <Text style={styles.habitDesc}>{habit.description}</Text> : null}
      </View>
    </TouchableOpacity>
  );
}

export default function DailyScreen() {
  const identity = useIdentityStore((s) => s.identity);
  const currentDay = useIdentityStore((s) => s.currentDay);
  const habits = useHabitStore((s) => s.habits);
  const habitLogs = useHabitStore((s) => s.habitLogs);
  const toggleHabit = useHabitStore((s) => s.toggleHabit);
  const loadTodayLogs = useHabitStore((s) => s.loadTodayLogs);

  const [identityCheck, setIdentityCheck] = useState('');
  const [mood, setMood] = useState('');
  const [win, setWin] = useState('');
  const [struggle, setStruggle] = useState('');
  const [highlight, setHighlight] = useState('');
  const [note, setNote] = useState('');
  const [saving, setSaving] = useState(false);

  // Already completed today
  const [completed, setCompleted] = useState(false);
  const [savedEntry, setSavedEntry] = useState(null);

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

  useFocusEffect(
    useCallback(() => {
      const init = async () => {
        loadTodayLogs();

        // Check if today is already completed
        if (identity?.id) {
          const existing = await getJournalEntry(identity.id);
          if (existing && existing.ai_title) {
            setCompleted(true);
            setSavedEntry(existing);
            // Fill form with saved data
            setIdentityCheck(existing.identity_check || '');
            setMood(existing.mood || '');
            setWin(existing.win || '');
            setStruggle(existing.struggle || '');
            setHighlight(existing.highlight || '');
            setNote(existing.note || '');
          } else {
            setCompleted(false);
            setSavedEntry(null);
            setIdentityCheck('');
            setMood('');
            setWin('');
            setStruggle('');
            setHighlight('');
            setNote('');
          }
        }

        Animated.timing(fadeAnim, { toValue: 1, duration: 600, useNativeDriver: true }).start();
      };
      init();
    }, [identity?.id])
  );

  const habitsCompleted = Object.values(habitLogs).filter(Boolean).length;

  const handleCompleteDay = async () => {
    if (!identityCheck) {
      showAlert('Identity Check', 'Did you embody your identity today?');
      return;
    }
    if (!mood) {
      showAlert('Mood', 'How are you feeling today?');
      return;
    }

    setSaving(true);
    try {
      const ai = await generateDailyReflection({ mood, win, struggle, highlight, note });

      const saved = await saveDailyJournal(identity.id, currentDay, {
        identityCheck,
        habitsCompleted,
        mood, win, struggle, highlight, note,
        aiTitle: ai.title,
        aiSummary: ai.summary,
        aiQuote: ai.quote,
      });

      setCompleted(true);
      setSavedEntry({ ...saved, ai_title: ai.title, ai_summary: ai.summary, ai_quote: ai.quote });
    } catch (error) {
      console.warn('DailyScreen save error:', error);
      showAlert('Error', error?.message || 'Failed to save. Try again.');
    } finally {
      setSaving(false);
    }
  };

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

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

  const handleExportPDF = async () => {
    try {
      const e = savedEntry;
      const dateStr = new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
      const html = `<html><head><style>
        body{font-family:-apple-system,sans-serif;padding:40px;background:#0A0E1A;color:#FFF}
        .brand{text-align:center;color:#6C63FF;font-size:14px;letter-spacing:4px;margin-bottom:30px}
        .title{font-size:26px;font-weight:bold;text-align:center;margin-bottom:16px}
        .summary{font-size:16px;line-height:1.8;color:#8A8FB5;text-align:center;margin-bottom:24px}
        .quote{font-size:18px;font-style:italic;color:#00E5FF;text-align:center;margin-bottom:24px}
        .meta{text-align:center;color:#4A5078;font-size:13px}
        .divider{border-top:1px solid #1E2548;margin:16px 0}
      </style></head><body>
        <div class="brand">NOVA40 — DAILY JOURNAL</div>
        <div class="title">${e?.ai_title || ''}</div>
        <div class="summary">${e?.ai_summary || ''}</div>
        <div class="divider"></div>
        <div class="quote">"${e?.ai_quote || ''}"</div>
        <div class="divider"></div>
        <div class="meta">Day ${currentDay} — ${dateStr}</div>
        <div class="meta">${identity?.title || ''}</div>
      </body></html>`;
      const { uri } = await Print.printToFileAsync({ html });
      await Sharing.shareAsync(uri, { mimeType: 'application/pdf' });
    } catch (_) { showAlert('Error', 'Could not generate PDF.'); }
  };

  const narrative = getDayNarrative(currentDay);

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

  return (
    <ScreenWrapper>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        style={styles.flex}
      >
        <Animated.ScrollView
          style={[styles.flex, { opacity: fadeAnim }]}
          contentContainerStyle={styles.scrollContent}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
        >
          <Text style={styles.dayLabel}>DAY {currentDay} OF 40</Text>
          <Text style={styles.narrative}>{narrative}</Text>

          {/* === COMPLETED STATE: show journal card + actions === */}
          {completed && savedEntry?.ai_title ? (
            <>
              {/* Completion badge */}
              <View style={styles.completedBadge}>
                <Text style={styles.completedBadgeText}>✓ Day {currentDay} Complete</Text>
              </View>

              {/* Shareable journal card */}
              {ViewShot ? (
                <ViewShot ref={viewShotRef} options={{ format: 'png', quality: 1 }}>
                  <View style={styles.journalCard}>
                    <Text style={styles.cardBrand}>NOVA40</Text>
                    <Text style={styles.cardMoodEmoji}>{MOOD_EMOJIS[savedEntry.mood] || '✦'}</Text>
                    <Text style={styles.cardTitle}>{savedEntry.ai_title}</Text>
                    <Text style={styles.cardSummary}>{savedEntry.ai_summary}</Text>
                    <View style={styles.cardDivider} />
                    <Text style={styles.cardQuote}>"{savedEntry.ai_quote}"</Text>
                    <View style={styles.cardFooter}>
                      <Text style={styles.cardDay}>Day {currentDay}</Text>
                      <Text style={styles.cardDate}>
                        {new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                      </Text>
                    </View>
                    {identity?.title && <Text style={styles.cardIdentity}>{identity.title}</Text>}
                  </View>
                </ViewShot>
              ) : (
                <View style={styles.journalCard}>
                  <Text style={styles.cardBrand}>NOVA40</Text>
                  <Text style={styles.cardMoodEmoji}>{MOOD_EMOJIS[savedEntry.mood] || '✦'}</Text>
                  <Text style={styles.cardTitle}>{savedEntry.ai_title}</Text>
                  <Text style={styles.cardSummary}>{savedEntry.ai_summary}</Text>
                  <View style={styles.cardDivider} />
                  <Text style={styles.cardQuote}>"{savedEntry.ai_quote}"</Text>
                  <View style={styles.cardFooter}>
                    <Text style={styles.cardDay}>Day {currentDay}</Text>
                    <Text style={styles.cardDate}>
                      {new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                    </Text>
                  </View>
                  {identity?.title && <Text style={styles.cardIdentity}>{identity.title}</Text>}
                </View>
              )}

              {/* Share actions */}
              <View style={styles.actions}>
                <Button title="Share Journal" 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>
              </View>

              {/* Show what was logged */}
              <View style={styles.loggedSection}>
                <Text style={styles.loggedTitle}>What you logged</Text>
                {savedEntry.win ? <LoggedRow label="Win" value={savedEntry.win} /> : null}
                {savedEntry.struggle ? <LoggedRow label="Struggle" value={savedEntry.struggle} /> : null}
                {savedEntry.highlight ? <LoggedRow label="Highlight" value={savedEntry.highlight} /> : null}
                {savedEntry.note ? <LoggedRow label="Reflection" value={savedEntry.note} /> : null}
              </View>
            </>
          ) : (
            <>
              {/* === FORM STATE: habits + journal inputs === */}

              {/* Habits */}
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>Today's Habits</Text>
                {habits.map((habit) => (
                  <HabitItem
                    key={habit.id}
                    habit={habit}
                    completed={!!habitLogs[habit.id]}
                    onToggle={() => toggleHabit(habit.id)}
                    disabled={false}
                  />
                ))}
                <Text style={styles.habitCount}>{habitsCompleted}/{habits.length} completed</Text>
              </View>

              {/* Identity Check */}
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>Identity Check</Text>
                <Text style={styles.sectionSubtitle}>Did you embody "{identity?.title}" today?</Text>
                <View style={styles.identityRow}>
                  {[
                    { key: 'yes', label: 'Yes', color: colors.success },
                    { key: 'almost', label: 'Almost', color: colors.warning },
                    { key: 'no', label: 'No', color: colors.error },
                  ].map((opt) => (
                    <Pressable
                      key={opt.key}
                      style={[styles.identityBtn, identityCheck === opt.key && { borderColor: opt.color, backgroundColor: `${opt.color}10` }]}
                      onPress={() => setIdentityCheck(opt.key)}
                    >
                      <Text style={[styles.identityLabel, identityCheck === opt.key && { color: opt.color }]}>{opt.label}</Text>
                    </Pressable>
                  ))}
                </View>
              </View>

              {/* Mood */}
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>How are you feeling?</Text>
                <View style={styles.moodRow}>
                  {MOODS.map((m) => (
                    <Pressable key={m.key} style={[styles.moodBtn, mood === m.key && styles.moodBtnSelected]} onPress={() => setMood(m.key)}>
                      <Text style={styles.moodEmoji}>{m.emoji}</Text>
                      <Text style={[styles.moodLabel, mood === m.key && styles.moodLabelSelected]}>{m.label}</Text>
                    </Pressable>
                  ))}
                </View>
              </View>

              {/* Journal */}
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>Daily Journal</Text>
                <Input label="What went well?" value={win} onChangeText={setWin} placeholder="A small or big win..." />
                <Input label="What was difficult?" value={struggle} onChangeText={setStruggle} placeholder="A challenge you faced..." />
                <Input label="Highlight of the day" value={highlight} onChangeText={setHighlight} placeholder="A moment that stood out..." />
                <Input label="Reflection" value={note} onChangeText={setNote} placeholder="Anything on your mind..." multiline />
              </View>

              {/* Complete Day */}
              <Button
                title={saving ? 'Generating reflection...' : 'Complete Day'}
                onPress={handleCompleteDay}
                loading={saving}
                disabled={!identityCheck || !mood}
                style={styles.completeBtn}
              />
            </>
          )}
        </Animated.ScrollView>
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}

function LoggedRow({ label, value }) {
  return (
    <View style={styles.loggedRow}>
      <Text style={styles.loggedLabel}>{label}</Text>
      <Text style={styles.loggedValue}>{value}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1 },
  loadingContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  loadingText: { color: colors.textSecondary, fontSize: fonts.sizes.md },
  scrollContent: { padding: spacing.lg, paddingBottom: spacing.xxl * 2 },
  dayLabel: { color: colors.accent, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.bold, letterSpacing: 3, marginBottom: spacing.sm },
  narrative: { color: colors.text, fontSize: fonts.sizes.xl, fontWeight: fonts.weights.semibold, lineHeight: 32, marginBottom: spacing.xl },

  section: { marginBottom: spacing.xl },
  sectionTitle: { color: colors.text, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.semibold, marginBottom: spacing.sm },
  sectionSubtitle: { color: colors.textSecondary, fontSize: fonts.sizes.sm, marginBottom: spacing.md },

  // Habits
  habitItem: { flexDirection: 'row', alignItems: 'center', backgroundColor: colors.surface, borderRadius: borderRadius.md, padding: spacing.md, marginBottom: spacing.sm, borderWidth: 1, borderColor: colors.border },
  habitCompleted: { borderColor: colors.success, backgroundColor: 'rgba(0, 230, 118, 0.05)' },
  checkbox: { width: 28, height: 28, borderRadius: 14, borderWidth: 2, borderColor: colors.textMuted, alignItems: 'center', justifyContent: 'center', marginRight: spacing.md },
  checkboxChecked: { borderColor: colors.success, backgroundColor: colors.success },
  checkmark: { color: colors.background, fontSize: 14, fontWeight: fonts.weights.bold },
  habitContent: { flex: 1 },
  habitTitle: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.medium },
  habitTitleDone: { textDecorationLine: 'line-through', opacity: 0.6 },
  habitDesc: { color: colors.textSecondary, fontSize: fonts.sizes.sm, marginTop: 2 },
  habitCount: { color: colors.textMuted, fontSize: fonts.sizes.sm, textAlign: 'center', marginTop: spacing.sm },

  // Identity check
  identityRow: { flexDirection: 'row', gap: spacing.sm },
  identityBtn: { flex: 1, alignItems: 'center', paddingVertical: spacing.md, borderRadius: borderRadius.md, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.surface },
  identityLabel: { color: colors.textSecondary, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.medium },

  // Mood
  moodRow: { flexDirection: 'row', justifyContent: 'space-between' },
  moodBtn: { alignItems: 'center', paddingVertical: spacing.sm, paddingHorizontal: spacing.sm, borderRadius: borderRadius.md, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.surface, flex: 1, marginHorizontal: 3 },
  moodBtnSelected: { borderColor: colors.primary, backgroundColor: 'rgba(108, 99, 255, 0.1)' },
  moodEmoji: { fontSize: 20, marginBottom: 3 },
  moodLabel: { color: colors.textMuted, fontSize: 9, fontWeight: fonts.weights.medium },
  moodLabelSelected: { color: colors.primary },

  completeBtn: { marginTop: spacing.md },

  // === Completed state ===
  completedBadge: {
    alignSelf: 'center',
    backgroundColor: 'rgba(0, 230, 118, 0.1)',
    borderRadius: borderRadius.full,
    paddingVertical: spacing.sm,
    paddingHorizontal: spacing.lg,
    borderWidth: 1,
    borderColor: 'rgba(0, 230, 118, 0.3)',
    marginBottom: spacing.xl,
  },
  completedBadgeText: {
    color: colors.success,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.semibold,
  },

  // Journal card
  journalCard: {
    backgroundColor: colors.background,
    borderRadius: borderRadius.xl,
    padding: spacing.xl,
    borderWidth: 1,
    borderColor: 'rgba(108, 99, 255, 0.25)',
    alignItems: 'center',
  },
  cardBrand: { color: colors.primary, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.bold, letterSpacing: 5, marginBottom: spacing.lg },
  cardMoodEmoji: { 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: { marginTop: spacing.xl },
  actionBtn: { marginBottom: spacing.sm },
  actionRow: { flexDirection: 'row', gap: spacing.sm, marginBottom: spacing.sm },
  halfBtn: { flex: 1 },

  // Logged data
  loggedSection: {
    marginTop: spacing.xl,
    backgroundColor: colors.surface,
    borderRadius: borderRadius.md,
    padding: spacing.lg,
    borderWidth: 1,
    borderColor: colors.border,
  },
  loggedTitle: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.semibold, marginBottom: spacing.md },
  loggedRow: { marginBottom: spacing.md },
  loggedLabel: { color: colors.textMuted, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.medium, marginBottom: spacing.xs },
  loggedValue: { color: colors.textSecondary, fontSize: fonts.sizes.sm, lineHeight: 20 },
});
