import React, { useState, useCallback } from 'react';
import {
  Box,
  Stack,
  Heading,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  Button,
  Badge,
  Checkbox,
  Input,
  HStack,
  Text,
  useToast,
  Spinner,
  Select,
  InputGroup,
  InputLeftElement,
  ButtonGroup,
  Slide,
  Portal,
  Progress,
  Tag,
  TagLabel,
  TagCloseButton,
  Flex,
  Menu,
  MenuButton,
  MenuList,
  MenuItem,
  MenuDivider,
  useColorModeValue,
  Container,
  VStack,
  Image,
  Grid,
  GridItem,
  Card,
  CardBody,
  IconButton,
  Tooltip,
  useDisclosure,
  Collapse,
  Divider,
  SimpleGrid,
  InputRightElement,
  List,
  ListItem,
  Center,
  Circle,
  Alert,
  AlertIcon
} from '@chakra-ui/react';
import {
  SearchIcon,
  CheckIcon,
  ChevronDownIcon,
  CloseIcon,
  ViewIcon,
  ViewOffIcon,
  SettingsIcon,
  InfoIcon,
  RepeatIcon
} from '@chakra-ui/icons';
import { FiTag, FiImage, FiPackage, FiBarChart2, FiGrid, FiList } from 'react-icons/fi';
import Pagination from '../common/Pagination';
import CategoryModal from './CategoryModal';
import BulkCategoryModal from './BulkCategoryModal';
import BulkEanModal from './BulkEanModal';
import ProductActionBar from './ProductActionBar';
import EanModal from './EanModal';
import ManufacturerModal from './ManufacturerModal';
import ProductImagesModal from './ProductImagesModal';

const PLACEHOLDER_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgdmlld0JveD0iMCAwIDIwMCAyMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHJlY3Qgd2lkdGg9IjIwMCIgaGVpZ2h0PSIyMDAiIGZpbGw9IiNFREVERUQiLz48cGF0aCBkPSJNODAgOTBINzBWMTEwSDgwVjEyMEg5MFYxMTBIMTAwVjEwMEg5MFY5MEg4MFoiIGZpbGw9IiM5Q0E0QjAiLz48cGF0aCBkPSJNMTIwIDkwSDExMFYxMTBIMTIwVjEyMEgxMzBWMTEwSDE0MFYxMDBIMTMwVjkwSDEyMFoiIGZpbGw9IiM5Q0E0QjAiLz48L3N2Zz4=';

