import React, { useRef, useState, useCallback } from 'react';
import { View, Text, TextInput, Image, StyleSheet, Animated, Pressable } from 'react-native';
import { CommonActions, useFocusEffect } from '@react-navigation/native';
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 useAuthStore from '../store/useAuthStore';
import useIdentityStore from '../store/useIdentityStore';
import useHabitStore from '../store/useHabitStore';
import { getProfile } from '../services/profileService';
import * as offline from '../services/offlineStorage';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';
import { formatDate, getDayPhase } from '../utils/helpers';

// --- Reusable guide components ---
function Section({ icon, title, children }) {
  return (
    <View style={gs.box}>
      <View style={gs.boxHead}>
        <Text style={gs.boxIcon}>{icon}</Text>
        <Text style={gs.boxTitle}>{title}</Text>
      </View>
      {children}
    </View>
  );
}
function Rule({ label, value, color }) {
  return (
    <View style={gs.rule}>
      <View style={[gs.dot, { backgroundColor: color }]} />
      <Text style={gs.ruleLabel} numberOfLines={1}>{label}</Text>
      <Text style={[gs.ruleVal, { color }]} numberOfLines={1}>{value}</Text>
    </View>
  );
}
const gs = StyleSheet.create({
  box: { backgroundColor: colors.surface, borderRadius: borderRadius.sm, padding: spacing.sm, marginBottom: 6, borderWidth: 1, borderColor: colors.border },
  boxHead: { flexDirection: 'row', alignItems: 'center', marginBottom: 6 },
  boxIcon: { fontSize: 14, marginRight: 6 },
  boxTitle: { color: colors.text, fontSize: 12, fontWeight: fonts.weights.bold },
  rule: { flexDirection: 'row', alignItems: 'center', paddingVertical: 3 },
  dot: { width: 5, height: 5, borderRadius: 3, marginRight: 6 },
  ruleLabel: { color: colors.textSecondary, fontSize: 11, flex: 1 },
  ruleVal: { fontSize: 10, fontWeight: fonts.weights.bold },
});

