import React, { useState, useRef, useCallback } from 'react';
import {
  View, Text, StyleSheet, Pressable,
  TouchableOpacity, Animated, KeyboardAvoidingView, Platform,
} from 'react-native';
import { useFocusEffect, CommonActions } from '@react-navigation/native';
let ViewShot, Sharing;
try {
  ViewShot = require('react-native-view-shot').default;
  Sharing = require('expo-sharing');
} catch (_) {}
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Button from '../components/Button';
import FadeIn from '../components/FadeIn';
import NovaAd from '../components/NovaAd';
import useIdentityStore from '../store/useIdentityStore';
import useHabitStore from '../store/useHabitStore';
import { generateDailyReflection, saveDailyJournal, getJournalEntry } from '../services/journalService';
import { trackDayCompleted, trackJournalSaved } from '../services/analytics';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';
import { getDayNarrative } from '../utils/helpers';

const MOODS = [
  { key: 'great', emoji: '🔥', label: 'Amazing' },
  { key: 'good', emoji: '😊', label: 'Good' },
  { key: 'okay', emoji: '😌', label: 'Okay' },
  { key: 'bad', emoji: '😔', label: 'Tough' },
  { key: 'terrible', emoji: '💀', label: 'Hard' },
];
const MOOD_EMOJIS = { great: '🔥', good: '😊', okay: '😌', bad: '😔', terrible: '💀' };

// Progress ring for day counter
function DayRing({ current, total }) {
  const pct = Math.min(current / total, 1);
  return (
    <View style={ringStyles.container}>
      <View style={ringStyles.track} />
      <View style={[ringStyles.fill, { width: `${pct * 100}%` }]} />
      <View style={ringStyles.center}>
        <Text style={ringStyles.day}>{current}</Text>
        <Text style={ringStyles.of}>/ {total}</Text>
      </View>
    </View>
  );
}
const ringStyles = StyleSheet.create({
  container: { alignSelf: 'center', width: 80, height: 80, borderRadius: 40, backgroundColor: colors.surface, borderWidth: 2, borderColor: colors.border, alignItems: 'center', justifyContent: 'center', marginBottom: spacing.md, overflow: 'hidden' },
  track: { ...StyleSheet.absoluteFillObject, backgroundColor: colors.surface },
  fill: { position: 'absolute', left: 0, top: 0, bottom: 0, backgroundColor: 'rgba(108, 99, 255, 0.15)' },
  center: { alignItems: 'center' },
  day: { color: colors.text, fontSize: fonts.sizes.xl, fontWeight: fonts.weights.bold },
  of: { color: colors.textMuted, fontSize: fonts.sizes.xs },
});

function formatMin(min) {
  if (!min || min <= 0) return null;
  if (min >= 60) return `${Math.floor(min / 60)}h${min % 60 > 0 ? `${min % 60}m` : ''}`;
  return `${min}m`;
}

function HabitItem({ habit, completed, onToggle }) {
  const dur = formatMin(habit.duration);
  const hasTime = habit.best_time && habit.best_time.length >= 4;
  const hasMeta = hasTime || dur;
  return (
    <TouchableOpacity
      style={[s.habitItem, completed && s.habitDone]}
      onPress={onToggle}
      activeOpacity={0.7}
    >
      <View style={[s.habitCheck, completed && s.habitCheckDone]}>
        {completed && <Text style={s.habitCheckIcon}>{'\u2713'}</Text>}
      </View>
      <View style={s.habitBody}>
        <Text style={[s.habitText, completed && s.habitTextDone]} numberOfLines={2}>{habit.title}</Text>
        {hasMeta && <View style={s.habitSep} />}
        {hasMeta && (
          <View style={s.habitMeta}>
            {hasTime && (
              <View style={s.habitMetaItem}>
                <View style={[s.habitMetaDot, { backgroundColor: colors.accent }]} />
                <Text style={s.habitMetaLabel}>{habit.best_time}</Text>
              </View>
            )}
            {dur && (
              <View style={s.habitMetaItem}>
                <View style={[s.habitMetaDot, { backgroundColor: colors.primary }]} />
                <Text style={s.habitMetaLabel}>{dur}</Text>
              </View>
            )}
          </View>
        )}
      </View>
      {completed && <Text style={s.habitDoneTag}>Done</Text>}
    </TouchableOpacity>
  );
}

