import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity, ScrollView } from 'react-native';
import { DrawerContentComponentProps } from '@react-navigation/drawer';
import { Ionicons } from '@expo/vector-icons';
import { Colors } from '@/constants/theme';
import { useAuthStore } from '@/store/authStore';
import api from '@/services/api';
import { useRouter } from 'expo-router';
import NotificationBadge from './NotificationBadge';

export default function CustomDrawerContent(props: DrawerContentComponentProps) {
  const router = useRouter();
  const { user_id, user_type, logout } = useAuthStore();
  const [profile, setProfile] = useState<any>(null);

  useEffect(() => {
    if (user_id) fetchProfile();
  }, [user_id]);

  const fetchProfile = async () => {
    try {
      const response = await api.post(`/get-profile-details?is_mobile=yes`, { provider_id: user_id });
      setProfile(response.data.data);
    } catch (error) {
      console.error('Error fetching profile for drawer:', error);
    }
  };

  const handleLogout = async () => {
    await logout();
    router.replace('/login');
  };

  const isStaff = user_type === 4;

  const menuItems = isStaff ? [
    { label: 'Dashboard',       icon: 'grid-outline',              route: '/(drawer)/(tabs)' },
    { label: 'Meus Serviços',    icon: 'calendar-outline',          route: '/(drawer)/(tabs)/bookings' },
    { label: 'Chat',            icon: 'chatbubble-ellipses-outline', route: '/(drawer)/(tabs)/chat' },
  ] : [
    { label: 'Painel',        icon: 'grid-outline',              route: '/(drawer)/(tabs)' },
    { label: 'Serviços',      icon: 'calendar-outline',          route: '/(drawer)/(tabs)/bookings' },
    { label: 'Chat',          icon: 'chatbubble-ellipses-outline', route: '/(drawer)/(tabs)/chat' },
    { label: 'Carteira',      icon: 'wallet-outline',            route: '/(drawer)/(tabs)/wallet' },
    { label: 'Transações',    icon: 'swap-horizontal-outline',   route: '/(drawer)/transactions' },
    { label: 'Notificações',  icon: 'notifications-outline',     route: '/notifications' },
    { label: 'Tickets',       icon: 'ticket-outline',            route: '/tickets' },
  ];

  const settingsItems = [
    { label: 'Perfil',    icon: 'person-outline',      route: '/(drawer)/(tabs)/profile-settings' },
    { label: 'Segurança', icon: 'lock-closed-outline', route: '/security' },
  ];

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <View style={styles.profileInfo}>
          <Image 
            source={profile?.userDetails?.profile_image ? { uri: profile.userDetails.profile_image } : require('@/assets/images/logo_real.png')} 
            style={styles.avatar} 
          />
          <View style={styles.nameContainer}>
            <Text style={styles.name} numberOfLines={1}>
              {profile?.userDetails?.first_name || 'Cliente'} {profile?.userDetails?.last_name || ''}
            </Text>
            <Text style={styles.memberSince}>
              Membro desde {profile?.created_at ? new Date(profile.created_at).toLocaleDateString() : '...'}
            </Text>
          </View>
        </View>
      </View>

      <ScrollView style={styles.menuContainer}>
        <Text style={styles.sectionTitle}>Principal</Text>
        {menuItems.map((item, index) => (
          <TouchableOpacity 
            key={index} 
            style={styles.menuItem}
            onPress={() => router.navigate(item.route as any)}
          >
            <Ionicons name={item.icon as any} size={22} color={Colors.light.primary} style={styles.menuIcon} />
            <Text style={styles.menuLabel}>{item.label}</Text>
            {item.label === 'Notificações' && (
              <NotificationBadge size={16} style={{ position: 'relative', top: 0, right: 10, borderWidth: 0 }} />
            )}
            <Ionicons name="chevron-forward" size={16} color="#ccc" />
          </TouchableOpacity>
        ))}

        <Text style={styles.sectionTitle}>Configurações</Text>
        {settingsItems.map((item, index) => (
          <TouchableOpacity 
            key={index} 
            style={styles.menuItem}
            onPress={() => router.navigate(item.route as any)}
          >
            <Ionicons name={item.icon as any} size={22} color={Colors.light.primary} style={styles.menuIcon} />
            <Text style={styles.menuLabel}>{item.label}</Text>
            <Ionicons name="chevron-forward" size={16} color="#ccc" />
          </TouchableOpacity>
        ))}
      </ScrollView>

      <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
        <Ionicons name="log-out-outline" size={22} color={Colors.light.error} style={styles.menuIcon} />
        <Text style={[styles.menuLabel, { color: Colors.light.error }]}>Sair</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff' },
  header: { 
    paddingTop: 60, 
    paddingBottom: 30, 
    paddingHorizontal: 20, 
    backgroundColor: Colors.light.primary,
    borderBottomRightRadius: 30
  },
  profileInfo: { flexDirection: 'row', alignItems: 'center' },
  avatar: { width: 60, height: 60, borderRadius: 30, backgroundColor: '#fff', borderWidth: 2, borderColor: '#fff' },
  nameContainer: { marginLeft: 15, flex: 1 },
  name: { fontSize: 18, fontWeight: 'bold', color: '#fff' },
  memberSince: { fontSize: 12, color: 'rgba(255,255,255,0.7)', marginTop: 4 },
  menuContainer: { flex: 1, paddingVertical: 20 },
  sectionTitle: { 
    fontSize: 12, 
    fontWeight: 'bold', 
    color: '#999', 
    textTransform: 'uppercase', 
    marginHorizontal: 20, 
    marginTop: 15, 
    marginBottom: 10 
  },
  menuItem: { 
    flexDirection: 'row', 
    alignItems: 'center', 
    paddingVertical: 12, 
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0'
  },
  menuIcon: { width: 30 },
  menuLabel: { flex: 1, fontSize: 16, color: '#333' },
  logoutButton: { 
    flexDirection: 'row', 
    alignItems: 'center', 
    paddingVertical: 20, 
    paddingHorizontal: 20,
    borderTopWidth: 1,
    borderTopColor: '#f0f0f0'
  }
});
