import React, { useState, useCallback, useMemo } from "react";
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  RefreshControl,
  ActivityIndicator,
  Platform,
  ScrollView,
} from "react-native";
import { useQuery } from "@tanstack/react-query";
import { Feather } from "@expo/vector-icons";
import { router } from "expo-router";
import { customFetch } from "@workspace/api-client-react";
import { useColors } from "@/hooks/useColors";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import VendorCard from "@/components/VendorCard";
import EmptyState from "@/components/EmptyState";

interface Vendor {
  id: number;
  companyName: string;
  sector: string;
  city: string;
  logoUrl?: string;
  isVerified: boolean;
  rating: string;
  totalReviews: number;
  categories: string[];
}

interface ProductSearchVendor {
  id: number;
  companyName: string;
  city: string;
  isVerified: boolean;
  rating: string;
  logoUrl?: string;
}

interface ProductSearchResult {
  product: { id: number; category: string };
  vendor: ProductSearchVendor;
}

export default function VendorsScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const isWeb = Platform.OS === "web";

  const [q, setQ] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCity, setSelectedCity] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("");
  const [verifiedOnly, setVerifiedOnly] = useState(false);
  const [minPrice, setMinPrice] = useState("");
  const [maxPrice, setMaxPrice] = useState("");
  const [showPriceFilter, setShowPriceFilter] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const hasPriceFilter = minPrice.length > 0 || maxPrice.length > 0;

  const { data: categories = [] } = useQuery<string[]>({
    queryKey: ["vendor-categories"],
    queryFn: () => customFetch<string[]>("/api/vendors/categories"),
    staleTime: 5 * 60 * 1000,
  });

  const { data: cities = [] } = useQuery<string[]>({
    queryKey: ["vendor-cities"],
    queryFn: () => customFetch<string[]>("/api/vendors/cities"),
    staleTime: 5 * 60 * 1000,
  });

  // Standard vendor list (used when no price filter is active)
  const vendorParams = new URLSearchParams({
    ...(searchQuery && { search: searchQuery }),
    ...(selectedCity && { city: selectedCity }),
    ...(selectedCategory && { category: selectedCategory }),
    ...(verifiedOnly && { verified: "true" }),
    limit: "40",
  }).toString();

  const { data: vendorData, isLoading: vendorsLoading, refetch: refetchVendors } = useQuery({
    queryKey: ["mobile-vendors", vendorParams],
    queryFn: () =>
      customFetch<{ vendors: Vendor[]; total: number }>(
        `/api/vendors?${vendorParams}`
      ),
    enabled: !hasPriceFilter,
  });

  // Price-filtered vendor list — finds vendors via product search
  const productSearchParams = new URLSearchParams({
    ...(searchQuery && { q: searchQuery }),
    ...(selectedCity && { city: selectedCity }),
    ...(selectedCategory && { category: selectedCategory }),
    ...(minPrice && { minPrice }),
    ...(maxPrice && { maxPrice }),
    limit: "100",
  }).toString();

  const { data: priceFilteredData, isLoading: priceLoading, refetch: refetchPrice } = useQuery({
    queryKey: ["mobile-vendor-price-filter", productSearchParams],
    queryFn: () =>
      customFetch<{ products: ProductSearchResult[]; total: number }>(
        `/api/vendor-products/search?${productSearchParams}`
      ),
    enabled: hasPriceFilter,
  });

  // Deduplicate vendors from product search results
  const priceFilteredVendors = useMemo<Vendor[]>(() => {
    if (!priceFilteredData?.products) return [];
    const seen = new Set<number>();
    return priceFilteredData.products.reduce<Vendor[]>((acc, item) => {
      if (!seen.has(item.vendor.id)) {
        seen.add(item.vendor.id);
        acc.push({
          id: item.vendor.id,
          companyName: item.vendor.companyName,
          sector: "",
          city: item.vendor.city,
          logoUrl: item.vendor.logoUrl,
          isVerified: item.vendor.isVerified,
          rating: item.vendor.rating,
          totalReviews: 0,
          categories: [],
        });
      }
      return acc;
    }, []);
  }, [priceFilteredData]);

  const vendors = hasPriceFilter ? priceFilteredVendors : (vendorData?.vendors ?? []);
  const isLoading = hasPriceFilter ? priceLoading : vendorsLoading;

  const handleRefresh = useCallback(async () => {
    setRefreshing(true);
    await (hasPriceFilter ? refetchPrice() : refetchVendors());
    setRefreshing(false);
  }, [hasPriceFilter, refetchPrice, refetchVendors]);

  const clearPriceFilter = () => {
    setMinPrice("");
    setMaxPrice("");
  };

  const topPad = isWeb ? 67 : insets.top;

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <View
        style={[
          styles.header,
          {
            paddingTop: topPad + 16,
            backgroundColor: colors.background,
            borderBottomColor: colors.border,
          },
        ]}
      >
        <Text
          style={[
            styles.title,
            { color: colors.foreground, fontFamily: "Inter_700Bold" },
          ]}
        >
          Vendors
        </Text>

        {/* Search bar */}
        <View
          style={[
            styles.searchRow,
            { backgroundColor: colors.muted, borderRadius: colors.radius },
          ]}
        >
          <Feather
            name="search"
            size={18}
            color={colors.mutedForeground}
            style={{ marginLeft: 12 }}
          />
          <TextInput
            value={q}
            onChangeText={setQ}
            onSubmitEditing={() => setSearchQuery(q)}
            returnKeyType="search"
            placeholder="Search by name, sector..."
            placeholderTextColor={colors.mutedForeground}
            style={[
              styles.searchInput,
              { color: colors.foreground, fontFamily: "Inter_400Regular" },
            ]}
          />
          {q.length > 0 && (
            <TouchableOpacity
              onPress={() => {
                setQ("");
                setSearchQuery("");
              }}
              style={{ paddingHorizontal: 12 }}
              hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
            >
              <Feather name="x" size={16} color={colors.mutedForeground} />
            </TouchableOpacity>
          )}
        </View>

        {/* Filter chips: price, verified, category, city */}
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          style={styles.filterScroll}
          contentContainerStyle={{ gap: 8, paddingHorizontal: 16 }}
        >
          {/* Price range chip */}
          <TouchableOpacity
            onPress={() => setShowPriceFilter(!showPriceFilter)}
            style={[
              styles.chip,
              {
                backgroundColor: hasPriceFilter ? colors.accent : colors.muted,
                borderRadius: 20,
                flexDirection: "row",
                alignItems: "center",
              },
            ]}
          >
            <Feather
              name="sliders"
              size={12}
              color={hasPriceFilter ? colors.accentForeground : colors.mutedForeground}
              style={{ marginRight: 4 }}
            />
            <Text
              style={[
                styles.chipText,
                {
                  color: hasPriceFilter
                    ? colors.accentForeground
                    : colors.mutedForeground,
                  fontFamily: "Inter_500Medium",
                },
              ]}
            >
              {hasPriceFilter
                ? `SAR ${minPrice || "0"} – ${maxPrice || "∞"}`
                : "Price"}
            </Text>
          </TouchableOpacity>

          {/* Verified toggle chip */}
          <TouchableOpacity
            onPress={() => setVerifiedOnly(!verifiedOnly)}
            style={[
              styles.chip,
              {
                backgroundColor: verifiedOnly ? colors.primary : colors.muted,
                borderRadius: 20,
                flexDirection: "row",
                alignItems: "center",
              },
            ]}
            activeOpacity={0.8}
          >
            <Feather
              name="check-circle"
              size={12}
              color={
                verifiedOnly ? colors.primaryForeground : colors.mutedForeground
              }
              style={{ marginRight: 4 }}
            />
            <Text
              style={[
                styles.chipText,
                {
                  color: verifiedOnly
                    ? colors.primaryForeground
                    : colors.mutedForeground,
                  fontFamily: "Inter_500Medium",
                },
              ]}
            >
              Verified
            </Text>
          </TouchableOpacity>

          {/* Category chips */}
          {categories.slice(0, 6).map((cat) => {
            const active = selectedCategory === cat;
            return (
              <TouchableOpacity
                key={cat}
                onPress={() => setSelectedCategory(active ? "" : cat)}
                style={[
                  styles.chip,
                  {
                    backgroundColor: active ? colors.primary : colors.muted,
                    borderRadius: 20,
                  },
                ]}
              >
                <Text
                  style={[
                    styles.chipText,
                    {
                      color: active
                        ? colors.primaryForeground
                        : colors.mutedForeground,
                      fontFamily: "Inter_500Medium",
                    },
                  ]}
                >
                  {cat}
                </Text>
              </TouchableOpacity>
            );
          })}

          {/* City chips */}
          {cities.slice(0, 5).map((city) => {
            const active = selectedCity === city;
            return (
              <TouchableOpacity
                key={city}
                onPress={() => setSelectedCity(active ? "" : city)}
                style={[
                  styles.chip,
                  {
                    backgroundColor: active ? colors.secondary : colors.muted,
                    borderRadius: 20,
                    flexDirection: "row",
                    alignItems: "center",
                  },
                ]}
              >
                <Feather
                  name="map-pin"
                  size={11}
                  color={active ? "#D6E0F0" : colors.mutedForeground}
                  style={{ marginRight: 4 }}
                />
                <Text
                  style={[
                    styles.chipText,
                    {
                      color: active ? "#D6E0F0" : colors.mutedForeground,
                      fontFamily: "Inter_500Medium",
                    },
                  ]}
                >
                  {city}
                </Text>
              </TouchableOpacity>
            );
          })}
        </ScrollView>

        {/* Price range inline panel */}
        {showPriceFilter && (
          <View
            style={[
              styles.pricePanel,
              {
                backgroundColor: colors.muted,
                borderRadius: colors.radius,
                borderColor: colors.border,
              },
            ]}
          >
            <Text
              style={[
                styles.pricePanelLabel,
                { color: colors.mutedForeground, fontFamily: "Inter_500Medium" },
              ]}
            >
              Product price range (SAR)
            </Text>
            <View style={styles.priceRow}>
              <TextInput
                value={minPrice}
                onChangeText={setMinPrice}
                keyboardType="numeric"
                placeholder="Min"
                placeholderTextColor={colors.mutedForeground}
                returnKeyType="next"
                style={[
                  styles.priceInput,
                  {
                    color: colors.foreground,
                    backgroundColor: colors.card,
                    borderColor: colors.border,
                    borderRadius: colors.radius - 2,
                    fontFamily: "Inter_400Regular",
                  },
                ]}
              />
              <Text
                style={[
                  styles.priceSep,
                  { color: colors.mutedForeground, fontFamily: "Inter_400Regular" },
                ]}
              >
                –
              </Text>
              <TextInput
                value={maxPrice}
                onChangeText={setMaxPrice}
                keyboardType="numeric"
                placeholder="Max"
                placeholderTextColor={colors.mutedForeground}
                returnKeyType="done"
                onSubmitEditing={() => setShowPriceFilter(false)}
                style={[
                  styles.priceInput,
                  {
                    color: colors.foreground,
                    backgroundColor: colors.card,
                    borderColor: colors.border,
                    borderRadius: colors.radius - 2,
                    fontFamily: "Inter_400Regular",
                  },
                ]}
              />
              {hasPriceFilter && (
                <TouchableOpacity
                  onPress={() => {
                    clearPriceFilter();
                    setShowPriceFilter(false);
                  }}
                  style={[
                    styles.clearBtn,
                    { backgroundColor: colors.destructive + "18", borderRadius: 6 },
                  ]}
                  hitSlop={{ top: 4, bottom: 4, left: 4, right: 4 }}
                >
                  <Text
                    style={[
                      styles.clearBtnText,
                      { color: colors.destructive, fontFamily: "Inter_500Medium" },
                    ]}
                  >
                    Clear
                  </Text>
                </TouchableOpacity>
              )}
              <TouchableOpacity
                onPress={() => setShowPriceFilter(false)}
                style={[
                  styles.applyBtn,
                  { backgroundColor: colors.primary, borderRadius: 6 },
                ]}
              >
                <Text
                  style={[
                    styles.applyBtnText,
                    { color: colors.primaryForeground, fontFamily: "Inter_600SemiBold" },
                  ]}
                >
                  Apply
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        )}
      </View>

      {/* Result count + price filter note */}
      {!isLoading && vendors.length > 0 && (
        <View style={styles.countRow}>
          <Text
            style={[
              styles.countText,
              { color: colors.mutedForeground, fontFamily: "Inter_400Regular" },
            ]}
          >
            {hasPriceFilter ? priceFilteredVendors.length : (vendorData?.total ?? vendors.length)} vendors
          </Text>
          {hasPriceFilter && (
            <Text
              style={[
                styles.priceNote,
                { color: colors.accent, fontFamily: "Inter_400Regular" },
              ]}
            >
              with products in selected range
            </Text>
          )}
        </View>
      )}

      {isLoading ? (
        <View style={styles.center}>
          <ActivityIndicator color={colors.primary} size="large" />
        </View>
      ) : vendors.length === 0 ? (
        <EmptyState
          icon="briefcase"
          title="No vendors found"
          subtitle="Try a different search term or clear filters"
        />
      ) : (
        <FlatList
          data={vendors}
          keyExtractor={(item) => item.id.toString()}
          renderItem={({ item }) => (
            <VendorCard
              vendor={item}
              onPress={() => router.push(`/vendor/${item.id}`)}
            />
          )}
          contentContainerStyle={{
            padding: 16,
            gap: 12,
            paddingBottom: isWeb ? 50 : 100,
          }}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={handleRefresh}
              tintColor={colors.primary}
            />
          }
          showsVerticalScrollIndicator={false}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  header: {
    paddingHorizontal: 16,
    paddingBottom: 12,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  title: { fontSize: 28, marginBottom: 12 },
  searchRow: { flexDirection: "row", alignItems: "center", height: 44 },
  searchInput: { flex: 1, height: 44, paddingHorizontal: 8, fontSize: 15 },
  filterScroll: { marginTop: 12, marginHorizontal: -16 },
  chip: { paddingVertical: 6, paddingHorizontal: 12 },
  chipText: { fontSize: 13 },
  pricePanel: {
    marginTop: 10,
    padding: 12,
    borderWidth: StyleSheet.hairlineWidth,
  },
  pricePanelLabel: { fontSize: 12, marginBottom: 8 },
  priceRow: { flexDirection: "row", alignItems: "center", gap: 8 },
  priceInput: {
    flex: 1,
    height: 38,
    paddingHorizontal: 10,
    fontSize: 14,
    borderWidth: 1,
  },
  priceSep: { fontSize: 16 },
  clearBtn: { paddingHorizontal: 10, paddingVertical: 8 },
  clearBtnText: { fontSize: 13 },
  applyBtn: { paddingHorizontal: 14, paddingVertical: 8 },
  applyBtnText: { fontSize: 13 },
  countRow: {
    flexDirection: "row",
    alignItems: "center",
    gap: 6,
    marginHorizontal: 16,
    marginTop: 12,
    marginBottom: 2,
  },
  countText: { fontSize: 13 },
  priceNote: { fontSize: 12 },
  center: { flex: 1, alignItems: "center", justifyContent: "center" },
});
