import React, { useState } from 'react';
import {
  View,
  Dimensions,
  Image,
  TouchableOpacity,
  Alert,
  Platform,
} from 'react-native';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { theme, tw, useManualRefresh, MyFlatList, useDrawerTitle, useMarkDataFetchers, LoadingDialog, MyText, MyTouchableOpacity } from 'common-ui';
import dayjs from 'dayjs';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import FontAwesome5 from '@expo/vector-icons/FontAwesome5';
import { trpc } from '@/src/trpc-client';
import { useAddToCart } from '@/hooks/cart-query-hooks';
import ProductCard from '@/components/ProductCard';
import FloatingCartBar from '@/components/floating-cart-bar';

const { width: screenWidth } = Dimensions.get('window');
const itemWidth = (screenWidth - 48) / 2; // 48 = padding horizontal (16*2) + gap (16)


export default function StoreDetail() {
  const router = useRouter();
  // const { storeId } = useLocalSearchParams();
  const { id: storeId } = useLocalSearchParams();
  const storeIdNum = parseInt(storeId as string);
  const [isLoadingDialogOpen, setIsLoadingDialogOpen] = useState(false);

  const { data: storeData, isLoading, refetch, error } = trpc.user.stores.getStoreWithProducts.useQuery(
    { storeId: storeIdNum },
    { enabled: !!storeIdNum }
  );
  

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

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

  const addToCart = useAddToCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true });

  const handleAddToCart = (productId: number) => {
    setIsLoadingDialogOpen(true);
    addToCart.mutate({ productId, quantity: 1 }, {
      onSuccess: () => {
        Alert.alert('Success', 'Item added to cart!');
      },
      onError: (error: any) => {
        Alert.alert('Error', error.message || 'Failed to add item to cart');
      },
      onSettled: () => {
        setIsLoadingDialogOpen(false);
      },
    });
  };

  const handleBuyNow = (productId: number) => {
    setIsLoadingDialogOpen(true);
    addToCart.mutate({ productId, quantity: 1 }, {
      onSuccess: () => {
        router.push(`/(drawer)/(tabs)/home/cart?select=${productId}`);
      },
      onError: (error: any) => {
        Alert.alert('Error', error.message || 'Failed to add item to cart');
      },
      onSettled: () => {
        setIsLoadingDialogOpen(false);
      },
    });
  };

  if (isLoading) {
    return (
      <View style={tw`flex-1 justify-center items-center bg-gray-50`}>
        <MyText style={tw`text-gray-500 font-medium`}>Loading store...</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={storeData?.products || []}
        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}
           />
        )}
        keyExtractor={(item, index) => index.toString()}
        columnWrapperStyle={{ gap: 16 }}
        contentContainerStyle={[tw`px-4 pb-24`, { gap: 16 }]}
        ListHeaderComponent={
          <View style={tw`pt-4 pb-6`}>
            <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>
            <View style={tw`flex-row items-center mt-6 mb-2`}>
              <MaterialIcons name="grid-view" size={20} color="#374151" />
              <MyText style={tw`text-lg font-bold text-gray-900 ml-2`}>Products from this Store</MyText>
            </View>
          </View>
        }
      />
      <LoadingDialog open={isLoadingDialogOpen} message="Processing..." />

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