import { useTheme } from '@/components/ThemeContext';
import { products_api } from '@/screens/home/lib/api';
import { useMutation, useQuery } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import { XIcon } from 'lucide-react-native';
import React, { Dispatch, SetStateAction, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import CategorySelect from './CategorySelect';

interface FilterUIProps {
  back: () => void;
  onApply?: (data: any) => void;
  setStep: Dispatch<SetStateAction<'filter' | 'items'>>;
  setFiltered: Dispatch<SetStateAction<any[]>>;
}

interface Category {
  id: number;
  name: string;
  code: string;
  external_id: string | null;
  level: number;
  is_leaf: boolean;
  icon_name: string | null;
}

export default function FilterUI({ back, onApply, setStep, setFiltered }: FilterUIProps) {
  const { isDark } = useTheme();
  const { t } = useTranslation();
  const [selectedCategories, setSelectedCategories] = useState<Category | null>(null);
  const [selectedCountry, setSelectedCountry] = useState<string>('all');
  const [selectedRegion, setSelectedRegion] = useState<string>('all');
  const [selectedDistrict, setSelectedDistrict] = useState<string>('all');

  const { data: countryResponse, isLoading } = useQuery({
    queryKey: ['country-detail'],
    queryFn: async () => products_api.getStates(),
    select: (res) => res.data?.data || [],
  });

  const { mutate } = useMutation({
    mutationFn: (params: any) => products_api.businessAbout(params),
    onSuccess: (data) => {
      setStep('items');
      setFiltered(data.data.data.results);
    },
    onError: (error: AxiosError) => console.log(error),
  });

  const handleApply = () => {
    const countryObj = countryResponse?.find((c) => c.id?.toString() === selectedCountry);
    const regionObj = countryObj?.region.find((r) => r.id?.toString() === selectedRegion);
    const districtObj = regionObj?.districts.find((d) => d.id?.toString() === selectedDistrict);

    mutate({
      country: countryObj?.name || '',
      region: regionObj?.name || '',
      district: districtObj?.name || '',
      types: selectedCategories ? selectedCategories.id : undefined,
    });
  };

  const regions = useMemo(() => {
    if (selectedCountry === 'all') return [];
    const country = countryResponse?.find((c) => c.id?.toString() === selectedCountry);
    return country?.region || [];
  }, [countryResponse, selectedCountry]);

  const districts = useMemo(() => {
    if (selectedRegion === 'all') return [];
    const region = regions.find((r) => r.id?.toString() === selectedRegion);
    return region?.districts || [];
  }, [regions, selectedRegion]);

  if (isLoading) {
    return (
      <View
        style={[
          styles.container,
          isDark ? styles.darkBg : styles.lightBg,
          { justifyContent: 'center', alignItems: 'center' },
        ]}
      >
        <ActivityIndicator size="large" color="#3b82f6" />
      </View>
    );
  }

  // Single Tag Component
  const Tag = ({
    label,
    selected,
    onPress,
  }: {
    label: string;
    selected: boolean;
    onPress: () => void;
  }) => (
    <TouchableOpacity
      style={[
        styles.tag,
        isDark ? styles.darkTag : styles.lightTag,
        selected && styles.tagSelected,
      ]}
      onPress={onPress}
      activeOpacity={0.7}
    >
      <Text
        style={[
          styles.tagText,
          isDark ? styles.darkTagText : styles.lightTagText,
          selected && styles.tagTextSelected,
        ]}
      >
        {label}
      </Text>
    </TouchableOpacity>
  );

  return (
    <View style={[styles.container, isDark ? styles.darkBg : styles.lightBg]}>
      {/* Header */}
      <View style={styles.btn}>
        <TouchableOpacity
          onPress={back}
          style={[styles.backBtn, isDark ? styles.darkBackBtn : styles.lightBackBtn]}
        >
          <XIcon color={isDark ? 'white' : '#0f172a'} fontSize={24} />
        </TouchableOpacity>
      </View>

      {/* Scrollable Content */}
      <ScrollView
        style={{ padding: 16 }}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ paddingBottom: 140 }}
      >
        {/* Country Filter */}
        <Text style={[styles.sectionTitle, isDark ? styles.darkText : styles.lightText]}>
          {t('Davlat')}
        </Text>
        <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.scrollRow}>
          <Tag
            label={t('Barchasi')}
            selected={selectedCountry === 'all'}
            onPress={() => setSelectedCountry('all')}
          />
          {countryResponse?.map((c) => (
            <Tag
              key={c.id}
              label={c.name}
              selected={selectedCountry === c.id?.toString()}
              onPress={() => {
                setSelectedCountry(c.id?.toString() || 'all');
                setSelectedRegion('all');
                setSelectedDistrict('all');
              }}
            />
          ))}
        </ScrollView>

        {/* Region Filter */}
        {regions.length > 0 && (
          <>
            <Text style={[styles.sectionTitle, isDark ? styles.darkText : styles.lightText]}>
              {t('Viloyat')}
            </Text>
            <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.scrollRow}>
              <Tag
                label={t('Barchasi')}
                selected={selectedRegion === 'all'}
                onPress={() => setSelectedRegion('all')}
              />
              {regions.map((r) => (
                <Tag
                  key={r.id}
                  label={r.name}
                  selected={selectedRegion === r.id?.toString()}
                  onPress={() => {
                    setSelectedRegion(r.id?.toString() || 'all');
                    setSelectedDistrict('all');
                  }}
                />
              ))}
            </ScrollView>
          </>
        )}

        {/* District Filter */}
        {districts.length > 0 && (
          <>
            <Text style={[styles.sectionTitle, isDark ? styles.darkText : styles.lightText]}>
              {t('Tuman')}
            </Text>
            <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.scrollRow}>
              <Tag
                label={t('Barchasi')}
                selected={selectedDistrict === 'all'}
                onPress={() => setSelectedDistrict('all')}
              />
              {districts.map((d) => (
                <Tag
                  key={d.id}
                  label={d.name}
                  selected={selectedDistrict === d.id?.toString()}
                  onPress={() => setSelectedDistrict(d.id?.toString() || 'all')}
                />
              ))}
            </ScrollView>
          </>
        )}

        {/* Industry Selection */}
        <Text style={[styles.sectionTitle, isDark ? styles.darkText : styles.lightText]}>
          {t('Sohalar')}
        </Text>
        <CategorySelect
          selectedCategories={selectedCategories}
          setSelectedCategories={setSelectedCategories}
        />
      </ScrollView>

      {/* Fixed Apply Button */}
      <View style={styles.applyBtnWrapper}>
        <TouchableOpacity style={styles.applyBtn} onPress={handleApply}>
          <Text style={styles.applyBtnText}>{t("Natijalarni ko'rish")}</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  darkBg: {
    backgroundColor: '#0f172a',
  },
  lightBg: {
    backgroundColor: '#f8fafc',
  },
  backBtn: {
    paddingHorizontal: 10,
    paddingVertical: 10,
    borderRadius: 10,
    marginTop: 10,
    borderWidth: 1,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 2,
    elevation: 1,
  },
  darkBackBtn: {
    backgroundColor: '#1e293b',
    borderColor: '#334155',
  },
  lightBackBtn: {
    backgroundColor: '#ffffff',
    borderColor: '#e2e8f0',
  },
  btn: {
    justifyContent: 'flex-end',
    alignItems: 'flex-end',
    paddingHorizontal: 16,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '700',
    marginBottom: 10,
  },
  darkText: {
    color: '#f1f5f9',
  },
  lightText: {
    color: '#0f172a',
  },
  scrollRow: { flexDirection: 'row', marginBottom: 12, gap: 10 },

  tag: {
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderRadius: 12,
    marginRight: 10,
    borderWidth: 1,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 2,
    elevation: 1,
  },
  darkTag: {
    backgroundColor: '#1e293b',
    borderColor: '#334155',
  },
  lightTag: {
    backgroundColor: '#ffffff',
    borderColor: '#e2e8f0',
  },
  tagSelected: {
    backgroundColor: '#3b82f6',
    borderColor: '#3b82f6',
    shadowColor: '#3b82f6',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 5,
  },
  tagText: {
    fontWeight: '500',
  },
  darkTagText: {
    color: '#cbd5e1',
  },
  lightTagText: {
    color: '#64748b',
  },
  tagTextSelected: {
    color: '#ffffff',
    fontWeight: '600',
  },

  applyBtnWrapper: {
    position: 'absolute',
    bottom: 55,
    left: 16,
    right: 16,
    zIndex: 10,
  },
  applyBtn: {
    backgroundColor: '#3b82f6',
    padding: 16,
    borderRadius: 12,
    alignItems: 'center',
    shadowColor: '#3b82f6',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 5,
    marginBottom: 20,
  },
  applyBtnText: { color: '#ffffff', fontWeight: '700', fontSize: 16 },
});