const Products = () => {
  const [products, setProducts] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(true);
  const [selectedProducts, setSelectedProducts] = React.useState([]);
  const [selectedProductsCache, setSelectedProductsCache] = React.useState({});
  const [pagination, setPagination] = React.useState({
    currentPage: 1,
    totalPages: 1,
    totalItems: 0
  });
  const [search, setSearch] = React.useState('');
  const [perPage, setPerPage] = React.useState(10);
  const toast = useToast();
  const [selectedProduct, setSelectedProduct] = React.useState(null);
  const [isCategoryModalOpen, setIsCategoryModalOpen] = React.useState(false);
  const [bulkAction, setBulkAction] = React.useState('');
  const [isBulkCategoryModalOpen, setIsBulkCategoryModalOpen] = React.useState(false);
  const [categories, setCategories] = React.useState([]);
  const [selectedCategory, setSelectedCategory] = React.useState(null);
  const [isCategoriesLoading, setIsCategoriesLoading] = React.useState(true);
  const [isEanModalOpen, setIsEanModalOpen] = React.useState(false);
  const [isBulkEanModalOpen, setIsBulkEanModalOpen] = useState(false);
  const [selectedProductsForEan, setSelectedProductsForEan] = useState([]);
  const [isManufacturerModalOpen, setIsManufacturerModalOpen] = useState(false);
  const [isImagesModalOpen, setIsImagesModalOpen] = useState(false);
  const [viewMode, setViewMode] = useState('grid'); // 'grid' or 'list'
  const [showFilters, setShowFilters] = useState(true);
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  const hoverBg = useColorModeValue('gray.50', 'gray.700');
  const selectedBg = useColorModeValue('blue.50', 'blue.900');
  const textColor = useColorModeValue('gray.800', 'gray.100');
  const [searchQuery, setSearchQuery] = useState('');
  const categoryMenuDisclosure = useDisclosure();
  const [currentStep, setCurrentStep] = React.useState(1);

  const fetchCategories = async () => {
    setIsCategoriesLoading(true);
    try {
      const response = await fetch('/wp-json/wc/v3/products/categories?per_page=100', {
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch categories');
      }

      const data = await response.json();

      // Decode HTML entities in category names
      const decodedData = data.map(category => ({
        ...category,
        name: decodeHTMLEntities(category.name)
      }));

      setCategories(decodedData);

    } catch (error) {
      toast({
        title: 'Error loading categories',
        description: 'Could not load product categories.',
        status: 'error',
        duration: 3000
      });
      setCategories([]);
    } finally {
      setIsCategoriesLoading(false);
    }
  };

  // Helper function to decode HTML entities
  const decodeHTMLEntities = (text) => {
    const textarea = document.createElement('textarea');
    textarea.innerHTML = text;
    return textarea.value;
  };

  React.useEffect(() => {
    fetchCategories();
  }, []);

  const fetchProducts = async () => {
    setIsLoading(true);
    try {
      const queryParams = new URLSearchParams({
        page: pagination.currentPage,
        per_page: perPage,
        search: search
      });

      if (selectedCategory) {
        queryParams.append('category', selectedCategory);
      }

      // Using WooCommerce REST API endpoint for products
      const response = await fetch(
        `/wp-json/wc/v3/products?${queryParams.toString()}`, {
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce,
          'Content-Type': 'application/json'
        }
      }
      );

      if (!response.ok) {
        throw new Error('Failed to fetch products');
      }

      const data = await response.json();

      const totalItems = parseInt(response.headers.get('X-WP-Total') || '0');
      const totalPages = parseInt(response.headers.get('X-WP-TotalPages') || '0');

      // Transform WooCommerce products to match our format
      const transformedProducts = data.map(product => ({
        id: product.id,
        name: product.name,
        sku: product.sku,
        price: product.price,
        stock_quantity: product.stock_quantity,
        description: product.description,
        short_description: product.short_description,
        categories: product.categories,
        kaufland_status: product.meta_data?.find(meta => meta.key === '_klcnn_sync_status')?.value || 'not_synced',
        kaufland_category: product.meta_data?.find(meta => meta.key === '_klcnn_kaufland_category_title')?.value || null,
        kaufland_category_id: product.meta_data?.find(meta => meta.key === '_klcnn_kaufland_category_id')?.value || null,
        last_synced: product.meta_data?.find(meta => meta.key === '_klcnn_last_synced')?.value || null,
        selectedCategory: null,
        main_image: product.images[0] ? {
          id: product.images[0].id,
          url: product.images[0].src
        } : null,
        gallery_images: product.images.slice(1).map(img => ({
          id: img.id,
          url: img.src
        }))
      }));

      setProducts(transformedProducts);
      setPagination({
        ...pagination,
        totalPages,
        totalItems
      });
    } catch (error) {
      console.error('Error fetching products:', error);
      toast({
        title: 'Error loading products',
        description: 'Could not load products. Please check if WooCommerce is properly configured.',
        status: 'error',
        duration: 3000
      });
    } finally {
      setIsLoading(false);
    }
  };

  React.useEffect(() => {
    fetchProducts();
  }, [pagination.currentPage, perPage, search, selectedCategory]);

  const getSyncStatusBadge = (status) => {
    switch (status) {
      case 'synced':
        return <Badge colorScheme="green">Synced</Badge>;
      case 'pending':
        return <Badge colorScheme="yellow">Pending</Badge>;
      case 'error':
        return <Badge colorScheme="red">Error</Badge>;
      default:
        return <Badge colorScheme="gray">Not Synced</Badge>;
    }
  };

  const handleSetCategory = (product) => {
    setSelectedProduct(product);
    setIsCategoryModalOpen(true);
  };

  const handleSetEan = (product) => {
    setSelectedProduct(product);
    setIsEanModalOpen(true);
  };

  const handleCategoryModalClose = () => {
    setSelectedProduct(null);
    setIsCategoryModalOpen(false);
  };

  const handleBulkAction = () => {
    if (!bulkAction || selectedProducts.length === 0) return;

    switch (bulkAction) {
      case 'set_category':
        setIsBulkCategoryModalOpen(true);
        break;
      case 'sync':
        handleBulkPushToKaufland();
        break;
      case 'manage_images':
        // Use the cached products instead of filtering from current page
        const selectedProductsDetails = Object.values(selectedProductsCache);
        setSelectedProduct(selectedProductsDetails);
        setIsImagesModalOpen(true);
        break;
      case 'set_manufacturer':
        // Get the first selected product from cache
        const firstSelectedProduct = selectedProductsCache[selectedProducts[0]];
        setSelectedProduct(firstSelectedProduct);
        setIsManufacturerModalOpen(true);
        break;
      default:
        break;
    }
    // Reset bulk action after processing
    setBulkAction('');
  };

  const handleBulkPushToKaufland = async () => {
    // First, check which products are missing EANs
    const productsWithoutEAN = selectedProductDetails.filter(product => !product.ean);

    if (productsWithoutEAN.length > 0) {
      // Show EAN assignment modal for products without EAN
      setSelectedProductsForEan(productsWithoutEAN);
      setIsBulkEanModalOpen(true);
    } else {
      // All products have EANs, proceed with push
      await pushSelectedProductsToKaufland();
    }
  };

  const pushSelectedProductsToKaufland = async () => {
    const successfulPushes = [];
    const failedPushes = [];

    for (const productId of selectedProducts) {
      try {
        const response = await fetch(`/wp-json/klcnn/v1/products/${productId}/push`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': window.klcnnData.nonce
          }
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || 'Failed to push product');
        }

        successfulPushes.push(productId);

        // Update product sync status in UI
        setProducts(prevProducts =>
          prevProducts.map(p =>
            p.id === productId
              ? { ...p, kaufland_status: 'pending' }
              : p
          )
        );

      } catch (error) {
        failedPushes.push({ id: productId, error: error.message });
      }
    }

    // Show summary toast
    if (successfulPushes.length > 0) {
      toast({
        title: 'Products pushed to Kaufland',
        description: `Successfully pushed ${successfulPushes.length} products${failedPushes.length > 0 ? `, ${failedPushes.length} failed` : ''}`,
        status: 'success',
        duration: 5000
      });
    }

    if (failedPushes.length > 0) {
      toast({
        title: 'Some products failed to push',
        description: `${failedPushes.length} products failed to push. Check the console for details.`,
        status: 'error',
        duration: 5000
      });
      console.error('Failed pushes:', failedPushes);
    }
  };

  const handleBulkCategoryModalClose = () => {
    setIsBulkCategoryModalOpen(false);
  };

  // Group selected products by manufacturer
  const getSelectedGroupSummary = () => {
    const groups = {};
    selectedProducts.forEach(product => {
      const manufacturer = product.manufacturer || 'Other';
      groups[manufacturer] = (groups[manufacturer] || 0) + 1;
    });
    return Object.entries(groups).map(([manufacturer, count]) => ({
      manufacturer,
      count
    }));
  };

  const selectedProductDetails = products.filter(p => selectedProducts.includes(p.id));
  const selectedGroups = getSelectedGroupSummary();

  const handleCategoryUpdated = (productId, category) => {
    // Update the products array with the new category
    setProducts(prevProducts =>
      prevProducts.map(product =>
        product.id === productId
          ? {
            ...product,
            kaufland_category: category.title_singular,
            kaufland_category_id: category.id_category,
            kaufland_category_name: category.name
          }
          : product
      )
    );
  };

  const handlePushToKaufland = async (product) => {
    try {
      const response = await fetch(`/wp-json/klcnn/v1/products/${product.id}/push`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': window.klcnnData.nonce
        }
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to push product to Kaufland');
      }

      const data = await response.json();

      toast({
        title: 'Product pushed successfully',
        description: 'The product has been pushed to Kaufland',
        status: 'success',
        duration: 3000
      });

      // Update product sync status
      setProducts(prevProducts =>
        prevProducts.map(p =>
          p.id === product.id
            ? { ...p, kaufland_status: 'pending' }
            : p
        )
      );

    } catch (error) {
      toast({
        title: 'Error pushing product',
        description: error.message,
        status: 'error',
        duration: 3000
      });
    }
  };

  const handleEanUpdated = async (productId, ean) => {
    // Update the products array with the new EAN
    setProducts(prevProducts =>
      prevProducts.map(product =>
        product.id === productId
          ? { ...product, ean }
          : product
      )
    );
  };

  const handleSetManufacturer = (product) => {
    setSelectedProduct(product);
    setIsManufacturerModalOpen(true);
  };

  const handleManufacturerUpdated = async (productId, manufacturer) => {
    try {
      // If we have selected products, update all of them
      if (selectedProducts.length > 0) {
        // Create an array of promises for all updates
        const updatePromises = selectedProducts.map(async (selectedId) => {
          try {
            const response = await fetch(`/wp-json/klcnn/v1/products/${selectedId}/manufacturer`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': window.klcnnData.nonce
              },
              body: JSON.stringify({ manufacturer })
            });

            if (!response.ok) {
              throw new Error(`Failed to update manufacturer for product ${selectedId}`);
            }

            return selectedId;
          } catch (error) {
            console.error(`Error updating product ${selectedId}:`, error);
            throw error;
          }
        });

        // Wait for all updates to complete
        await Promise.all(updatePromises);

        // Update the UI state after all updates are complete
        setProducts(prevProducts =>
          prevProducts.map(product =>
            selectedProducts.includes(product.id)
              ? { ...product, manufacturer }
              : product
          )
        );

        // Show success message for bulk update
        toast({
          title: 'Manufacturer Updated',
          description: `Updated manufacturer for ${selectedProducts.length} products`,
          status: 'success',
          duration: 3000
        });

        // Close the modal but don't clear selection
        setIsManufacturerModalOpen(false);
      } else {
        // Single product update
        const response = await fetch(`/wp-json/klcnn/v1/products/${productId}/manufacturer`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': window.klcnnData.nonce
          },
          body: JSON.stringify({ manufacturer })
        });

        if (!response.ok) {
          throw new Error('Failed to update manufacturer');
        }

        // Update the products array with the new manufacturer
        setProducts(prevProducts =>
          prevProducts.map(product =>
            product.id === productId
              ? { ...product, manufacturer }
              : product
          )
        );

        // Close the modal
        setIsManufacturerModalOpen(false);
      }
    } catch (error) {
      console.error('Error updating manufacturer:', error);
      toast({
        title: 'Error',
        description: 'Failed to update manufacturer: ' + error.message,
        status: 'error',
        duration: 5000
      });
    }
  };

  const handleManageImages = (product) => {
    console.log('Opening image modal for product:', product);
    console.log('Product main image:', product.main_image);
    console.log('Product gallery images:', product.gallery_images);
    setSelectedProduct(product);
    setIsImagesModalOpen(true);
  };

  const handleImagesUpdated = (images) => {
    // Update the products array with the new images
    setProducts(prevProducts =>
      prevProducts.map(product =>
        selectedProducts.includes(product.id)
          ? {
            ...product,
            main_image: images[0] ? {
              id: images[0].id,
              url: images[0].src || images[0].url
            } : null,
            gallery_images: images.slice(1).map(img => ({
              id: img.id,
              url: img.src || img.url
            }))
          }
          : product
      )
    );

    // Show success message
    toast({
      title: 'Images Updated',
      description: 'Product images have been successfully updated',
      status: 'success',
      duration: 3000
    });

    // Close the modal
    setIsImagesModalOpen(false);
  };

  // Add this new helper function to check step completion
  const getStepCompletion = () => {
    if (!selectedProducts.length) return 0;

    const selectedProductsData = products.filter(p => selectedProducts.includes(p.id));

    // Check if all selected products have required fields
    const allHaveCategory = selectedProductsData.every(p => p.kaufland_category);
    const allHaveManufacturer = selectedProductsData.every(p => p.manufacturer);
    const allHaveImages = selectedProductsData.every(p => p.main_image);

    if (!allHaveCategory) return 25;
    if (!allHaveManufacturer) return 50;
    if (!allHaveImages) return 75;
    return 100;
  };

  // Add useEffect to update currentStep whenever products or selection changes
  React.useEffect(() => {
    if (selectedProducts.length > 0) {
      const selectedProductsData = products.filter(p => selectedProducts.includes(p.id));

      // Determine the current required step
      if (!selectedProductsData.every(p => p.kaufland_category)) {
        setCurrentStep(1);
      } else if (!selectedProductsData.every(p => p.manufacturer)) {
        setCurrentStep(2);
      } else if (!selectedProductsData.every(p => p.main_image)) {
        setCurrentStep(3);
      } else {
        setCurrentStep(4);
      }
    }
  }, [products, selectedProducts]);

  // Add this new function to update the cache
  const updateSelectedProductCache = useCallback((product, isSelected) => {
    setSelectedProductsCache(prev => {
      if (isSelected) {
        return { ...prev, [product.id]: product };
      } else {
        const newCache = { ...prev };
        delete newCache[product.id];
        return newCache;
      }
    });
  }, []);

  // Modify the click handler in ProductCard and list view
  const handleProductSelection = (product, isSelected) => {
    setSelectedProducts(prev => {
      if (isSelected) {
        updateSelectedProductCache(product, true);
        return [...prev, product.id];
      } else {
        updateSelectedProductCache(product, false);
        return prev.filter(id => id !== product.id);
      }
    });
  };

  // Modify the clear selection handler
  const clearSelection = () => {
    setSelectedProducts([]);
    setSelectedProductsCache({});
  };

  const ProductCard = ({ product }) => {
    const isSelected = selectedProducts.includes(product.id);

    return (
      <Card
        bg={isSelected ? selectedBg : bgColor}
        borderWidth="1px"
        borderColor={isSelected ? 'blue.400' : borderColor}
        borderRadius="xl"
        overflow="hidden"
        transition="all 0.2s"
        cursor="pointer"
        onClick={(e) => {
          if (e.target.closest('button')) return;
          handleProductSelection(product, !isSelected);
        }}
        _hover={{
          transform: 'translateY(-2px)',
          shadow: 'lg',
          borderColor: isSelected ? 'blue.500' : 'blue.200'
        }}
      >
        <Box position="relative">
          <Image
            src={product.main_image?.url || PLACEHOLDER_IMAGE}
            alt={product.name}
            height="200px"
            width="100%"
            objectFit="cover"
            fallbackSrc={PLACEHOLDER_IMAGE}
          />
          <Checkbox
            position="absolute"
            top={2}
            right={2}
            isChecked={isSelected}
            colorScheme="blue"
            size="lg"
            zIndex={1}
          />
          <Badge
            position="absolute"
            bottom={2}
            right={2}
            colorScheme={
              product.kaufland_status === 'synced' ? 'green' :
                product.kaufland_status === 'pending' ? 'yellow' :
                  product.kaufland_status === 'error' ? 'red' : 'gray'
            }
            variant="solid"
            px={2}
            py={1}
            borderRadius="full"
          >
            {product.kaufland_status === 'synced' ? 'Synced' :
              product.kaufland_status === 'pending' ? 'Pending' :
                product.kaufland_status === 'error' ? 'Error' : 'Not Synced'}
          </Badge>
        </Box>

        <CardBody>
          <VStack align="stretch" spacing={3}>
            <Heading size="sm" noOfLines={2}>
              {product.name}
            </Heading>

            <HStack justify="space-between">
              <Text fontSize="sm" color="gray.500">
                Price: ${product.price}
              </Text>
              <Text fontSize="sm" color="gray.500">
                Stock: {product.stock_quantity}
              </Text>
            </HStack>

            {product.kaufland_category && (
              <Tag size="sm" colorScheme="blue" variant="subtle">
                {product.kaufland_category}
              </Tag>
            )}

            <ButtonGroup size="sm" width="100%" spacing={2}>
              <Tooltip label="Set Category">
                <IconButton
                  icon={<FiTag />}
                  onClick={() => handleSetCategory(product)}
                  variant="ghost"
                  colorScheme="blue"
                />
              </Tooltip>
              <Tooltip label="Manage Images">
                <IconButton
                  icon={<FiImage />}
                  onClick={() => handleManageImages(product)}
                  variant="ghost"
                  colorScheme="purple"
                />
              </Tooltip>
              <Tooltip label="Set Manufacturer">
                <IconButton
                  icon={<FiPackage />}
                  onClick={() => handleSetManufacturer(product)}
                  variant="ghost"
                  colorScheme="green"
                />
              </Tooltip>
              <Tooltip label="Push to Kaufland">
                <IconButton
                  icon={<RepeatIcon />}
                  onClick={() => handlePushToKaufland(product)}
                  variant="ghost"
                  colorScheme="orange"
                />
              </Tooltip>
            </ButtonGroup>
          </VStack>
        </CardBody>
      </Card>
    );
  };

  const handleCategorySelect = (categoryId) => {
    setSelectedCategory(categoryId);
    setPagination(prev => ({ ...prev, currentPage: 1 }));
    categoryMenuDisclosure.onClose();
  };

  const handleCategoryClear = () => {
    setSelectedCategory(null);
    setPagination(prev => ({ ...prev, currentPage: 1 }));
    categoryMenuDisclosure.onClose();
  };

  return (
    <Container maxW="container.xl" py={6}>
      <Stack spacing={6}>
        <Flex justify="space-between" align="center" wrap="wrap" gap={4}>
          <VStack align="start" spacing={1}>
            <Heading size="lg">Products</Heading>
            <Text color="gray.500">
              Manage your WooCommerce products for Kaufland
            </Text>
          </VStack>

          <HStack spacing={4}>
            <ButtonGroup isAttached variant="outline">
              <IconButton
                icon={<FiGrid />}
                aria-label="Grid view"
                onClick={() => setViewMode('grid')}
                colorScheme={viewMode === 'grid' ? 'blue' : 'gray'}
              />
              <IconButton
                icon={<FiList />}
                aria-label="List view"
                onClick={() => setViewMode('list')}
                colorScheme={viewMode === 'list' ? 'blue' : 'gray'}
              />
            </ButtonGroup>

            <Button
              leftIcon={<SettingsIcon />}
              variant="ghost"
              onClick={() => setShowFilters(!showFilters)}
            >
              Filters & Options
            </Button>
          </HStack>
        </Flex>

        <Collapse in={showFilters}>
          <Card variant="outline" mb={6} position="relative" zIndex={2}>
            <CardBody>
              <VStack spacing={4} align="stretch">
                <Text fontWeight="medium" color="gray.600">Filters & Search</Text>
                <SimpleGrid columns={{ base: 1, md: 3 }} spacing={6} position="relative">
                  {/* Search Products */}
                  <Box>
                    <Text mb={2} fontSize="sm" color="gray.600">Search Products</Text>
                    <InputGroup size="md">
                      <InputLeftElement pointerEvents="none">
                        <SearchIcon color="gray.400" />
                      </InputLeftElement>
                      <Input
                        placeholder="Search by name, SKU..."
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        bg="white"
                        _hover={{ borderColor: 'blue.400' }}
                        _focus={{ borderColor: 'blue.500', boxShadow: '0 0 0 1px var(--chakra-colors-blue-500)' }}
                      />
                      {search && (
                        <InputRightElement>
                          <IconButton
                            icon={<CloseIcon />}
                            size="sm"
                            variant="ghost"
                            onClick={() => setSearch('')}
                            aria-label="Clear search"
                          />
                        </InputRightElement>
                      )}
                    </InputGroup>
                  </Box>

                  {/* Category Selection */}
                  <Box position="relative">
                    <Text mb={2} fontSize="sm" color="gray.600">Filter by Category</Text>
                    <Menu
                      isOpen={categoryMenuDisclosure.isOpen}
                      onClose={categoryMenuDisclosure.onClose}
                      onOpen={categoryMenuDisclosure.onOpen}
                      autoSelect={false}
                      placement="bottom-start"
                      closeOnSelect={false}
                    >
                      <MenuButton
                        as={Button}
                        rightIcon={<ChevronDownIcon />}
                        width="100%"
                        isLoading={isCategoriesLoading}
                        colorScheme={selectedCategory ? "blue" : "gray"}
                        variant={selectedCategory ? "solid" : "outline"}
                        onClick={categoryMenuDisclosure.onOpen}
                        bg={selectedCategory ? "blue.500" : "white"}
                        _hover={{
                          bg: selectedCategory ? "blue.600" : "gray.50",
                          borderColor: selectedCategory ? "blue.600" : "blue.400"
                        }}
                      >
                        <HStack spacing={2} justify="space-between">
                          <Text isTruncated>
                            {selectedCategory && categories.length > 0
                              ? categories.find(c => c.id === selectedCategory)?.name || 'Select Category'
                              : 'Select Category'}
                          </Text>
                          {selectedCategory && (
                            <Badge colorScheme="blue" variant="subtle" bg="white">
                              1 selected
                            </Badge>
                          )}
                        </HStack>
                      </MenuButton>
                      <Portal>
                        <MenuList
                          maxH="400px"
                          overflowY="auto"
                          p={3}
                          minW="300px"
                          zIndex={1500}
                          shadow="lg"
                        >
                          <VStack spacing={3} align="stretch">
                            <InputGroup size="sm">
                              <InputLeftElement pointerEvents="none">
                                <SearchIcon color="gray.400" />
                              </InputLeftElement>
                              <Input
                                placeholder="Search categories..."
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                borderRadius="md"
                                onClick={(e) => e.stopPropagation()}
                                _focus={{ borderColor: 'blue.500', boxShadow: '0 0 0 1px var(--chakra-colors-blue-500)' }}
                              />
                              {searchQuery && (
                                <InputRightElement>
                                  <IconButton
                                    icon={<CloseIcon />}
                                    size="xs"
                                    variant="ghost"
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      setSearchQuery('');
                                    }}
                                    aria-label="Clear search"
                                  />
                                </InputRightElement>
                              )}
                            </InputGroup>

                            {selectedCategory && (
                              <HStack>
                                <Tag
                                  size="md"
                                  variant="subtle"
                                  colorScheme="blue"
                                  borderRadius="full"
                                >
                                  <TagLabel>
                                    {categories.find(c => c.id === selectedCategory)?.name}
                                  </TagLabel>
                                  <TagCloseButton
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      handleCategoryClear();
                                    }}
                                  />
                                </Tag>
                              </HStack>
                            )}

                            <Box
                              borderRadius="md"
                              borderWidth="1px"
                              borderColor="gray.200"
                              maxH="300px"
                              overflowY="auto"
                            >
                              <List spacing={0}>
                                {categories
                                  .filter(cat =>
                                    !searchQuery ||
                                    cat.name.toLowerCase().includes(searchQuery.toLowerCase())
                                  )
                                  .map(category => (
                                    <ListItem
                                      key={category.id}
                                      onClick={(e) => {
                                        e.stopPropagation();
                                        handleCategorySelect(category.id);
                                      }}
                                      role="button"
                                      py={2}
                                      px={3}
                                      cursor="pointer"
                                      bg={selectedCategory === category.id ? "blue.50" : "transparent"}
                                      _hover={{
                                        bg: selectedCategory === category.id ? "blue.100" : "gray.50"
                                      }}
                                      transition="all 0.2s"
                                      borderBottomWidth="1px"
                                      borderBottomColor="gray.100"
                                      display="flex"
                                      alignItems="center"
                                      justifyContent="space-between"
                                    >
                                      <HStack spacing={3}>
                                        <Text>{category.name}</Text>
                                        <Badge colorScheme="gray" variant="subtle">
                                          {category.count || 0}
                                        </Badge>
                                      </HStack>
                                      {selectedCategory === category.id && (
                                        <CheckIcon color="blue.500" />
                                      )}
                                    </ListItem>
                                  ))}
                              </List>
                            </Box>
                          </VStack>
                        </MenuList>
                      </Portal>
                    </Menu>
                  </Box>

                  {/* Items per Page */}
                  <Box>
                    <Text mb={2} fontSize="sm" color="gray.600">Items per Page</Text>
                    <Select
                      value={perPage}
                      onChange={(e) => setPerPage(Number(e.target.value))}
                      bg="white"
                      _hover={{ borderColor: 'blue.400' }}
                      _focus={{ borderColor: 'blue.500', boxShadow: '0 0 0 1px var(--chakra-colors-blue-500)' }}
                    >
                      <option value="10">10 items</option>
                      <option value="25">25 items</option>
                      <option value="50">50 items</option>
                      <option value="100">100 items</option>
                    </Select>
                  </Box>
                </SimpleGrid>

                {/* Active Filters */}
                {(search || selectedCategory) && (
                  <HStack spacing={4} pt={2}>
                    <Text fontSize="sm" color="gray.500">Active Filters:</Text>
                    {search && (
                      <Tag size="md" variant="subtle" colorScheme="blue">
                        <TagLabel>Search: {search}</TagLabel>
                        <TagCloseButton onClick={() => setSearch('')} />
                      </Tag>
                    )}
                    {selectedCategory && (
                      <Tag size="md" variant="subtle" colorScheme="blue">
                        <TagLabel>
                          Category: {categories.find(c => c.id === selectedCategory)?.name}
                        </TagLabel>
                        <TagCloseButton onClick={handleCategoryClear} />
                      </Tag>
                    )}
                  </HStack>
                )}
              </VStack>
            </CardBody>
          </Card>
        </Collapse>

        {selectedProducts.length > 0 && (
          <Box
            position="fixed"
            bottom={0}
            left={0}
            right={0}
            zIndex={1000}
            py={2}
            px={4}
            bg="white"
            boxShadow="0 -2px 8px rgba(0,0,0,0.1)"
            borderTopWidth="1px"
            borderColor="blue.200"
            ml={{ base: 0, md: '160px' }}
          >
            <Container maxW="container.xl">
              <VStack spacing={3}>
                <Grid templateColumns="auto 1fr" gap={6} alignItems="center" width="100%">
                  <VStack align="start" spacing={1} minW="200px">
                    <HStack>
                      <Text fontSize="md" fontWeight="bold">
                        {selectedProducts.length} products selected
                      </Text>
                      <Button
                        size="sm"
                        variant="ghost"
                        colorScheme="gray"
                        leftIcon={<CloseIcon />}
                        onClick={clearSelection}
                      >
                        Clear
                      </Button>
                    </HStack>
                    <Text fontSize="sm" color="gray.600">
                      Complete these steps to sync products
                    </Text>
                  </VStack>

                  <VStack spacing={3} align="stretch">
                    <HStack spacing={4} justify="space-between">
                      <ButtonGroup size="sm" spacing={4}>
                        {/* Step 1 */}
                        <Box position="relative">
                          <HStack
                            spacing={2}
                            bg={currentStep === 1 ? "blue.50" : "gray.50"}
                            py={1.5}
                            px={2}
                            borderRadius="lg"
                            borderWidth="1px"
                            borderColor={currentStep === 1 ? "blue.200" : "gray.200"}
                            transition="all 0.2s"
                            opacity={currentStep === 1 ? 1 : 0.7}
                            _hover={{ opacity: 1 }}
                          >
                            <Circle
                              size="28px"
                              bg={currentStep === 1 ? "blue.500" :
                                (selectedProduct?.kaufland_category ? "green.500" : "gray.300")}
                              color="white"
                              fontSize="sm"
                              fontWeight="bold"
                              animation={currentStep === 1 ? "pulse 2s infinite" : "none"}
                            >
                              1
                            </Circle>
                            <Tooltip label="First, set the category for selected products" hasArrow>
                              <Button
                                leftIcon={<FiTag />}
                                variant={currentStep === 1 ? "solid" : "ghost"}
                                colorScheme="blue"
                                size="sm"
                                onClick={() => setIsBulkCategoryModalOpen(true)}
                                tabIndex={currentStep === 1 ? 0 : -1}
                              >
                                Set Category
                              </Button>
                            </Tooltip>
                            {selectedProduct?.kaufland_category && <CheckIcon color="green.500" />}
                          </HStack>
                        </Box>

                        {/* Step 2 */}
                        <Box position="relative">
                          <HStack
                            spacing={2}
                            bg={currentStep === 2 ? "green.50" : "gray.50"}
                            py={1.5}
                            px={2}
                            borderRadius="lg"
                            borderWidth="1px"
                            borderColor={currentStep === 2 ? "green.200" : "gray.200"}
                            transition="all 0.2s"
                            opacity={currentStep === 2 ? 1 : 0.7}
                            _hover={{ opacity: 1 }}
                          >
                            <Circle
                              size="28px"
                              bg={currentStep === 2 ? "green.500" :
                                (selectedProduct?.manufacturer ? "green.500" : "gray.300")}
                              color="white"
                              fontSize="sm"
                              fontWeight="bold"
                              animation={currentStep === 2 ? "pulse 2s infinite" : "none"}
                            >
                              2
                            </Circle>
                            <Tooltip label="Next, set the manufacturer" hasArrow>
                              <Button
                                leftIcon={<FiPackage />}
                                variant={currentStep === 2 ? "solid" : "ghost"}
                                colorScheme="green"
                                size="sm"
                                onClick={() => {
                                  const firstSelectedProduct = products.find(p => selectedProducts.includes(p.id));
                                  setSelectedProduct(firstSelectedProduct);
                                  setIsManufacturerModalOpen(true);
                                }}
                                tabIndex={currentStep === 2 ? 0 : -1}
                              >
                                Set Manufacturer
                              </Button>
                            </Tooltip>
                            {selectedProduct?.manufacturer && <CheckIcon color="green.500" />}
                          </HStack>
                        </Box>

                        {/* Step 3 */}
                        <Box position="relative">
                          <Tooltip
                            label={
                              <VStack spacing={1} p={1}>
                                <Text>Optimize your product images (Optional)</Text>
                                <Text fontSize="xs" color="gray.300">
                                  This step is optional but recommended. Your images will be:
                                  • Optimized with white background
                                  • Properly sized for Kaufland
                                  • Compressed if needed
                                </Text>
                                {currentStep === 3 && (
                                  <Text fontSize="xs" color="blue.200" fontWeight="bold">
                                    ↓ Click to manage images or proceed to next step
                                  </Text>
                                )}
                              </VStack>
                            }
                            hasArrow
                            placement="top"
                            openDelay={300}
                            bg="gray.700"
                          >
                            <Button
                              leftIcon={<FiImage />}
                              variant={currentStep === 3 ? "solid" : "ghost"}
                              colorScheme={currentStep === 3 ? "blue" : "gray"}
                              size="sm"
                              onClick={() => {
                                const selectedProductsDetails = products.filter(p => selectedProducts.includes(p.id));
                                setSelectedProduct(selectedProductsDetails);
                                setIsImagesModalOpen(true);
                              }}
                              tabIndex={currentStep === 3 ? 0 : -1}
                              position="relative"
                              _after={currentStep === 3 ? {
                                content: '""',
                                position: "absolute",
                                bottom: "-10px",
                                left: "50%",
                                transform: "translateX(-50%)",
                                width: "4px",
                                height: "4px",
                                borderRadius: "full",
                                bg: "blue.500",
                                animation: "pulse 2s infinite"
                              } : {}}
                            >
                              Manage Images
                              <Badge
                                ml={2}
                                colorScheme={currentStep === 3 ? "blue" : "gray"}
                                variant="subtle"
                                fontSize="xs"
                              >
                                Optional
                              </Badge>
                            </Button>
                          </Tooltip>
                          {selectedProduct?.main_image && <CheckIcon color="green.500" />}

                          {/* Add animation keyframes */}
                          <style>
                            {`
                              @keyframes pulse {
                                0% { transform: translateX(-50%) scale(1); opacity: 1; }
                                50% { transform: translateX(-50%) scale(1.5); opacity: 0.5; }
                                100% { transform: translateX(-50%) scale(1); opacity: 1; }
                              }
                            `}
                          </style>

                          {/* Add a small info alert when step 3 is active */}
                          {currentStep === 3 && (
                            <Box mt={2} width="100%">
                              <Alert status="info" variant="left-accent" size="sm" borderRadius="md">
                                <AlertIcon />
                                <VStack align="start" spacing={0}>
                                  <Text fontSize="sm" fontWeight="medium">
                                    Optional Step
                                  </Text>
                                  <Text fontSize="xs">
                                    You can optimize your images now or proceed to the next step
                                  </Text>
                                </VStack>
                              </Alert>
                            </Box>
                          )}
                        </Box>

                        {/* Final Step */}
                        <Box position="relative">
                          <HStack
                            spacing={2}
                            bg={currentStep === 4 ? "orange.100" : "gray.50"}
                            py={1.5}
                            px={2}
                            borderRadius="lg"
                            borderWidth="2px"
                            borderColor={currentStep === 4 ? "orange.400" : "gray.200"}
                            transition="all 0.2s"
                            opacity={currentStep === 4 ? 1 : 0.7}
                            _hover={{
                              opacity: 1,
                              transform: currentStep === 4 ? "translateY(-2px)" : "none",
                              shadow: currentStep === 4 ? "md" : "none"
                            }}
                          >
                            <Circle
                              size="28px"
                              bg={currentStep === 4 ? "orange.500" :
                                (getStepCompletion() === 100 ? "green.500" : "gray.300")}
                              color="white"
                              fontSize="sm"
                              fontWeight="bold"
                              animation={currentStep === 4 ? "pulse 2s infinite" : "none"}
                            >
                              ✓
                            </Circle>
                            <Tooltip label="Finally, sync products to Kaufland" hasArrow>
                              <Button
                                leftIcon={<RepeatIcon />}
                                variant={currentStep === 4 ? "solid" : "ghost"}
                                colorScheme="orange"
                                size="sm"
                                onClick={handleBulkPushToKaufland}
                                isDisabled={getStepCompletion() !== 100}
                                tabIndex={currentStep === 4 ? 0 : -1}
                              >
                                Sync to Kaufland
                              </Button>
                            </Tooltip>
                          </HStack>
                        </Box>
                      </ButtonGroup>
                    </HStack>

                    <Progress
                      value={getStepCompletion()}
                      size="sm"
                      colorScheme="blue"
                      borderRadius="full"
                      hasStripe
                      isAnimated
                    />
                  </VStack>
                </Grid>
              </VStack>

              <style>
                {`
                  @keyframes pulse {
                    0% {
                      box-shadow: 0 0 0 0 rgba(66, 153, 225, 0.4);
                    }
                    70% {
                      box-shadow: 0 0 0 8px rgba(66, 153, 225, 0);
                    }
                    100% {
                      box-shadow: 0 0 0 0 rgba(66, 153, 225, 0);
                    }
                  }
                `}
              </style>
            </Container>
          </Box>
        )}

        {/* Add padding at the bottom when bulk action bar is visible */}
        {selectedProducts.length > 0 && <Box h="140px" />}

        {isLoading ? (
          <Box textAlign="center" py={12}>
            <Spinner size="xl" color="blue.500" thickness="4px" />
          </Box>
        ) : viewMode === 'grid' ? (
          <SimpleGrid
            columns={{ base: 1, sm: 2, md: 3, lg: 4 }}
            spacing={6}
          >
            {products.map(product => (
              <ProductCard key={product.id} product={product} />
            ))}
          </SimpleGrid>
        ) : (
          <Card variant="outline">
            <Table>
              <Thead>
                <Tr>
                  <Th width="40px">
                    <Checkbox
                      isChecked={selectedProducts.length === products.length}
                      isIndeterminate={selectedProducts.length > 0 && selectedProducts.length < products.length}
                      onChange={(e) => {
                        if (e.target.checked) {
                          // Add all current page products to cache and selection
                          products.forEach(product => {
                            updateSelectedProductCache(product, true);
                          });
                          setSelectedProducts(prev => [...prev, ...products.map(p => p.id)]);
                        } else {
                          // Remove all current page products from cache and selection
                          products.forEach(product => {
                            updateSelectedProductCache(product, false);
                          });
                          setSelectedProducts(prev =>
                            prev.filter(id => !products.find(p => p.id === id))
                          );
                        }
                      }}
                    />
                  </Th>
                  <Th>Product</Th>
                  <Th>Price / Stock</Th>
                  <Th>Status</Th>
                  <Th>Category</Th>
                  <Th>Actions</Th>
                </Tr>
              </Thead>
              <Tbody>
                {products.map(product => (
                  <Tr
                    key={product.id}
                    bg={selectedProducts.includes(product.id) ? selectedBg : 'transparent'}
                    _hover={{ bg: hoverBg }}
                    cursor="pointer"
                    onClick={(e) => {
                      if (e.target.closest('button') || e.target.tagName === 'INPUT') return;
                      handleProductSelection(product, selectedProducts.includes(product.id));
                    }}
                  >
                    <Td>
                      <Checkbox
                        isChecked={selectedProducts.includes(product.id)}
                        onChange={(e) => {
                          handleProductSelection(product, e.target.checked);
                        }}
                      />
                    </Td>
                    <Td>
                      <HStack>
                        <Image
                          src={product.main_image?.url || PLACEHOLDER_IMAGE}
                          alt={product.name}
                          boxSize="40px"
                          objectFit="cover"
                          borderRadius="md"
                          fallbackSrc={PLACEHOLDER_IMAGE}
                        />
                        <Text>{product.name}</Text>
                      </HStack>
                    </Td>
                    <Td>${product.price} / {product.stock_quantity}</Td>
                    <Td>{getSyncStatusBadge(product.kaufland_status)}</Td>
                    <Td>
                      {product.kaufland_category ? (
                        <Tag colorScheme="blue" size="sm">
                          {product.kaufland_category}
                        </Tag>
                      ) : (
                        <Text color="gray.500">No Category</Text>
                      )}
                    </Td>
                    <Td>
                      <ButtonGroup size="sm" spacing={2}>
                        <Tooltip label="Set Category">
                          <IconButton
                            icon={<FiTag />}
                            onClick={() => handleSetCategory(product)}
                            variant="ghost"
                            colorScheme="blue"
                          />
                        </Tooltip>
                        <Tooltip label="Manage Images">
                          <IconButton
                            icon={<FiImage />}
                            onClick={() => handleManageImages(product)}
                            variant="ghost"
                            colorScheme="purple"
                          />
                        </Tooltip>
                        <Tooltip label="Push to Kaufland">
                          <IconButton
                            icon={<RepeatIcon />}
                            onClick={() => handlePushToKaufland(product)}
                            variant="ghost"
                            colorScheme="orange"
                          />
                        </Tooltip>
                      </ButtonGroup>
                    </Td>
                  </Tr>
                ))}
              </Tbody>
            </Table>
          </Card>
        )}

        <Flex justify="space-between" align="center" mt={4}>
          <Text color="gray.500">
            Showing {products.length} of {pagination.totalItems} products
          </Text>
          <Pagination
            currentPage={pagination.currentPage}
            totalPages={pagination.totalPages}
            onPageChange={(page) => setPagination({ ...pagination, currentPage: page })}
          />
        </Flex>
      </Stack>

      <CategoryModal
        isOpen={isCategoryModalOpen}
        onClose={handleCategoryModalClose}
        product={selectedProduct}
        onCategoryUpdated={handleCategoryUpdated}
      />

      <BulkCategoryModal
        isOpen={isBulkCategoryModalOpen}
        onClose={() => setIsBulkCategoryModalOpen(false)}
        selectedProducts={selectedProducts}
        products={products}
        onCategoriesUpdated={(productId, category) => {
          // Update the products array with the new category
          setProducts(prevProducts =>
            prevProducts.map(product =>
              product.id === productId
                ? {
                  ...product,
                  kaufland_category: category.title_singular,
                  kaufland_category_id: category.id_category,
                  kaufland_category_name: category.name
                }
                : product
            )
          );
        }}
      />

      <BulkEanModal
        isOpen={isBulkEanModalOpen}
        onClose={() => setIsBulkEanModalOpen(false)}
        products={selectedProductsForEan}
        onEansUpdated={(updates) => {
          // Update the products array with new EANs
          setProducts(prevProducts =>
            prevProducts.map(product => {
              const update = updates.find(u => u.id === product.id);
              return update ? { ...product, ean: update.ean } : product;
            })
          );
        }}
        onComplete={pushSelectedProductsToKaufland}
      />

      <EanModal
        isOpen={isEanModalOpen}
        onClose={() => setIsEanModalOpen(false)}
        product={selectedProduct}
        onEanUpdated={handleEanUpdated}
      />

      <ManufacturerModal
        isOpen={isManufacturerModalOpen}
        onClose={() => setIsManufacturerModalOpen(false)}
        product={selectedProduct}
        onManufacturerUpdated={handleManufacturerUpdated}
      />

      <ProductImagesModal
        isOpen={isImagesModalOpen}
        onClose={() => {
          setIsImagesModalOpen(false);
          setSelectedProduct(null);
        }}
        products={Array.isArray(selectedProduct) ? selectedProduct : [selectedProduct].filter(Boolean)}
        onImagesUpdated={handleImagesUpdated}
      />
    </Container>
  );
};

export default Products;