export default function ProfileScreen({ navigation }) {
  const user = useAuthStore((s) => s.user);
  const identity = useIdentityStore((s) => s.identity);
  const currentDay = useIdentityStore((s) => s.currentDay);
  const logout = useAuthStore((s) => s.logout);
  const resetIdentity = useIdentityStore((s) => s.reset);
  const resetHabits = useHabitStore((s) => s.reset);
  const resetJourney = useIdentityStore((s) => s.resetJourney);
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const [showGuide, setShowGuide] = useState(false);
  const [showReset, setShowReset] = useState(false);
  const [resetReason, setResetReason] = useState('');
  const [resetting, setResetting] = useState(false);
  const [focusCount, setFocusCount] = useState(0);
  const [profile, setProfile] = useState(null);
  const [journeyCount, setJourneyCount] = useState(0);
  const [totalDaysLogged, setTotalDaysLogged] = useState(0);

  useFocusEffect(
    useCallback(() => {
      setFocusCount((c) => c + 1);
      Animated.timing(fadeAnim, { toValue: 1, duration: 500, useNativeDriver: true }).start();
      if (user?.id) {
        getProfile(user.id).then((p) => setProfile(p));
        // Load journey stats
        offline.getAll('identities', { user_id: user.id }).then((ids) => setJourneyCount(ids.length));
        offline.getAll('daily_logs').then((logs) => {
          offline.getAll('identities', { user_id: user.id }).then((ids) => {
            const idSet = new Set(ids.map((i) => i.id));
            setTotalDaysLogged(logs.filter((l) => idSet.has(l.identity_id) && (l.identity_check || l.ai_title)).length);
          });
        });
      }
    }, [user?.id])
  );

  const handleReset = () => {
    if (!resetReason.trim()) {
      showAlert('Tell us why', "We'd like to understand why. It helps us help you.");
      return;
    }
    showAlert('Are you sure?', "Everything you've built will be gone. This can't be undone.", [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Yes, Reset', style: 'destructive',
        onPress: async () => {
          setResetting(true);
          try {
            await resetJourney(resetReason.trim());
            setShowReset(false);
            setResetReason('');
            navigation.dispatch(CommonActions.reset({ index: 0, routes: [{ name: 'IdentityStory' }] }));
          } catch (e) {
            showAlert('Error', e?.message || 'Failed to reset.');
          } finally { setResetting(false); }
        },
      },
    ]);
  };

  const handleSignOut = () => {
    showAlert('Leaving already?', 'You can always come back.', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Sign Out', style: 'destructive',
        onPress: async () => {
          resetIdentity(); resetHabits(); await logout();
          navigation.dispatch(CommonActions.reset({ index: 0, routes: [{ name: 'Login' }] }));
        },
      },
    ]);
  };

  const phase = getDayPhase(currentDay);
  const progressPct = Math.round((currentDay / 40) * 100);
  const displayName = profile?.nickname || profile?.fullName || user?.email?.split('@')[0] || 'Nova';

  // Dynamic greeting
  const hour = new Date().getHours();
  const greeting = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening';

  // Phase motivational message
  const phaseMessages = {
    awakening: "You're planting the seeds of change.",
    building: "Momentum is building. Can you feel it?",
    testing: "This is where champions are made.",
    strengthening: "Your new identity is taking shape.",
    transcending: "You're becoming unstoppable.",
  };

  return (
    <ScreenWrapper>
      <Animated.ScrollView
        style={[st.flex, { opacity: fadeAnim }]}
        contentContainerStyle={st.scroll}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
      >
        {/* ═══ Profile Hero ═══ */}
        <FadeIn delay={0} trigger={focusCount}>
          <View style={st.heroSection}>
            <Pressable onPress={() => navigation.navigate('EditProfile')}>
              {profile?.photoUri ? (
                <Image source={{ uri: profile.photoUri }} style={st.avatarPhoto} />
              ) : (
                <View style={st.avatar}>
                  <Text style={st.avatarText}>
                    {displayName[0].toUpperCase()}
                  </Text>
                </View>
              )}
            </Pressable>

            <Text style={st.greeting}>{greeting},</Text>
            <Text style={st.displayName}>{displayName}</Text>

            <Pressable
              style={({ pressed }) => [st.editBtn, pressed && st.editBtnPressed]}
              onPress={() => navigation.navigate('EditProfile')}
            >
              <Text style={st.editBtnText}>Edit Profile</Text>
            </Pressable>
          </View>
        </FadeIn>

        {/* ═══ Journey Progress Card ═══ */}
        {identity && (
          <FadeIn delay={100} trigger={focusCount}>
            <View style={st.journeyCard}>
              <View style={st.journeyHeader}>
                <View>
                  <Text style={st.journeyLabel}>{phase.toUpperCase()} PHASE</Text>
                  <Text style={st.journeyTitle}>{identity.title}</Text>
                </View>
                <View style={st.journeyDayCircle}>
                  <Text style={st.journeyDayNum}>{currentDay}</Text>
                  <Text style={st.journeyDayLabel}>DAY</Text>
                </View>
              </View>

              {/* Progress bar */}
              <View style={st.progressRow}>
                <View style={st.progressBar}>
                  <View style={[st.progressFill, { width: `${progressPct}%` }]} />
                </View>
                <Text style={st.progressPct}>{progressPct}%</Text>
              </View>

              {/* Phase message */}
              <Text style={st.phaseMessage}>{phaseMessages[phase] || 'Keep going.'}</Text>

              {/* Journey meta */}
              <View style={st.journeyMeta}>
                <View style={st.journeyMetaItem}>
                  <Text style={st.journeyMetaValue}>{40 - currentDay}</Text>
                  <Text style={st.journeyMetaLabel}>days left</Text>
                </View>
                <View style={[st.journeyMetaItem, st.journeyMetaCenter]}>
                  <Text style={st.journeyMetaValue}>{formatDate(identity.start_date)}</Text>
                  <Text style={st.journeyMetaLabel}>started</Text>
                </View>
                <View style={st.journeyMetaItem}>
                  <Text style={st.journeyMetaValue}>{formatDate(identity.end_date)}</Text>
                  <Text style={st.journeyMetaLabel}>finish</Text>
                </View>
              </View>
            </View>
          </FadeIn>
        )}

        <NovaAd />

        {/* ═══ Scoring Guide ═══ */}
        <FadeIn delay={200} trigger={focusCount}>
          <Pressable
            style={({ pressed }) => [st.accordion, st.accordionGuide, pressed && st.accordionPressed]}
            onPress={() => setShowGuide((p) => !p)}
          >
            <Text style={st.accordionIcon}>📘</Text>
            <Text style={st.accordionText}>How your score works</Text>
            <Text style={[st.accordionArrow, { color: colors.primary }]}>{showGuide ? '▲' : '▼'}</Text>
          </Pressable>
        </FadeIn>

        {showGuide && (
          <View style={st.accordionBody}>
            <Section icon="🪞" title="Identity Check">
              <Rule label='Answer "Yes"' value="+3 pts" color={colors.success} />
              <Rule label='Answer "Almost"' value="+1 pt" color={colors.warning} />
              <Rule label='Answer "No"' value="+0 pts" color={colors.error} />
            </Section>
            <Section icon="📊" title="Score Categories">
              <Rule label="Discipline" value="Yes +3 / Almost +1" color={colors.primary} />
              <Rule label="Focus" value="Yes +3 / Almost +1" color={colors.accent} />
              <Rule label="Consistency" value="Yes +2 / Almost +1" color={colors.success} />
            </Section>
            <Section icon="🔥" title="Streak">
              <Text style={st.desc}>Consecutive "Yes" or "Almost" days. Resets on "No" or missed day.</Text>
            </Section>
            <Section icon="📖" title="History">
              <Text style={st.desc}>All completed days are saved in the History tab — even after you reset and start a new journey.</Text>
            </Section>
            <Section icon="🏆" title="Max Score">
              <Text style={st.desc}>8 pts/day × 40 days = 320 max score possible.</Text>
            </Section>
            <Section icon="⚡" title="Critical Days">
              <Text style={st.desc}>Day 3, 10, 21, 30 — turning points where most give up.</Text>
            </Section>
            <Section icon="🌙" title="Phases">
              <Rule label="1–7 Awakening" value="Foundation" color={colors.textSecondary} />
              <Rule label="8–14 Building" value="Momentum" color={colors.primary} />
              <Rule label="15–21 Testing" value="Challenge" color={colors.warning} />
              <Rule label="22–30 Strengthening" value="Solidifying" color={colors.accent} />
              <Rule label="31–40 Transcending" value="Nova" color={colors.success} />
            </Section>
          </View>
        )}

        {/* ═══ Legal ═══ */}
        <FadeIn delay={300} trigger={focusCount}>
          <View style={st.divider} />
          <View style={st.legalRow}>
            <Pressable style={({ pressed }) => [st.legalBtn, pressed && st.legalBtnPressed]} onPress={() => navigation.navigate('PrivacyPolicy')}>
              <Text style={st.legalIcon}>🔒</Text>
              <Text style={st.legalText}>Privacy Policy</Text>
              <Text style={st.legalArrow}>›</Text>
            </Pressable>
            <Pressable style={({ pressed }) => [st.legalBtn, pressed && st.legalBtnPressed]} onPress={() => navigation.navigate('Terms')}>
              <Text style={st.legalIcon}>📄</Text>
              <Text style={st.legalText}>Terms & Conditions</Text>
              <Text style={st.legalArrow}>›</Text>
            </Pressable>
          </View>
        </FadeIn>

        {/* ═══ Reset Journey ═══ */}
        {identity && (
          <FadeIn delay={350} trigger={focusCount}>
            <View style={st.divider} />
            <Pressable
              style={({ pressed }) => [st.accordion, st.accordionReset, pressed && st.accordionPressed]}
              onPress={() => setShowReset((p) => !p)}
            >
              <Text style={st.accordionIcon}>🔄</Text>
              <Text style={[st.accordionText, { color: colors.error }]}>Reset Current Journey</Text>
              <Text style={[st.accordionArrow, { color: colors.error }]}>{showReset ? '▲' : '▼'}</Text>
            </Pressable>

            {showReset && (
              <View style={st.resetBody}>
                <View style={st.resetWarningBox}>
                  <Text style={st.resetWarningIcon}>⚠️</Text>
                  <Text style={st.resetWarningText}>This will erase your current identity, habits, and stats. Your history will be kept.</Text>
                </View>
                <Text style={st.resetLabel}>Before you go — why the reset?</Text>
                <TextInput
                  style={st.resetInput}
                  value={resetReason}
                  onChangeText={setResetReason}
                  placeholder="I'm resetting because..."
                  placeholderTextColor={colors.textMuted}
                  multiline
                  selectionColor={colors.error}
                />
                <Button
                  title={resetting ? 'Resetting...' : 'Reset Journey'}
                  onPress={handleReset}
                  loading={resetting}
                  disabled={!resetReason.trim()}
                  variant="danger"
                />
              </View>
            )}
          </FadeIn>
        )}

        {/* ═══ Sign Out ═══ */}
        <FadeIn delay={400} trigger={focusCount}>
          <View style={st.divider} />
          <Button title="Sign Out" onPress={handleSignOut} variant="secondary" style={st.signOutBtn} />
        </FadeIn>

        {/* ═══ Footer ═══ */}
        <FadeIn delay={500} trigger={focusCount}>
          <Text style={st.version}>Nova40 v1.0.0</Text>
          <Text style={st.footerQuote}>Your identity is what you do repeatedly.</Text>
        </FadeIn>

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

const st = StyleSheet.create({
  flex: { flex: 1 },
  scroll: { paddingHorizontal: spacing.lg, paddingTop: spacing.xl, paddingBottom: spacing.xxl * 2 },

  // Hero
  heroSection: { alignItems: 'center', marginBottom: spacing.xl },
  avatar: {
    width: 90, height: 90, borderRadius: 45, backgroundColor: colors.primary,
    alignItems: 'center', justifyContent: 'center', marginBottom: spacing.md,
    shadowColor: colors.primary, shadowOffset: { width: 0, height: 0 }, shadowOpacity: 0.5, shadowRadius: 16, elevation: 8,
  },
  avatarPhoto: {
    width: 90, height: 90, borderRadius: 45, marginBottom: spacing.md,
    borderWidth: 3, borderColor: colors.primary,
  },
  avatarText: { color: colors.text, fontSize: fonts.sizes.xxl, fontWeight: fonts.weights.bold },
  greeting: { color: colors.accent, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.medium, letterSpacing: 1 },
  displayName: { color: colors.text, fontSize: fonts.sizes.xl, fontWeight: fonts.weights.bold, marginTop: 2 },
  editBtn: {
    marginTop: spacing.md, paddingVertical: spacing.sm, paddingHorizontal: spacing.xl,
    borderRadius: borderRadius.full, borderWidth: 1, borderColor: colors.primary,
  },
  editBtnPressed: { opacity: 0.6 },
  editBtnText: { color: colors.primary, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.semibold },

  // Journey card
  journeyCard: {
    backgroundColor: colors.surface, borderRadius: borderRadius.xl,
    padding: spacing.lg, marginBottom: spacing.lg,
    borderWidth: 1, borderColor: 'rgba(108,99,255,0.25)',
  },
  journeyHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: spacing.md },
  journeyLabel: { color: colors.accent, fontSize: 10, fontWeight: fonts.weights.bold, letterSpacing: 2, marginBottom: spacing.xs },
  journeyTitle: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.bold, maxWidth: 200 },
  journeyDayCircle: {
    width: 56, height: 56, borderRadius: 28,
    borderWidth: 2, borderColor: colors.accent,
    alignItems: 'center', justifyContent: 'center',
    backgroundColor: 'rgba(0,229,255,0.06)',
  },
  journeyDayNum: { color: colors.accent, fontSize: 22, fontWeight: fonts.weights.bold, lineHeight: 26 },
  journeyDayLabel: { color: colors.accent, fontSize: 8, fontWeight: fonts.weights.bold, letterSpacing: 1 },

  progressRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, marginBottom: spacing.sm },
  progressBar: { flex: 1, height: 5, backgroundColor: colors.surfaceLight, borderRadius: 3, overflow: 'hidden' },
  progressFill: { height: '100%', backgroundColor: colors.primary, borderRadius: 3 },
  progressPct: { color: colors.primary, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.bold, width: 36, textAlign: 'right' },

  phaseMessage: { color: colors.textSecondary, fontSize: fonts.sizes.sm, fontStyle: 'italic', marginBottom: spacing.md },

  journeyMeta: { flexDirection: 'row', borderTopWidth: 1, borderTopColor: colors.border, paddingTop: spacing.md },
  journeyMetaItem: { flex: 1, alignItems: 'center' },
  journeyMetaCenter: { borderLeftWidth: 1, borderRightWidth: 1, borderColor: colors.border },
  journeyMetaValue: { color: colors.text, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.semibold },
  journeyMetaLabel: { color: colors.textMuted, fontSize: 9, marginTop: 2 },

  // Lifetime stats
  lifetimeRow: { flexDirection: 'row', gap: spacing.sm, marginBottom: spacing.lg },
  lifetimeCard: {
    flex: 1, alignItems: 'center',
    backgroundColor: colors.surface, borderRadius: borderRadius.lg,
    paddingVertical: spacing.lg, borderWidth: 1, borderColor: colors.border,
  },
  lifetimeEmoji: { fontSize: 24, marginBottom: spacing.sm },
  lifetimeValue: { color: colors.text, fontSize: fonts.sizes.xxl, fontWeight: fonts.weights.bold },
  lifetimeLabel: { color: colors.textMuted, fontSize: 10, marginTop: 2 },

  // Accordion shared
  accordion: {
    flexDirection: 'row', alignItems: 'center',
    borderRadius: borderRadius.md, padding: spacing.md, marginBottom: 6,
  },
  accordionGuide: { backgroundColor: 'rgba(108,99,255,0.06)', borderWidth: 1, borderColor: 'rgba(108,99,255,0.15)' },
  accordionReset: { backgroundColor: 'rgba(255,82,82,0.05)', borderWidth: 1, borderColor: 'rgba(255,82,82,0.12)' },
  accordionPressed: { opacity: 0.7 },
  accordionIcon: { fontSize: 16, marginRight: spacing.sm },
  accordionText: { color: colors.text, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.semibold, flex: 1 },
  accordionArrow: { fontSize: 10 },
  accordionBody: { marginBottom: spacing.md },
  desc: { color: colors.textSecondary, fontSize: 11, lineHeight: 16 },

  divider: { height: 1, backgroundColor: colors.border, marginVertical: spacing.md },

  // Reset
  resetBody: {
    backgroundColor: colors.surface, borderRadius: borderRadius.md,
    padding: spacing.lg, marginBottom: spacing.sm,
    borderWidth: 1, borderColor: 'rgba(255,82,82,0.15)',
  },
  resetWarningBox: {
    flexDirection: 'row', alignItems: 'flex-start',
    backgroundColor: 'rgba(255,82,82,0.06)', borderRadius: borderRadius.sm,
    padding: spacing.sm, marginBottom: spacing.lg,
  },
  resetWarningIcon: { fontSize: 16, marginRight: spacing.sm, marginTop: 1 },
  resetWarningText: { color: colors.error, fontSize: 11, lineHeight: 17, flex: 1 },
  resetLabel: { color: colors.text, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.semibold, marginBottom: spacing.sm },
  resetInput: {
    backgroundColor: colors.background, borderRadius: borderRadius.md,
    paddingHorizontal: spacing.md, paddingVertical: spacing.md,
    color: colors.text, fontSize: fonts.sizes.sm,
    borderWidth: 1, borderColor: colors.border,
    minHeight: 90, textAlignVertical: 'top', marginBottom: spacing.lg,
  },

  // Legal
  legalRow: { gap: spacing.sm },
  legalBtn: {
    flexDirection: 'row', alignItems: 'center',
    backgroundColor: colors.surface, borderRadius: borderRadius.md,
    padding: spacing.md, borderWidth: 1, borderColor: colors.border,
  },
  legalBtnPressed: { opacity: 0.6 },
  legalIcon: { fontSize: 16, marginRight: spacing.md },
  legalText: { color: colors.text, fontSize: fonts.sizes.sm, fontWeight: fonts.weights.medium, flex: 1 },
  legalArrow: { color: colors.textMuted, fontSize: fonts.sizes.lg },

  signOutBtn: { borderColor: colors.error },

  // Footer
  version: { color: colors.textMuted, fontSize: 9, textAlign: 'center', marginTop: spacing.xl },
  footerQuote: { color: colors.textMuted, fontSize: 10, textAlign: 'center', fontStyle: 'italic', marginTop: spacing.sm },
});
