import { useTheme } from '@/components/ThemeContext';
import { products_api } from '@/screens/home/lib/api';
import { useInfiniteQuery } from '@tanstack/react-query';
import { Image } from 'expo-image';
import { Building2, ChevronDown, ChevronUp } from 'lucide-react-native';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  Dimensions,
  FlatList,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

const { width: SCREEN_WIDTH } = Dimensions.get('window');
const PAGE_SIZE = 10;

export default function CountriesList({ search }: { search: string }) {
  const { isDark } = useTheme();
  const { t } = useTranslation();
  const [openedCountryId, setOpenedCountryId] = useState<number | null>(null);

  const { data, isLoading, isError, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useInfiniteQuery({
      queryKey: ['countries-list-infinite', search],
      queryFn: async ({ pageParam = 1 }) => {
        const response = await products_api.getCountry({
          page: pageParam,
          page_size: PAGE_SIZE,
          search: search,
        });
        return response.data.data;
      },
      getNextPageParam: (lastPage) =>
        lastPage.current_page < lastPage.total_pages ? lastPage.current_page + 1 : undefined,
      initialPageParam: 1,
    });

  const allCountries = data?.pages.flatMap((page) => page.results) ?? [];

  const toggleAccordion = (id: number) => setOpenedCountryId((prev) => (prev === id ? null : id));

  const loadMore = () => hasNextPage && !isFetchingNextPage && fetchNextPage();

  if (isLoading) {
    return (
      <View style={styles.center}>
        <ActivityIndicator size="large" color="#3b82f6" />
      </View>
    );
  }

  if (isError) {
    return (
      <View style={styles.center}>
        <Text style={styles.errorText}>{t('Xatolik yuz berdi')}</Text>
      </View>
    );
  }

  if (allCountries.length === 0) {
    return (
      <View style={styles.emptyContainer}>
        <Text style={[styles.emptyText, isDark ? styles.darkSubText : styles.lightSubText]}>
          {t('Natija topilmadi')}
        </Text>
      </View>
    );
  }

  return (
    <FlatList
      data={allCountries}
      keyExtractor={(item) => item.id.toString()}
      contentContainerStyle={{ gap: 5, paddingBottom: 80 }}
      onEndReached={loadMore}
      onEndReachedThreshold={0.4}
      ListFooterComponent={
        isFetchingNextPage ? <ActivityIndicator color="#3b82f6" style={{ margin: 20 }} /> : null
      }
      showsVerticalScrollIndicator={false}
      renderItem={({ item }) => {
        const isOpen = openedCountryId === item.id;
        const flagCode = item.flag ? item.flag.toLowerCase() : ''; // "uz"
        return (
          <View style={[styles.countryCard, isDark ? styles.darkCard : styles.lightCard]}>
            {/* Davlat sarlavhasi */}
            <TouchableOpacity
              style={styles.countryHeader}
              onPress={() => toggleAccordion(item.id)}
              activeOpacity={0.8}
            >
              <View
                style={{
                  flexDirection: 'row',
                  gap: 10,
                  alignContent: 'center',
                  alignItems: 'center',
                }}
              >
                <Image
                  source={{ uri: `https://flagcdn.com/w320/${flagCode}.png` }}
                  style={{ width: 40, height: 20 }}
                  resizeMode="cover" // objectFit o'rniga resizeMode ishlatildi
                />

                <Text style={[styles.countryName, isDark ? styles.darkText : styles.lightText]}>
                  {item.name}
                </Text>
              </View>
              <View style={styles.rightSide}>
                <Text
                  style={[styles.companyCount, isDark ? styles.darkSubText : styles.lightSubText]}
                >
                  {item.companies.length} {t('ta korxona')}
                </Text>
                {isOpen ? (
                  <ChevronUp size={20} color={isDark ? '#64748b' : '#94a3b8'} />
                ) : (
                  <ChevronDown size={20} color={isDark ? '#64748b' : '#94a3b8'} />
                )}
              </View>
            </TouchableOpacity>

            {/* Ochiladigan qism */}
            {isOpen && (
              <View style={styles.companiesContainer}>
                {item.companies.map((company) => (
                  <View
                    key={company.id}
                    style={[
                      styles.companyItem,
                      isDark ? styles.darkCompanyItem : styles.lightCompanyItem,
                    ]}
                  >
                    <Building2 size={18} color="#3b82f6" />
                    <View style={styles.companyInfo}>
                      <Text
                        style={[styles.companyName, isDark ? styles.darkText : styles.lightText]}
                      >
                        {company.company_name}
                      </Text>
                      <Text
                        style={[
                          styles.serviceCount,
                          isDark ? styles.darkSubText : styles.lightSubText,
                        ]}
                      >
                        {company.service_count} {t('ta mahsulot/xizmat')}
                      </Text>
                    </View>
                  </View>
                ))}
              </View>
            )}
          </View>
        );
      }}
    />
  );
}

const CARD_WIDTH = SCREEN_WIDTH - 32;

const styles = StyleSheet.create({
  center: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 40 },
  loadingText: { fontSize: 16, marginTop: 10 },
  errorText: { fontSize: 16, color: '#ef4444', textAlign: 'center' },
  emptyContainer: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 16 },

  countryCard: {
    width: CARD_WIDTH - 4,
    borderRadius: 16,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.2,
    shadowRadius: 6,
    elevation: 2,
    marginLeft: 2,
    marginBottom: 5,
  },
  darkCard: {
    backgroundColor: '#1e293b',
  },
  lightCard: {
    backgroundColor: '#ffffff',
  },
  countryHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 16,
  },
  countryName: { fontSize: 17, fontWeight: '700' },
  darkText: {
    color: '#f1f5f9',
  },
  lightText: {
    color: '#0f172a',
  },
  rightSide: { flexDirection: 'row', alignItems: 'center', gap: 8 },
  companyCount: { fontSize: 14 },
  darkSubText: {
    color: '#64748b',
  },
  lightSubText: {
    color: '#94a3b8',
  },

  companiesContainer: { paddingHorizontal: 16, paddingBottom: 16, gap: 10 },
  companyItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    paddingVertical: 10,
    paddingHorizontal: 12,
    borderRadius: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 4,
    elevation: 3,
  },
  darkCompanyItem: {
    backgroundColor: '#0f172a',
  },
  lightCompanyItem: {
    backgroundColor: '#f8fafc',
  },
  companyInfo: { flex: 1 },
  companyName: { fontSize: 15, fontWeight: '600' },
  serviceCount: { fontSize: 13, marginTop: 2 },
});
