import React, { useState, useCallback } from "react";
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  RefreshControl,
  ScrollView,
  ActivityIndicator,
  Platform,
} 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 ProductCard from "@/components/ProductCard";
import EmptyState from "@/components/EmptyState";

interface Product {
  product: {
    id: number;
    name: string;
    category: string;
    minPrice?: string;
    maxPrice?: string;
    currency: string;
    unit: string;
    inStock: boolean;
    imageUrl?: string;
  };
  vendor: {
    id: number;
    companyName: string;
    city: string;
    isVerified: boolean;
    rating: string;
    logoUrl?: string;
  };
}

export default function BrowseScreen() {
  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 [minPrice, setMinPrice] = useState("");
  const [maxPrice, setMaxPrice] = useState("");
  const [showPriceFilter, setShowPriceFilter] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  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,
  });

  const productParams = new URLSearchParams({
    ...(searchQuery && { q: searchQuery }),
    ...(selectedCity && { city: selectedCity }),
    ...(selectedCategory && { category: selectedCategory }),
    ...(minPrice && { minPrice }),
    ...(maxPrice && { maxPrice }),
    limit: "30",
  }).toString();

  const { data, isLoading, refetch } = useQuery({
    queryKey: ["mobile-products", productParams],
    queryFn: () =>
      customFetch<{ products: Product[]; total: number }>(
        `/api/vendor-products/search?${productParams}`
      ),
  });

  const products = data?.products ?? [];

  const handleRefresh = useCallback(async () => {
    setRefreshing(true);
    await refetch();
    setRefreshing(false);
  }, [refetch]);

  const doSearch = () => setSearchQuery(q);

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

  const hasPriceFilter = minPrice.length > 0 || maxPrice.length > 0;
  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" },
          ]}
        >
          Marketplace
        </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={doSearch}
            returnKeyType="search"
            placeholder="Search products or services..."
            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>

        {/* Category + city + price filter chips */}
        {(categories.length > 0 || cities.length > 0) && (
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            style={styles.filterScroll}
            contentContainerStyle={{ gap: 8, paddingHorizontal: 16 }}
          >
            {/* Price filter 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>

            {/* 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" },
              ]}
            >
              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.clearPriceBtn,
                    { backgroundColor: colors.destructive + "18", borderRadius: 6 },
                  ]}
                  hitSlop={{ top: 4, bottom: 4, left: 4, right: 4 }}
                >
                  <Text
                    style={[
                      styles.clearPriceText,
                      { color: colors.destructive, fontFamily: "Inter_500Medium" },
                    ]}
                  >
                    Clear
                  </Text>
                </TouchableOpacity>
              )}
              <TouchableOpacity
                onPress={() => setShowPriceFilter(false)}
                style={[
                  styles.applyBtn,
                  { backgroundColor: colors.primary, borderRadius: 6 },
                ]}
              >
                <Text
                  style={[
                    styles.applyText,
                    { color: colors.primaryForeground, fontFamily: "Inter_600SemiBold" },
                  ]}
                >
                  Apply
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        )}
      </View>

      {!isLoading && products.length > 0 && (
        <Text
          style={[
            styles.countText,
            { color: colors.mutedForeground, fontFamily: "Inter_400Regular" },
          ]}
        >
          {data?.total ?? products.length} results
        </Text>
      )}

      {isLoading ? (
        <View style={styles.center}>
          <ActivityIndicator color={colors.primary} size="large" />
        </View>
      ) : products.length === 0 ? (
        <EmptyState
          icon="package"
          title="No products found"
          subtitle="Try different search terms or clear the filters above"
        />
      ) : (
        <FlatList
          data={products}
          keyExtractor={(item) => item.product.id.toString()}
          renderItem={({ item }) => (
            <ProductCard
              product={item.product}
              vendor={item.vendor}
              onPress={() => router.push(`/vendor/${item.vendor.id}`)}
            />
          )}
          contentContainerStyle={{
            padding: 16,
            gap: 12,
            paddingBottom: isWeb ? 50 : 100,
          }}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={handleRefresh}
              tintColor={colors.primary}
            />
          }
          showsVerticalScrollIndicator={false}
          scrollEnabled
        />
      )}
    </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 },
  clearPriceBtn: { paddingHorizontal: 10, paddingVertical: 8 },
  clearPriceText: { fontSize: 13 },
  applyBtn: { paddingHorizontal: 14, paddingVertical: 8 },
  applyText: { fontSize: 13 },
  countText: {
    fontSize: 13,
    marginHorizontal: 16,
    marginTop: 12,
    marginBottom: 2,
  },
  center: { flex: 1, alignItems: "center", justifyContent: "center" },
});
