import AdsLogo from '@/assets/images/one_click.png';
import { useTheme } from '@/components/ThemeContext';
import { useGlobalRefresh } from '@/components/ui/RefreshContext';
import { useQuery } from '@tanstack/react-query';
import { Image } from 'expo-image';
import { useRouter } from 'expo-router';
import {
  Award,
  Bell,
  BookAIcon,
  ChevronRight,
  HandCoins,
  LucideIcon,
  Megaphone,
  Package,
  Settings,
  Trash2,
  User,
  Users
} from 'lucide-react-native';
import { useTranslation } from 'react-i18next';
import { Alert, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { RefreshControl } from 'react-native-gesture-handler';
import { user_api } from '../lib/api';

interface SectionType {
  title: string;
  items: {
    icon: LucideIcon;
    label: string;
    route?: string;
    badge?: number;
    image?: any;
    isDestructive?: boolean;
  }[];
}

import { useAuth } from '@/components/AuthProvider';

export default function Profile() {
  const router = useRouter();
  const { logout } = useAuth();
  const { onRefresh, refreshing } = useGlobalRefresh();
  const { isDark } = useTheme();
  const { t } = useTranslation();

  const { data } = useQuery({
    queryKey: ['notification-list'],
    queryFn: () => user_api.notification_list({ page: 1, page_size: 1 }),
  });
  const unreadCount = data?.data?.data.unread_count ?? 0;

  const { data: me } = useQuery({
    queryKey: ['get_me'],
    queryFn: () => user_api.getMe(),
  });

  const sections: SectionType[] = [
    {
      title: 'Shaxsiy',
      items: [
        { icon: User, label: "Shaxsiy ma'lumotlar", route: '/profile/personal-info' },
        { icon: Users, label: 'Xodimlar', route: '/profile/employees' },
        {
          icon: Bell,
          label: 'Bildirishnomalar',
          route: '/profile/notification',
          badge: unreadCount,
        },
      ],
    },
    {
      title: 'Faoliyat',
      items: [
        { icon: Megaphone, label: "E'lonlar", image: AdsLogo, route: '/profile/my-ads' },
        { icon: Award, label: 'Bonuslar', route: '/profile/bonuses' },
        { icon: Package, label: 'Xizmatlar', route: '/profile/products' },
        ...(me?.data.data.can_create_referral
          ? [
            {
              icon: HandCoins,
              label: 'Refferallarim',
              route: '/profile/my-referrals',
            },
          ]
          : []),
      ],
    },
    {
      title: 'Sozlamalar',
      items: [
        { icon: Settings, label: 'Sozlamalar', route: '/profile/settings' },
        { icon: BookAIcon, label: "Foydalanish qo'llanmasi", route: '/profile/manual' },
        {
          icon: Trash2,
          label: "Hisobni o'chirish",
        },
      ],
    },
  ];

  return (
    <ScrollView
      style={[styles.content, isDark ? styles.darkBg : styles.lightBg]}
      contentContainerStyle={{ paddingBottom: 90 }}
      refreshControl={
        <RefreshControl
          refreshing={refreshing}
          onRefresh={onRefresh}
          colors={['#3b82f6']}
          tintColor="#3b82f6"
        />
      }
    >
      {sections.map((section, index) => (
        <View key={index} style={styles.section}>
          <Text style={[styles.sectionTitle, isDark ? styles.darkSubText : styles.lightSubText]}>
            {t(section.title)}
          </Text>

          <View style={styles.sectionContent}>
            {section.items.map((item, idx) => (
              <TouchableOpacity
                key={idx}
                style={[styles.card, isDark ? styles.darkCard : styles.lightCard]}
                onPress={() => {
                  if (item.label === "Hisobni o'chirish") {
                    Alert.alert(
                      t("Hisobni o'chirish"),
                      t("Rostdan ham hisobingizni o'chirmoqchimisiz?"),
                      [
                        { text: t('Bekor qilish'), style: 'cancel' },
                        { text: t("O'chirish"), onPress: () => logout(), style: 'destructive' },
                      ]
                    );
                  } else {
                    router.push(item.route as any);
                  }
                }}
                activeOpacity={0.7}
              >
                <View style={[styles.iconContainer, isDark ? styles.darkIconBg : styles.lightIconBg]}>
                  <item.icon
                    size={24}
                    color={item.label === "Hisobni o'chirish" ? '#ef4444' : '#3b82f6'}
                  />
                  {item?.badge && (
                    <View style={styles.badge}>
                      <Text style={styles.badgeText}>{item.badge}</Text>
                    </View>
                  )}
                </View>

                <View style={{ flex: 1 }}>
                  {item.image ? (
                    <View style={{ flex: 1 }}>
                      <Image
                        source={item.image}
                        style={{ width: '60%', height: 40 }}
                        contentFit="contain"
                      />
                      <Text
                        style={[
                          styles.cardLabel,
                          isDark ? styles.darkText : styles.lightText,
                          { fontSize: 14, marginTop: 4, fontWeight: '500' },
                        ]}
                      >
                        {t('Bir Zumda Jonatish')}
                      </Text>
                    </View>
                  ) : (
                    <View>
                      <Text
                        style={[
                          styles.cardLabel,
                          item.label === "Hisobni o'chirish"
                            ? { color: '#ef4444' }
                            : isDark
                              ? styles.darkText
                              : styles.lightText,
                        ]}
                      >
                        {t(item.label)}
                      </Text>
                    </View>
                  )}
                </View>

                <ChevronRight
                  size={20}
                  color={item.label === "Hisobni o'chirish" ? '#ef4444' : isDark ? '#64748b' : '#94a3b8'}
                />
              </TouchableOpacity>

            ))}
          </View>
        </View>
      ))
      }
    </ScrollView >
  );
}

const styles = StyleSheet.create({
  content: {
    flex: 1,
    paddingBottom: 120,
  },

  darkBg: {
    backgroundColor: '#0f172a',
  },
  lightBg: {
    backgroundColor: '#f8fafc',
  },

  section: {
    marginBottom: 4,
    paddingTop: 16,
  },

  sectionTitle: {
    fontSize: 12,
    fontWeight: '700',
    textTransform: 'uppercase',
    letterSpacing: 1,
    paddingHorizontal: 20,
    marginBottom: 12,
  },

  darkSubText: {
    color: '#64748b',
  },
  lightSubText: {
    color: '#64748b',
  },

  sectionContent: {
    paddingHorizontal: 16,
    gap: 10,
  },

  card: {
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: 14,
    padding: 16,
    gap: 14,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.05,
    shadowRadius: 8,
    elevation: 2,
  },

  darkCard: {
    backgroundColor: '#1e293b',
    borderWidth: 1,
    borderColor: '#334155',
  },
  lightCard: {
    backgroundColor: '#ffffff',
    borderWidth: 1,
    borderColor: '#f1f5f9',
  },

  iconContainer: {
    width: 48,
    height: 48,
    borderRadius: 12,
    alignItems: 'center',
    justifyContent: 'center',
  },

  darkIconBg: {
    backgroundColor: 'rgba(59, 130, 246, 0.15)',
  },
  lightIconBg: {
    backgroundColor: 'rgba(59, 130, 246, 0.1)',
  },

  cardLabel: {
    flex: 1,
    fontSize: 16,
    fontWeight: '600',
    letterSpacing: 0.2,
  },

  darkText: {
    color: '#f1f5f9',
  },
  lightText: {
    color: '#0f172a',
  },
  badge: {
    position: 'absolute',
    top: -5,
    right: -5,
    backgroundColor: '#ef4444', // qizil badge
    borderRadius: 8,
    minWidth: 16,
    height: 16,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 3,
  },

  badgeText: {
    color: '#ffffff',
    fontSize: 10,
    fontWeight: '700',
    textAlign: 'center',
  },
});
