import React, { useRef, useEffect, useState } from 'react';
import { View, Text, ScrollView, StyleSheet, TouchableOpacity, Animated } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { useAuth } from '../../hooks/useAuth';
import { useResponsive } from '../../hooks/useResponsive';
import { useToast } from '../../context/ToastContext';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
import { colors, spacing, radii, shadows } from '../../theme';

export default function ProfileScreen() {
  const navigation = useNavigation<any>();
  const insets = useSafeAreaInsets();
  const { user, isAdmin, logout } = useAuth();
  const { toast } = useToast();
  const { contentPadding, fontSize } = useResponsive();
  const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);
  const [loggingOut, setLoggingOut] = useState(false);
  const initials = `${user?.first_name?.[0] || ''}${user?.last_name?.[0] || ''}`.toUpperCase();
  const headerFade = useRef(new Animated.Value(0)).current;

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

  const handleLogout = async () => {
    setLoggingOut(true);
    setShowLogoutConfirm(false);
    try {
      await logout();
    } catch {
      // silent
    }
    toast('Signed out', 'success');
  };

  const menuItems = [
    { icon: 'person-outline', label: 'My Profile', onPress: () => {} },
    { icon: 'notifications-outline', label: 'Notifications', onPress: () => {} },
    { icon: 'help-circle-outline', label: 'Help & Support', onPress: () => {} },
    { icon: 'information-circle-outline', label: 'About', onPress: () => {} },
  ];

  const adminMenuItems = isAdmin ? [
    { icon: 'people-outline', label: 'Manage Users', onPress: () => navigation.navigate('Admin', { screen: 'UserList' }) },
    { icon: 'shield-checkmark-outline', label: 'Roles & Permissions', onPress: () => navigation.navigate('Admin', { screen: 'RoleList' }) },
    { icon: 'location-outline', label: 'Manage Geofences', onPress: () => navigation.navigate('Admin', { screen: 'GeofenceList' }) },
    { icon: 'bar-chart-outline', label: 'Reports', onPress: () => navigation.navigate('Admin', { screen: 'Report' }) },
  ] : [];

  return (
    <ScrollView
      style={styles.container}
      contentContainerStyle={{ paddingBottom: 100 }}
      showsVerticalScrollIndicator={false}
    >
      <Animated.View style={[styles.header, { paddingTop: insets.top + spacing.xl, paddingHorizontal: contentPadding, opacity: headerFade }]}>
        <View style={styles.avatarLarge}>
          <Text style={styles.avatarText}>{initials}</Text>
        </View>
        <Text style={[styles.name, { fontSize: fontSize.h2 }]}>{user?.first_name} {user?.last_name}</Text>
        <Text style={[styles.email, { fontSize: fontSize.body }]}>{user?.email}</Text>
        <View style={styles.roleBadge}>
          <Ionicons name={isAdmin ? 'shield-checkmark' : 'person'} size={12} color={colors.primary[600]} />
          <Text style={[styles.roleText, { fontSize: fontSize.caption }]}>
            {user?.role_names?.[0]?.replace(/_/g, ' ') || 'User'}
          </Text>
        </View>
      </Animated.View>

      <AnimatedCard delay={100} style={{ marginHorizontal: contentPadding, marginBottom: spacing.sm }}>
        {menuItems.map((item, i) => (
          <TouchableOpacity
            key={item.label}
            style={[styles.menuItem, i < menuItems.length - 1 && styles.menuBorder]}
            onPress={item.onPress}
            activeOpacity={0.6}
          >
            <Ionicons name={item.icon as any} size={20} color={colors.gray[600]} />
            <Text style={[styles.menuLabel, { fontSize: fontSize.body }]}>{item.label}</Text>
            <Ionicons name="chevron-forward" size={16} color={colors.gray[300]} />
          </TouchableOpacity>
        ))}
      </AnimatedCard>

      {adminMenuItems.length > 0 && (
        <>
          <Text style={[styles.sectionLabel, { fontSize: fontSize.caption, paddingHorizontal: contentPadding }]}>Admin</Text>
          <AnimatedCard delay={200} style={{ marginHorizontal: contentPadding }}>
            {adminMenuItems.map((item, i) => (
              <TouchableOpacity
                key={item.label}
                style={[styles.menuItem, i < adminMenuItems.length - 1 && styles.menuBorder]}
                onPress={item.onPress}
                activeOpacity={0.6}
              >
                <Ionicons name={item.icon as any} size={20} color={colors.primary[600]} />
                <Text style={[styles.menuLabel, { fontSize: fontSize.body }]}>{item.label}</Text>
                <Ionicons name="chevron-forward" size={16} color={colors.gray[300]} />
              </TouchableOpacity>
            ))}
          </AnimatedCard>
        </>
      )}

      <TouchableOpacity
        style={[styles.logoutButton, { marginHorizontal: contentPadding }]}
        onPress={() => setShowLogoutConfirm(true)}
        activeOpacity={0.7}
      >
        <Ionicons name="log-out-outline" size={20} color={colors.danger[600]} />
        <Text style={[styles.logoutText, { fontSize: fontSize.body }]}>Sign Out</Text>
      </TouchableOpacity>

      <ConfirmDialog
        visible={showLogoutConfirm}
        title="Sign Out"
        message="Are you sure you want to sign out?"
        confirmLabel="Sign Out"
        cancelLabel="Cancel"
        variant="danger"
        onConfirm={handleLogout}
        onCancel={() => setShowLogoutConfirm(false)}
      />
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: colors.background },
  header: {
    alignItems: 'center',
    paddingBottom: spacing.xl,
    backgroundColor: colors.white,
    borderBottomLeftRadius: radii.xl,
    borderBottomRightRadius: radii.xl,
    ...shadows.sm,
  },
  avatarLarge: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: colors.primary[600],
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: spacing.lg,
  },
  avatarText: { color: colors.white, fontSize: 28, fontWeight: '700' },
  name: { fontWeight: '700', color: colors.gray[900], marginBottom: 4 },
  email: { color: colors.gray[500], marginBottom: spacing.md },
  roleBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
    backgroundColor: colors.primary[50],
    paddingHorizontal: 12,
    paddingVertical: 5,
    borderRadius: radii.full,
  },
  roleText: { fontWeight: '600', color: colors.primary[600], textTransform: 'capitalize' },
  sectionLabel: {
    fontWeight: '600',
    color: colors.gray[400],
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    marginTop: spacing.lg,
    marginBottom: spacing.sm,
  },
  menuItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 14,
    gap: spacing.md,
  },
  menuBorder: { borderBottomWidth: 1, borderBottomColor: colors.gray[100] },
  menuLabel: { flex: 1, fontWeight: '500', color: colors.gray[800] },
  logoutButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: spacing.sm,
    marginTop: spacing.xl,
    paddingVertical: 14,
    backgroundColor: colors.danger[50],
    borderRadius: radii.lg,
    borderWidth: 1,
    borderColor: colors.danger[100],
  },
  logoutText: { fontWeight: '600', color: colors.danger[600] },
});