export default function DailyScreen({ navigation }) {
  const identity = useIdentityStore((st) => st.identity);
  const currentDay = useIdentityStore((st) => st.currentDay);
  const fetchIdentity = useIdentityStore((st) => st.fetchIdentity);
  const habits = useHabitStore((st) => st.habits);
  const habitLogs = useHabitStore((st) => st.habitLogs);
  const toggleHabit = useHabitStore((st) => st.toggleHabit);
  const loadTodayLogs = useHabitStore((st) => st.loadTodayLogs);
  const [initialLoading, setInitialLoading] = useState(true);

  const [identityCheck, setIdentityCheck] = useState('');
  const [mood, setMood] = useState('');
  const [saving, setSaving] = useState(false);
  const [completed, setCompleted] = useState(false);
  const [savedEntry, setSavedEntry] = useState(null);
  const [focusCount, setFocusCount] = useState(0);

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

  useFocusEffect(
    useCallback(() => {
      const init = async () => {
        await fetchIdentity();
        const id = useIdentityStore.getState().identity;
        const day = useIdentityStore.getState().currentDay;
        if (!id) { setInitialLoading(false); navigation.dispatch(CommonActions.reset({ index: 0, routes: [{ name: 'IdentityStory' }] })); return; }
        if (day > 40) { navigation.dispatch(CommonActions.reset({ index: 0, routes: [{ name: 'Completion' }] })); return; }
        setInitialLoading(false);
        setFocusCount((c) => c + 1);
        loadTodayLogs();
        if (id?.id) {
          const existing = await getJournalEntry(id.id);
          if (existing && existing.ai_title) {
            setCompleted(true); setSavedEntry(existing);
            setIdentityCheck(existing.identity_check || ''); setMood(existing.mood || '');
          } else {
            setCompleted(false); setSavedEntry(null);
            setIdentityCheck(''); setMood('');
          }
        }
        Animated.timing(fadeAnim, { toValue: 1, duration: 600, useNativeDriver: true }).start();
      };
      init();
    }, [identity?.id])
  );

  const habitsCompleted = Object.values(habitLogs).filter(Boolean).length;
  const habitsTotal = habits.length;
  const allHabitsDone = habitsTotal > 0 && habitsCompleted === habitsTotal;
  const habitsPct = habitsTotal > 0 ? Math.round((habitsCompleted / habitsTotal) * 100) : 0;

  const handleCompleteDay = async () => {
    if (!identityCheck) { showAlert('Hold on', 'How did you show up as your new self today?'); return; }
    if (!mood) { showAlert('One more thing', 'How are you feeling right now?'); return; }
    setSaving(true);
    try {
      const ai = await generateDailyReflection({ mood });
      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 });
      trackDayCompleted(currentDay, identityCheck, mood);
      trackJournalSaved(currentDay);
    } catch (error) {
      showAlert('Oops', error?.message || 'Something went wrong. Give it another try.');
    } finally { setSaving(false); }
  };

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

  const narrative = getDayNarrative(currentDay);

  if (!identity || initialLoading) {
    return (<ScreenWrapper><View style={s.loadingWrap}><Text style={s.loadingText}>Loading your journey...</Text></View></ScreenWrapper>);
  }

  // ====== COMPLETED STATE ======
  if (completed && savedEntry?.ai_title) {
    const JournalCard = () => (
      <View style={s.journalCard}>
        <Text style={s.jBrand}>NOVA40</Text>
        <Text style={s.jEmoji}>{MOOD_EMOJIS[savedEntry.mood] || '\u2728'}</Text>
        <Text style={s.jTitle}>{savedEntry.ai_title}</Text>
        <Text style={s.jSummary}>{savedEntry.ai_summary}</Text>
        <View style={s.jDivider} />
        <Text style={s.jQuote}>"{savedEntry.ai_quote}"</Text>
        <View style={s.jFooter}>
          <Text style={s.jDay}>Day {currentDay}</Text>
          <Text style={s.jDate}>{new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</Text>
        </View>
        {identity?.title && <Text style={s.jIdentity}>{identity.title}</Text>}
      </View>
    );
    return (
      <ScreenWrapper>
        <Animated.ScrollView style={[s.flex, { opacity: fadeAnim }]} contentContainerStyle={s.scrollContent} showsVerticalScrollIndicator={false}>
          {/* Success header */}
          <View style={s.doneHeader}>
            <Text style={s.doneEmoji}>{'\u2728'}</Text>
            <Text style={s.doneTitle}>Day {currentDay} Complete!</Text>
            <Text style={s.doneSubtitle}>You showed up. That matters.</Text>
          </View>

          {ViewShot ? (<ViewShot ref={viewShotRef} options={{ format: 'png', quality: 1 }}><JournalCard /></ViewShot>) : (<JournalCard />)}

          <View style={s.actions}>
            <Button title="Share This" onPress={handleShare} style={s.actionBtn} />
          </View>

          {/* Entries removed */}
        </Animated.ScrollView>
      </ScreenWrapper>
    );
  }

  // ====== FORM STATE ======
  return (
    <ScreenWrapper>
      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={s.flex}>
        <Animated.ScrollView style={[s.flex, { opacity: fadeAnim }]} contentContainerStyle={s.scrollContent} showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled">

          {/* Hero section */}
          <FadeIn delay={0} trigger={focusCount}><View style={s.hero}>
            <DayRing current={currentDay} total={40} />
            <Text style={s.heroGreet}>
              {currentDay <= 3 ? "Let's build momentum!" : currentDay <= 20 ? 'Keep pushing forward!' : currentDay <= 35 ? "You're in the zone!" : 'The finish line is close!'}
            </Text>
            <Text style={s.heroNarrative}>{narrative}</Text>
          </View></FadeIn>

          {/* ── STEP 1: Habits ── */}
          <FadeIn delay={100} trigger={focusCount}><View style={s.section}>
            <View style={s.sectionHeader}>
              <Text style={s.sectionIcon}>{allHabitsDone ? '🔥' : '📋'}</Text>
              <View style={s.sectionHeaderText}>
                <Text style={s.sectionTitle}>Your habits for today</Text>
                <Text style={s.sectionMeta}>{habitsCompleted}/{habitsTotal} done</Text>
              </View>
              {/* Percentage badge */}
              <View style={[s.pctBadge, allHabitsDone && s.pctBadgeDone]}>
                <Text style={[s.pctText, allHabitsDone && s.pctTextDone]}>{habitsPct}%</Text>
              </View>
            </View>

            {/* Progress bar */}
            <View style={s.progressBar}>
              <Animated.View style={[s.progressFill, { width: `${habitsPct}%` }]} />
            </View>

            {habits.map((habit, i) => (
              <FadeIn key={habit.id} delay={150 + i * 80} trigger={focusCount}>
                <HabitItem habit={habit} completed={!!habitLogs[habit.id]} onToggle={() => toggleHabit(habit.id)} />
              </FadeIn>
            ))}

            {allHabitsDone && (
              <View style={s.allDoneBanner}>
                <Text style={s.allDoneEmoji}>🎉</Text>
                <Text style={s.allDoneText}>All habits done! You're crushing it today!</Text>
              </View>
            )}
          </View></FadeIn>

          <NovaAd />

          {/* ── STEP 2: Identity Check ── */}
          <FadeIn delay={200} trigger={focusCount}><View style={s.section}>
            <View style={s.sectionHeader}>
              <Text style={s.sectionIcon}>🪞</Text>
              <View>
                <Text style={s.sectionTitle}>How did you show up?</Text>
                <Text style={s.sectionMeta}>Did you live as "{identity?.title}" today?</Text>
              </View>
            </View>
            <View style={s.identityRow}>
              {[
                { key: 'yes', emoji: '✅', label: 'Yes!', color: colors.success },
                { key: 'almost', emoji: '🔶', label: 'Almost', color: colors.warning },
                { key: 'no', emoji: '❌', label: 'Not yet', color: colors.error },
              ].map((opt) => (
                <Pressable
                  key={opt.key}
                  style={[s.identityBtn, identityCheck === opt.key && { borderColor: opt.color, backgroundColor: `${opt.color}12` }]}
                  onPress={() => setIdentityCheck(opt.key)}
                >
                  <Text style={s.identityEmoji}>{opt.emoji}</Text>
                  <Text style={[s.identityLabel, identityCheck === opt.key && { color: opt.color, fontWeight: fonts.weights.bold }]}>{opt.label}</Text>
                </Pressable>
              ))}
            </View>
          </View></FadeIn>

          {/* ── STEP 3: Mood ── */}
          <FadeIn delay={300} trigger={focusCount}><View style={s.section}>
            <View style={s.sectionHeader}>
              <Text style={s.sectionIcon}>💭</Text>
              <Text style={s.sectionTitle}>How's your mood?</Text>
            </View>
            <View style={s.moodRow}>
              {MOODS.map((m) => (
                <Pressable key={m.key} style={[s.moodBtn, mood === m.key && s.moodBtnActive]} onPress={() => setMood(m.key)}>
                  <Text style={s.moodEmoji}>{m.emoji}</Text>
                  <Text style={[s.moodLabel, mood === m.key && s.moodLabelActive]}>{m.label}</Text>
                </Pressable>
              ))}
            </View>
          </View></FadeIn>

          {/* ── Submit ── */}
          <FadeIn delay={400} trigger={focusCount}>
          <Button
            title={saving ? 'Writing your reflection...' : allHabitsDone ? "Finish My Day — You crushed it! 🔥" : 'Finish My Day'}
            onPress={handleCompleteDay}
            loading={saving}
            disabled={!identityCheck || !mood}
            style={s.submitBtn}
          />
          {(!identityCheck || !mood) && (
            <Text style={s.submitHint}>
              {!identityCheck ? 'Select your identity check above' : 'Select your mood above'}
            </Text>
          )}
          </FadeIn>

        </Animated.ScrollView>
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}


const s = StyleSheet.create({
  flex: { flex: 1 },
  loadingWrap: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  loadingText: { color: colors.textSecondary, fontSize: fonts.sizes.md },
  scrollContent: { padding: spacing.md, paddingBottom: spacing.xxl * 2 },

  // Hero
  hero: { alignItems: 'center', marginBottom: spacing.md, paddingTop: spacing.xs },
  heroGreet: { color: colors.accent, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.semibold, letterSpacing: 1, marginBottom: spacing.xs },
  heroNarrative: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.semibold, textAlign: 'center', lineHeight: 22 },

  // Sections
  section: { marginBottom: spacing.md },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: spacing.sm, gap: spacing.sm },
  sectionIcon: { fontSize: 18 },
  sectionTitle: { color: colors.text, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.bold },
  sectionMeta: { color: colors.textMuted, fontSize: 10, marginTop: 1 },
  sectionHeaderText: { flex: 1 },
  pctBadge: { backgroundColor: colors.surface, borderRadius: borderRadius.full, paddingHorizontal: spacing.md, paddingVertical: spacing.xs, borderWidth: 1, borderColor: colors.border },
  pctBadgeDone: { backgroundColor: 'rgba(0,230,118,0.1)', borderColor: 'rgba(0,230,118,0.3)' },
  pctText: { color: colors.textSecondary, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.bold },
  pctTextDone: { color: colors.success },

  // Progress bar
  progressBar: { height: 3, backgroundColor: colors.surface, borderRadius: 2, marginBottom: spacing.sm, overflow: 'hidden' },
  progressFill: { height: '100%', backgroundColor: colors.primary, borderRadius: 2 },

  // Habits
  habitItem: { flexDirection: 'row', alignItems: 'flex-start', backgroundColor: colors.surface, borderRadius: borderRadius.sm, paddingVertical: spacing.sm, paddingHorizontal: spacing.md, marginBottom: 6, borderWidth: 1, borderColor: colors.border },
  habitDone: { borderColor: 'rgba(0,230,118,0.3)', backgroundColor: 'rgba(0,230,118,0.04)' },
  habitCheck: { width: 22, height: 22, borderRadius: 11, borderWidth: 2, borderColor: colors.textMuted, alignItems: 'center', justifyContent: 'center', marginRight: spacing.sm, marginTop: 2 },
  habitCheckDone: { borderColor: colors.success, backgroundColor: colors.success },
  habitCheckIcon: { color: '#fff', fontSize: 11, fontWeight: fonts.weights.bold },
  habitBody: { flex: 1 },
  habitText: { color: colors.text, fontSize: fonts.sizes.sm },
  habitTextDone: { color: colors.textSecondary, textDecorationLine: 'line-through' },
  habitSep: { height: 1, backgroundColor: colors.border, marginVertical: 5 },
  habitMeta: { flexDirection: 'row', gap: spacing.lg },
  habitMetaItem: { flexDirection: 'row', alignItems: 'center' },
  habitMetaDot: { width: 5, height: 5, borderRadius: 2.5, marginRight: 5 },
  habitMetaLabel: { color: colors.textSecondary, fontSize: 11 },
  habitDoneTag: { color: colors.success, fontSize: 10, fontWeight: fonts.weights.bold, marginLeft: spacing.sm, marginTop: 3 },
  allDoneBanner: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,230,118,0.08)', borderRadius: borderRadius.sm, padding: spacing.sm, marginTop: 4, borderWidth: 1, borderColor: 'rgba(0,230,118,0.2)' },
  allDoneEmoji: { fontSize: 14, marginRight: spacing.sm },
  allDoneText: { color: colors.success, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.semibold },

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

  // Mood
  moodRow: { flexDirection: 'row', justifyContent: 'space-between', gap: 4 },
  moodBtn: { alignItems: 'center', paddingVertical: spacing.sm, borderRadius: borderRadius.md, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.surface, flex: 1 },
  moodBtnActive: { borderColor: colors.primary, backgroundColor: 'rgba(108,99,255,0.12)' },
  moodEmoji: { fontSize: 20, marginBottom: 2 },
  moodLabel: { color: colors.textMuted, fontSize: 8, fontWeight: fonts.weights.medium },
  moodLabelActive: { color: colors.primary, fontWeight: fonts.weights.bold },

  // Submit
  submitBtn: { marginTop: spacing.sm },
  submitHint: { color: colors.textMuted, fontSize: fonts.sizes.xs, textAlign: 'center', marginTop: spacing.sm },

  // ====== Completed state ======
  doneHeader: { alignItems: 'center', paddingTop: spacing.lg, marginBottom: spacing.xl },
  doneEmoji: { fontSize: 48, marginBottom: spacing.md },
  doneTitle: { color: colors.text, fontSize: fonts.sizes.xxl, fontWeight: fonts.weights.bold, marginBottom: spacing.xs },
  doneSubtitle: { color: colors.textSecondary, fontSize: fonts.sizes.md },

  journalCard: { backgroundColor: colors.background, borderRadius: borderRadius.xl, padding: spacing.xl, borderWidth: 1, borderColor: 'rgba(108,99,255,0.25)', alignItems: 'center' },
  jBrand: { color: colors.primary, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.bold, letterSpacing: 5, marginBottom: spacing.lg },
  jEmoji: { fontSize: 36, marginBottom: spacing.md },
  jTitle: { color: colors.text, fontSize: fonts.sizes.xl, fontWeight: fonts.weights.bold, textAlign: 'center', lineHeight: 30, marginBottom: spacing.md },
  jSummary: { color: colors.textSecondary, fontSize: fonts.sizes.md, textAlign: 'center', lineHeight: 24, marginBottom: spacing.lg, paddingHorizontal: spacing.sm },
  jDivider: { width: 40, height: 2, backgroundColor: colors.primary, borderRadius: 1, marginBottom: spacing.lg },
  jQuote: { color: colors.accent, fontSize: fonts.sizes.md, fontStyle: 'italic', textAlign: 'center', lineHeight: 24, marginBottom: spacing.lg },
  jFooter: { flexDirection: 'row', justifyContent: 'center', gap: spacing.md, marginBottom: spacing.sm },
  jDay: { color: colors.textMuted, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.semibold },
  jDate: { color: colors.textMuted, fontSize: fonts.sizes.sm },
  jIdentity: { color: colors.textMuted, fontSize: fonts.sizes.xs, fontStyle: 'italic' },

  actions: { marginTop: spacing.xl },
  actionBtn: { marginBottom: spacing.sm },

});
