import React, { useRef, useEffect } from 'react';
import { View, Text, StyleSheet, Animated } from 'react-native';
import { CommonActions } from '@react-navigation/native';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Button from '../components/Button';
import useAuthStore from '../store/useAuthStore';
import useIdentityStore from '../store/useIdentityStore';
import useHabitStore from '../store/useHabitStore';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';
import { formatDate } from '../utils/helpers';

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 fadeAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(fadeAnim, { toValue: 1, duration: 500, useNativeDriver: true }).start();
  }, []);

  const handleSignOut = () => {
    showAlert('Sign Out', 'Are you sure you want to sign out?', [
      { 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.View style={[styles.container, { opacity: fadeAnim }]}>
        <View style={styles.avatar}>
          <Text style={styles.avatarText}>{user?.email?.[0]?.toUpperCase() || 'N'}</Text>
        </View>
        <Text style={styles.email} numberOfLines={1} adjustsFontSizeToFit>{user?.email}</Text>

        {identity && (
          <View style={styles.card}>
            <Text style={styles.cardLabel}>ACTIVE IDENTITY</Text>
            <Text style={styles.cardTitle}>{identity.title}</Text>
            <Text style={styles.cardMeta}>Day {currentDay}/40 • Started {formatDate(identity.start_date)}</Text>
          </View>
        )}

        <View style={styles.actions}>
          <Button title="View Mirror" onPress={() => navigation.navigate('Mirror')} variant="secondary" style={styles.actionBtn} />
          <Button title="Play Focus Game" onPress={() => navigation.navigate('MiniGame')} variant="secondary" style={styles.actionBtn} />
          <Button title="Sign Out" onPress={handleSignOut} variant="secondary" style={[styles.actionBtn, styles.signOutBtn]} />
        </View>
      </Animated.View>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.xxl,
  },
  avatar: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    alignSelf: 'center',
    marginBottom: spacing.md,
    shadowColor: colors.primary,
    shadowOffset: { width: 0, height: 0 },
    shadowOpacity: 0.5,
    shadowRadius: 15,
    elevation: 8,
  },
  avatarText: {
    color: colors.text,
    fontSize: fonts.sizes.xxl,
    fontWeight: fonts.weights.bold,
  },
  email: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    marginBottom: spacing.xl,
    textAlign: 'center',
  },
  card: {
    backgroundColor: colors.surface,
    borderRadius: borderRadius.md,
    padding: spacing.lg,
    borderWidth: 1,
    borderColor: colors.border,
    marginBottom: spacing.xl,
  },
  cardLabel: {
    color: colors.primary,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.bold,
    letterSpacing: 2,
    marginBottom: spacing.sm,
  },
  cardTitle: {
    color: colors.text,
    fontSize: fonts.sizes.lg,
    fontWeight: fonts.weights.semibold,
    marginBottom: spacing.xs,
  },
  cardMeta: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
  },
  actions: {},
  actionBtn: {
    marginBottom: spacing.sm,
  },
  signOutBtn: {
    borderColor: colors.error,
    marginTop: spacing.md,
  },
});
