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 { colors, fonts, spacing, borderRadius } from '../utils/theme';
import { formatDate } 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);

  useFocusEffect(
    useCallback(() => {
      setFocusCount((c) => c + 1);
      Animated.timing(fadeAnim, { toValue: 1, duration: 500, useNativeDriver: true }).start();
      // Load profile
      if (user?.id) {
        getProfile(user.id).then((p) => setProfile(p));
      }
    }, [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' }] }));
        },
      },
    ]);
  };

  return (
    <ScreenWrapper>
      <Animated.ScrollView
        style={[st.flex, { opacity: fadeAnim }]}
        contentContainerStyle={st.scroll}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
      >
        {/* ═══ Profile Header ═══ */}
        <FadeIn delay={0} trigger={focusCount}><View style={st.profileHeader}>
          <Pressable onPress={() => navigation.navigate('EditProfile')}>
            {profile?.photoUri ? (
              <Image source={{ uri: profile.photoUri }} style={st.avatarPhoto} />
            ) : (
              <View style={st.avatar}>
                <Text style={st.avatarText}>
                  {(profile?.nickname?.[0] || profile?.fullName?.[0] || user?.email?.[0] || 'N').toUpperCase()}
                </Text>
              </View>
            )}
          </Pressable>
          {profile?.nickname || profile?.fullName ? (
            <>
              <Text style={st.displayName}>{profile.nickname || profile.fullName}</Text>
              {profile?.fullName && profile?.nickname ? (
                <Text style={st.fullName}>{profile.fullName}</Text>
              ) : null}
              <Text style={st.email} numberOfLines={1}>{user?.email}</Text>
            </>
          ) : (
            <Text style={st.email} numberOfLines={1} adjustsFontSizeToFit>{user?.email}</Text>
          )}
          <Pressable
            style={({ pressed }) => [st.editBtn, pressed && st.editBtnPressed]}
            onPress={() => navigation.navigate('EditProfile')}
          >
            <Text style={st.editBtnText}>Edit Profile</Text>
          </Pressable>
        </View></FadeIn>

        {/* ═══ Active Identity ═══ */}
        {identity && (
          <FadeIn delay={100} trigger={focusCount}><View style={st.identityCard}>
            <Text style={st.identityLabel}>Your identity</Text>
            <Text style={st.identityTitle}>{identity.title}</Text>
            <View style={st.identitySep} />
            <View style={st.identityRow}>
              <Text style={st.identityMeta}>Day {currentDay}/40</Text>
              <Text style={st.identityMeta}>Started {formatDate(identity.start_date)}</Text>
            </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="40-Day Map Colors">
              <Rule label="Green" value="Yes" color={colors.success} />
              <Rule label="Yellow" value="Almost" color={colors.warning} />
              <Rule label="Red" value="No" color={colors.error} />
              <Rule label="Cyan border" value="Today" color={colors.accent} />
            </Section>
            <Section icon="🎮" title="Game Bonus">
              <Rule label="Reflex Tap" value="Disc ×1.0" color={colors.primary} />
              <Rule label="Focus Hold" value="Focus ×1.0" color={colors.accent} />
              <Rule label="Temptation" value="Cons ×1.0" color={colors.success} />
              <Rule label="Timing Tap" value="Focus ×0.8" color={colors.warning} />
            </Section>
            <Section icon="🏆" title="Max Score">
              <Text style={st.desc}>8 pts/day × 40 days = 320 max (before game bonus)</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 everything — your identity, habits, journal entries, stats, and game scores. There's no going back.</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>
        </FadeIn>

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

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

  // Profile header
  profileHeader: { alignItems: 'center', marginBottom: spacing.lg },
  avatar: {
    width: 80, height: 80, borderRadius: 40, backgroundColor: colors.primary,
    alignItems: 'center', justifyContent: 'center', marginBottom: spacing.sm,
    shadowColor: colors.primary, shadowOffset: { width: 0, height: 0 }, shadowOpacity: 0.4, shadowRadius: 12, elevation: 6,
  },
  avatarPhoto: {
    width: 80, height: 80, borderRadius: 40, marginBottom: spacing.sm,
    borderWidth: 3, borderColor: colors.primary,
  },
  avatarText: { color: colors.text, fontSize: fonts.sizes.xxl, fontWeight: fonts.weights.bold },
  displayName: { color: colors.text, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.bold, marginBottom: 2 },
  fullName: { color: colors.textSecondary, fontSize: fonts.sizes.sm, marginBottom: 2 },
  email: { color: colors.textMuted, fontSize: fonts.sizes.xs },
  editBtn: {
    marginTop: spacing.sm,
    paddingVertical: spacing.xs + 2,
    paddingHorizontal: spacing.lg,
    borderRadius: borderRadius.full,
    borderWidth: 1,
    borderColor: colors.primary,
  },
  editBtnPressed: { opacity: 0.6 },
  editBtnText: { color: colors.primary, fontSize: fonts.sizes.xs, fontWeight: fonts.weights.semibold },

  // Identity card
  identityCard: {
    backgroundColor: colors.surface, borderRadius: borderRadius.md,
    padding: spacing.md, marginBottom: spacing.lg,
    borderWidth: 1, borderColor: 'rgba(108,99,255,0.2)',
  },
  identityLabel: { color: colors.primary, fontSize: 9, fontWeight: fonts.weights.bold, letterSpacing: 2, marginBottom: 6 },
  identityTitle: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.semibold },
  identitySep: { height: 1, backgroundColor: colors.border, marginVertical: spacing.sm },
  identityRow: { flexDirection: 'row', justifyContent: 'space-between' },
  identityMeta: { color: colors.textMuted, fontSize: 11 },

  // 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 },

  // Accordion body
  accordionBody: { marginBottom: spacing.md },
  desc: { color: colors.textSecondary, fontSize: 11, lineHeight: 16 },

  // Divider
  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,
  },
  // Sign out
  // 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 },
});
