import React, { useMemo, useState } from "react";
import { View, Dimensions, ScrollView, TouchableOpacity } from "react-native";
import { useRouter, useLocalSearchParams } from "expo-router";
import { Image } from 'expo-image';
import {
  theme,
  tw,
  useManualRefresh,
  useMarkDataFetchers,
  MyFlatList,
  useDrawerTitle,
  MyText,
} from "common-ui";
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import FontAwesome5 from "@expo/vector-icons/FontAwesome5";
import ProductCard from "@/components/ProductCard";
import FloatingCartBar from "@/components/floating-cart-bar";
import { useStoreHeaderStore } from "@/src/store/storeHeaderStore";
import { useAllProducts, useStoreWithProducts } from "@/src/hooks/prominent-api-hooks";

const { width: screenWidth } = Dimensions.get("window");
const itemWidth = (screenWidth - 48) / 2;

interface Tag {
  id: number;
  tagName: string;
  productIds?: number[];
}

interface ChipProps {
  tag: Tag;
  isSelected: boolean;
  onPress: () => void;
}

const Chip: React.FC<ChipProps> = ({ tag, isSelected, onPress }) => {
  const productCount = tag.productIds?.length || 0;
  
  return (
    <TouchableOpacity
      onPress={onPress}
      style={tw`px-4 py-2 rounded-lg border ${
        isSelected
          ? 'bg-brand500 border-brand500'
          : 'bg-white border-brand500'
      }`}
    >
      <MyText
        style={tw`font-medium text-sm ${
          isSelected ? 'text-white' : 'text-brand500'
        }`}
      >
        {tag.tagName} ({productCount})
      </MyText>
    </TouchableOpacity>
  );
};

export default function StoreDetail() {
  const router = useRouter();
  const { id: storeId } = useLocalSearchParams();
  const storeIdNum = parseInt(storeId as string);
  const [selectedTagId, setSelectedTagId] = useState<number | null>(null);

  const { data: storeData, isLoading, refetch, error } =
    useStoreWithProducts(storeIdNum);

  const { data: productsData, isLoading: isProductsLoading } = useAllProducts();

  const productById = useMemo(() => {
    const map = new Map<number, any>();
    productsData?.products?.forEach((product) => {
      map.set(product.id, product);
    });
    return map;
  }, [productsData]);

  const storeProducts = useMemo(() => {
    if (!storeData?.products) return [];
    return storeData.products
      .map((product) => productById.get(product.id))
      .filter(Boolean);
  }, [storeData, productById]);

  // Filter products based on selected tag
  const filteredProducts = selectedTagId
    ? storeProducts.filter(product => {
        const selectedTag = storeData?.tags.find(t => t.id === selectedTagId);
        return selectedTag?.productIds?.includes(product.id) ?? false;
      })
    : storeProducts;

  // Set the store header title
  const setStoreHeaderTitle = useStoreHeaderStore((state) => state.setTitle);
  if (storeData?.store?.name) {
    setStoreHeaderTitle(storeData.store.name);
  }

  useManualRefresh(() => {
    refetch();
  });

  useMarkDataFetchers(() => {
    refetch();
  });

  useDrawerTitle(storeData?.store?.name || "Store", [storeData?.store?.name]);

  if (isLoading || isProductsLoading) {
    return (
      <View style={tw`flex-1 justify-center items-center bg-gray-50`}>
        <MyText style={tw`text-gray-500 font-medium`}>
          {isLoading ? 'Loading store...' : 'Loading products...'}
        </MyText>
      </View>
    );
  }

  if (error || !storeData) {
    return (
      <View style={tw`flex-1 justify-center items-center bg-gray-50`}>
        <MaterialIcons name="error-outline" size={48} color="#EF4444" />
        <MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Oops!</MyText>
        <MyText style={tw`text-gray-500 mt-2`}>
          Store not found or error loading
        </MyText>
      </View>
    );
  }

  return (
    <View style={tw`flex-1 bg-gray-50 relative`}>
      <MyFlatList
        data={filteredProducts}
        numColumns={2}
        renderItem={({ item }) => (
          <ProductCard
            item={item}
            itemWidth={itemWidth}
            onPress={() =>
              router.push(
                `/(drawer)/(tabs)/stores/store-detail/product-detail/${item.id}`
              )
            }
            showDeliveryInfo={false}
            miniView={true}
            useAddToCartDialog={true}
          />
        )}
        keyExtractor={(item, index) => index.toString()}
        columnWrapperStyle={{ gap: 16 }}
        contentContainerStyle={[tw`px-4 pb-24`, { gap: 16 }]}
        ListHeaderComponent={
          <View style={tw`pt-4 pb-6`}>
            {/* Meat Store Images - Show at top if store name contains 'meat' */}
            {storeData?.store?.name?.toLowerCase().includes('meat') && (
              <View style={tw`flex-row h-16 mb-4`}>
                <Image
                  source={{ uri: 'http://localhost:4000/assets/halal.jpg' }}
                  style={tw`flex-1 h-full`}
                  contentFit="cover"
                />
                <View style={tw`w-px bg-white`} />
                <Image
                  source={{ uri: 'http://localhost:4000/assets/preservs.jpg' }}
                  style={tw`flex-1 h-full`}
                  contentFit="cover"
                />
              </View>
            )}
            <View
              style={tw`bg-white p-6 rounded-2xl shadow-sm border border-gray-100 items-center`}
            >
              <View
                style={tw`w-16 h-16 bg-pink-50 rounded-full items-center justify-center mb-4`}
              >
                <FontAwesome5
                  name="store"
                  size={28}
                  color={theme.colors.brand500}
                />
              </View>
              <MyText
                style={tw`text-2xl font-bold text-gray-900 text-center mb-2`}
              >
                {storeData?.store?.name}
              </MyText>
              {storeData?.store?.description && (
                <MyText
                  style={tw`text-gray-500 text-center leading-5 px-4`}
                >
                  {storeData?.store?.description}
                </MyText>
              )}
            </View>
            {/* Tags Section */}
            {storeData?.tags && storeData.tags.length > 0 && (
              <ScrollView
                horizontal
                showsHorizontalScrollIndicator={false}
                contentContainerStyle={tw`gap-2 mt-6`}
              >
                {storeData.tags.map((tag) => (
                  <Chip
                    key={tag.id}
                    tag={tag}
                    isSelected={selectedTagId === tag.id}
                    onPress={() => setSelectedTagId(selectedTagId === tag.id ? null : tag.id)}
                  />
                ))}
              </ScrollView>
            )}

            <View style={tw`flex-row items-center justify-between mt-6 mb-2`}>
              <View style={tw`flex-row items-center`}>
                <MaterialIcons name="grid-view" size={20} color="#374151" />
                <MyText style={tw`text-lg font-bold text-gray-900 ml-2`}>
                  {selectedTagId
                    ? `${storeData?.tags.find(t => t.id === selectedTagId)?.tagName} items`
                    : `${filteredProducts.length} products`}
                </MyText>
              </View>
              {selectedTagId && (
                <TouchableOpacity
                  onPress={() => setSelectedTagId(null)}
                  style={tw`flex-row items-center`}
                >
                  <MyText style={tw`text-brand500 text-sm font-medium mr-1`}>
                    Clear
                  </MyText>
                  <MaterialIcons name="close" size={16} color={theme.colors.brand500} />
                </TouchableOpacity>
              )}
            </View>
          </View>
        }
      />

      <View style={tw`absolute bottom-2 left-4 right-4`}>
        <FloatingCartBar />
      </View>
    </View>
  );
}
