import React from 'react';
import { View, ScrollView, Pressable } from 'react-native';
import { useRouter } from 'expo-router';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { MyText, tw } from 'common-ui';
import { LinearGradient } from 'expo-linear-gradient';
import { theme } from 'common-ui/src/theme';
import { trpc } from '@/src/trpc-client';
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget';

interface MenuItem {
  title: string;
  icon: string;
  description?: string;
  route: string;
  category: 'quick' | 'products' | 'orders' | 'marketing' | 'settings' | 'users';
  iconColor?: string;
  iconBg?: string;
  badgeCount?: number;
  onPress?: () => void;
  testID?: string;
}

interface MenuItemComponentProps {
  item: MenuItem;
  router: any;
}

const MenuItemComponent: React.FC<MenuItemComponentProps> = ({ item, router }) => {
  
  return (
  <Pressable
    onPress={() => item.onPress ? item.onPress() : router.push(item.route as any)}
    style={({ pressed }) => [
      tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`,
      pressed && tw`bg-gray-50`,
    ]}
  >
    <View style={[tw`w-12 h-12 rounded-xl items-center justify-center mr-4`, { backgroundColor: item.iconBg }]}>
      <MaterialIcons name={item.icon as any} size={24} color={item.iconColor} />
    </View>
    <View style={tw`flex-1`}>
      <MyText style={tw`text-gray-900 font-bold text-base mb-0.5`}>{item.title}</MyText>
      {item.description && (
        <MyText style={tw`text-gray-500 text-xs`}>{item.description}</MyText>
      )}
    </View>
    {item.badgeCount ? (
      <View style={tw`bg-red-500 px-2 py-1 rounded-full`}>
        <MyText style={tw`text-white text-xs font-bold`}>{item.badgeCount}</MyText>
      </View>
    ) : null}
    <MaterialIcons name="chevron-right" size={24} color="#D1D5DB" style={tw`ml-2`} />
  </Pressable>
)
}

export default function Dashboard() {
  const router = useRouter();
  const { setNavigationTarget } = useNavigationTarget();

  const { data: essentialsData } = trpc.admin.user.getEssentials.useQuery();

  
  const handleManageOrdersPress = () => {
    setNavigationTarget('/manage-orders/orders');
    router.push('/(drawer)/manage-orders');
  };

  const handleDeliverySequencesPress = () => {
    setNavigationTarget('/manage-orders/delivery-sequences');
    router.push('/(drawer)/manage-orders');
  };

  const menuItems: MenuItem[] = [
    {
      title: 'Manage Orderss',
      icon: 'shopping-bag',
      description: 'View and manage customer orders',
      route: '/(drawer)/manage-orders',
      category: 'orders',
      iconColor: '#10B981',
      iconBg: '#D1FAE5',
      onPress: handleManageOrdersPress,
    },
    {
      title: 'Delivery Sequences',
      icon: 'alt-route',
      description: 'Plan and optimize delivery routes',
      route: '/manage-orders/delivery-sequences',
      category: 'orders',
      iconColor: '#8B5CF6',
      iconBg: '#EDE9FE',
      onPress: handleDeliverySequencesPress,
    },
    {
      title: 'Delivery Slots',
      icon: 'schedule',
      description: 'Configure delivery times',
      route: '/(drawer)/slots' as any,
      category: 'quick',
      iconColor: '#06B6D4',
      iconBg: '#CFFAFE',
      testID: 'delivery-slots-menu-item',
    },
    {
      title: 'Add Product',
      icon: 'add-circle',
      description: 'Create a new product listing',
      route: '/products/add',
      category: 'quick',
      iconColor: theme.colors.brand500,
      iconBg: theme.colors.brand50,
    },
    {
      title: 'Complaints',
      icon: 'report-problem',
      description: 'Handle customer complaints',
      route: '/(drawer)/complaints',
      category: 'quick',
      iconColor: '#F59E0B',
      iconBg: '#FEF3C7',
      badgeCount: essentialsData?.unresolvedComplaints,
    },
     {
       title: 'Products',
       icon: 'inventory-2',
       description: 'Manage product catalog',
       route: '/(drawer)/products',
       category: 'products',
       iconColor: '#6366F1',
       iconBg: '#E0E7FF',
     },
     {
       title: 'Prices Overview',
       icon: 'attach-money',
       description: 'Update product pricing',
       route: '/(drawer)/prices-overview',
       category: 'products',
       iconColor: '#059669',
       iconBg: '#ECFDF5',
     },
     {
       title: 'Product Tags',
       icon: 'label',
       description: 'Organize with tags',
       route: '/(drawer)/product-tags',
       category: 'products',
       iconColor: '#EC4899',
       iconBg: '#FCE7F3',
     },
    {
      title: 'Product Groupings',
      icon: 'category',
      description: 'Group products together',
      route: '/(drawer)/product-groupings',
      category: 'products',
      iconColor: '#8B5CF6',
      iconBg: '#F3E8FF',
    },
    {
      title: 'Stores',
      icon: 'store',
      description: 'Manage store locations',
      route: '/(drawer)/stores',
      category: 'settings',
      iconColor: '#14B8A6',
      iconBg: '#CCFBF1',
    },
    {
      title: 'Coupons',
      icon: 'local-offer',
      description: 'Create discount coupons',
      route: '/(drawer)/coupons',
      category: 'marketing',
      iconColor: '#F97316',
      iconBg: '#FFEDD5',
    },
      {
        title: 'App Constants',
        icon: 'settings-applications',
        description: 'Customize app settings',
        route: '/(drawer)/customize-app',
        category: 'settings',
        iconColor: '#7C3AED',
        iconBg: '#F3E8FF',
      },
      {
        title: 'User Management',
        icon: 'people',
        description: 'View and manage all users',
        route: '/(drawer)/user-management',
        category: 'users',
        iconColor: '#0EA5E9',
        iconBg: '#E0F2FE',
      },
      {
        title: 'Send Notifications',
        icon: 'campaign',
        description: 'Send push notifications to users',
        route: '/(drawer)/send-notifications',
        category: 'users',
        iconColor: '#8B5CF6',
        iconBg: '#F3E8FF',
      },
    ];

  const quickActions = menuItems.filter(item => item.category === 'quick');

  const categories = [
    { key: 'orders', title: 'Orders', icon: 'receipt-long' },
    { key: 'products', title: 'Products & Inventory', icon: 'inventory' },
    { key: 'marketing', title: 'Marketing & Promotions', icon: 'campaign' },
    { key: 'users', title: 'User Management', icon: 'people' },
    { key: 'settings', title: 'Settings & Configuration', icon: 'settings' },
  ];



  return (
    <View style={tw`flex-1 bg-gray-50`}>
      <ScrollView showsVerticalScrollIndicator={false}>
        {/* Header with Gradient */}
        {/* <LinearGradient
          colors={[theme.colors.brand500, theme.colors.brand700]}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
          style={tw`px-6 pt-8 pb-6`}
        >
          <MyText style={tw`text-white text-2xl font-bold mb-1`}>Dashboard</MyText>
          <MyText style={tw`text-brand-100 text-sm`}>Manage your business operations</MyText>
        </LinearGradient> */}

        {/* Quick Actions */}
        <View style={tw`px-6 mt-2 mb-4`}>
          <MyText style={tw`text-gray-900 text-lg font-bold mb-4`}>Quick Actions</MyText>
          <View style={tw`flex-row flex-wrap gap-3`}>
            {quickActions.map((item) => (
              <Pressable
                key={`quick-${item.route}`}
                testID={item.testID}
                accessibilityLabel={item.testID}
                onPress={() => item.onPress ? item.onPress() : router.push(item.route as any)}
                style={({ pressed }) => [
                  tw`bg-white rounded-xl p-3 shadow-sm border border-gray-100 items-center`,
                  { width: 'calc(25% - 9px)' },
                  pressed && tw`bg-gray-50`,
                ]}
              >
                <View style={[tw`w-10 h-10 rounded-lg items-center justify-center mb-2`, { backgroundColor: item.iconBg }]}>
                  <MaterialIcons name={item.icon as any} size={20} color={item.iconColor} />
                  {item.badgeCount ? (
                    <View style={tw`absolute -top-1 -right-1 bg-red-500 min-w-5 h-5 rounded-full items-center justify-center px-1`}>
                      <MyText style={tw`text-white text-[10px] font-bold`}>{item.badgeCount}</MyText>
                    </View>
                  ) : null}
                </View>
                <MyText style={tw`text-gray-900 font-bold text-xs text-center`} numberOfLines={2}>
                  {item.title}
                </MyText>
              </Pressable>
            ))}
          </View>
        </View>

        {/* Categorized Menu Items */}
        <View style={tw`px-6 pb-6`}>
          {categories.map((category) => {
            const categoryItems = menuItems.filter(item => item.category === category.key);
            if (categoryItems.length === 0) return null;

            return (
              <View key={category.key} style={tw`mb-6`}>
                <View style={tw`flex-row items-center mb-3`}>
                  <View style={tw`w-8 h-8 rounded-lg bg-gray-100 items-center justify-center mr-3`}>
                    <MaterialIcons name={category.icon as any} size={18} color={theme.colors.gray600} />
                  </View>
                  <MyText style={tw`text-gray-700 font-bold text-base`}>{category.title}</MyText>
                </View>
                {categoryItems.map(item => <MenuItemComponent key={`menu-${item.route}`} item={item} router={router} />)}
              </View>
            );
          })}
        </View>
      </ScrollView>
    </View>
  );
}
