// import React, { useState, useEffect } from 'react'

// // ** MUI Imports
// import {
//   Dialog,
//   DialogTitle,
//   DialogContent,
//   DialogActions,
//   Box,
//   Typography,
//   Button,
//   IconButton,
//   TextField,
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   Paper,
//   CircularProgress,
//   Chip
// } from '@mui/material'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// // ** Redux
// import { useDispatch } from 'react-redux'
// import { addToCart, updateQuantity, removeFromCart } from 'src/store/pages/pos/cartSlice'

// // ** Image Utils
// const BASE_URL = 'http://192.168.1.5:8001'

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''
//   if (path.startsWith('http://') || path.startsWith('https://')) return path
//   if (path.startsWith('blob:') || path.startsWith('data:')) return path
//   const cleanPath = path.startsWith('/') ? path : `/${path}`
//   return `${BASE_URL}${cleanPath}`
// }

// const getVariationImage = (variation: any): string => {
//   if (!variation) return ''
//   const images = variation.variationImages || []
//   if (images.length === 0) return ''
//   const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
//   return imageUrl ? getFullImageUrl(imageUrl) : ''
// }

// interface Variation {
//   uid: string
//   sku: string
//   mrp: number
//   stockQty: number
//   quantity: number
//   unit: string
//   calAmount: number
//   finalAmount: number
//   variationImages: any[]
//   attributes: any[]
// }

// interface Product {
//   uid: string
//   name: string
//   description?: string
//   variations: Variation[]
// }

// interface ProductDialogProps {
//   open: boolean
//   onClose: () => void
//   product: Product | null
//   editItem?: any
//   isEdit?: boolean
// }

// // Image component with authentication
// const AuthImageComponent: React.FC<{ src: string; alt: string; style?: React.CSSProperties }> = ({ src, alt, style }) => {
//   const [imageSrc, setImageSrc] = useState<string>('')
//   const [loading, setLoading] = useState(true)

//   useEffect(() => {
//     if (!src) {
//       setImageSrc('')
//       setLoading(false)
//       return
//     }

//     const fetchImage = async () => {
//       try {
//         const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
//         const response = await axios.get(src, {
//           responseType: 'blob',
//           headers: {
//             'Authorization': `Bearer ${token}`
//           }
//         })

//         const blob = response.data
//         const url = URL.createObjectURL(blob)
//         setImageSrc(url)
//         setLoading(false)
//       } catch (error) {
//         console.error('Error loading image:', error)
//         setImageSrc(src)
//         setLoading(false)
//       }
//     }

//     fetchImage()

//     return () => {
//       if (imageSrc && imageSrc.startsWith('blob:')) {
//         URL.revokeObjectURL(imageSrc)
//       }
//     }
//   }, [src])

//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <CircularProgress size={24} />
//       </Box>
//     )
//   }

//   return (
//     <img
//       src={imageSrc || 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"%3E%3Crect width="200" height="200" fill="%23f0f0f0"/%3E%3Ctext x="50" y="115" font-family="Arial" font-size="20" fill="%23999"%3ENo Image%3C/text%3E%3C/svg%3E'}
//       alt={alt}
//       style={style}
//       onError={(e) => {
//         e.currentTarget.src = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"%3E%3Crect width="200" height="200" fill="%23f0f0f0"/%3E%3Ctext x="50" y="115" font-family="Arial" font-size="20" fill="%23999"%3ENo Image%3C/text%3E%3C/svg%3E'
//       }}
//     />
//   )
// }

// const ProductDialog: React.FC<ProductDialogProps> = ({ 
//   open, 
//   onClose, 
//   product, 
//   editItem = null,
//   isEdit = false 
// }) => {
//   const dispatch = useDispatch()
//   const [loading, setLoading] = useState(false)
//   const [selectedVariation, setSelectedVariation] = useState<Variation | null>(null)
//   const [quantity, setQuantity] = useState<number>(1)
//   const [orderItemUid, setOrderItemUid] = useState<string>('')
//   const [posUid, setPosUid] = useState<string>('')
//   const [totalAmount, setTotalAmount] = useState<number>(0)

//   // Initialize with edit data if in edit mode
//   useEffect(() => {
//     if (isEdit && editItem) {
//       if (product) {
//         const variation = product.variations.find(v => v.uid === editItem.id)
//         if (variation) {
//           setSelectedVariation(variation)
//         }
//       }
//       setQuantity(editItem.quantity || 1)
//       setOrderItemUid(editItem.orderItemUid || '')
//       setPosUid(editItem.posUid || '')
//       console.log('Edit Mode - orderItemUid:', editItem.orderItemUid, 'posUid:', editItem.posUid)
//     } else if (product && product.variations.length > 0) {
//       setSelectedVariation(product.variations[0])
//       setQuantity(1)
//       setOrderItemUid('')
//       setPosUid('')
//     }
//   }, [product, editItem, isEdit, open])

//   // Calculate total amount when quantity or selected variation changes
//   useEffect(() => {
//     if (selectedVariation) {
//       setTotalAmount(selectedVariation.mrp * quantity)
//     }
//   }, [selectedVariation, quantity])

//   // Reset when dialog closes
//   useEffect(() => {
//     if (!open) {
//       setSelectedVariation(null)
//       setQuantity(1)
//       setOrderItemUid('')
//       setPosUid('')
//       setTotalAmount(0)
//     }
//   }, [open])

//   const handleQuantityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const val = parseInt(e.target.value)
//     if (!isNaN(val) && val > 0) {
//       setQuantity(val)
//     }
//   }

//   const handleIncrement = () => {
//     if (selectedVariation && quantity < selectedVariation.stockQty) {
//       setQuantity(prev => prev + 1)
//     }
//   }

//   const handleDecrement = () => {
//     if (quantity > 1) {
//       setQuantity(prev => prev - 1)
//     }
//   }

//   // Fetch order details to get the actual item UID
//   const fetchOrderDetails = async (orderUid: string): Promise<{ itemUid: string, posUid: string }> => {
//     try {
//       const response = await axios.get(`${endpoints.pos.posOrder.get}${orderUid}`)
//       console.log('Order details response:', response.data)
      
//       const orderData = response.data?.content?.result || response.data?.content || response.data
      
//       // Extract item UID from the order details
//       let itemUid = orderUid
//       let posUid = orderUid
      
//       if (orderData) {
//         // Get the order UID
//         posUid = orderData.uid || orderData.orderUid || orderUid
        
//         // Get the item UID - check various possible locations
//         if (orderData.items && orderData.items.length > 0) {
//           itemUid = orderData.items[0].uid || orderData.items[0].itemUid || posUid
//         } else if (orderData.itemUid) {
//           itemUid = orderData.itemUid
//         } else if (orderData.variationUid) {
//           itemUid = orderData.variationUid
//         }
//       }
      
//       console.log('Fetched - posUid:', posUid, 'itemUid:', itemUid)
//       return { itemUid, posUid }
//     } catch (error) {
//       console.error('Error fetching order details:', error)
//       return { itemUid: orderUid, posUid: orderUid }
//     }
//   }

//   const handleAddToOrder = async () => {
//     if (!selectedVariation) {
//       toast.error('Please select a variation', { style: { zIndex: 999999 } })
//       return
//     }

//     setLoading(true)

//     try {
//       if (isEdit && editItem) {
//         // UPDATE MODE - Call updateQuantity API
//         if (!orderItemUid) {
//           toast.error('Order item UID is missing. Please try again.', { style: { zIndex: 999999 } })
//           setLoading(false)
//           return
//         }
//         const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${orderItemUid}?quantity=${quantity}`
//         console.log('Update URL:', updateUrl)
//         await axios.put(updateUrl)
        
//         // Update Redux
//         dispatch(updateQuantity({ 
//           id: selectedVariation.uid, 
//           quantity: quantity 
//         }))
        
//         toast.success('Item updated successfully!', { style: { zIndex: 999999 } })
//         onClose()
//       } else {
//         // ADD MODE - Call create order API
//         const payload = {
//           items: [{
//             variationUid: selectedVariation.uid,
//             quantity: quantity
//           }]
//         }
        
//         const response = await axios.post(endpoints.pos.posOrder.create, payload)
//         console.log('Create Order Response:', response.data)
        
//         const orderData = response.data
        
//         if (orderData) {
//           // Get the order UID from the response
//           const orderUid = orderData.uid || orderData.orderUid || ''
          
//           // Fetch order details to get the actual item UID
//           const { itemUid, posUid: fetchedPosUid } = await fetchOrderDetails(orderUid)
          
//           console.log('Order created - posUid:', fetchedPosUid, 'itemUid:', itemUid)
          
//           // Add to Redux with order info
//           dispatch(addToCart({
//             id: selectedVariation.uid,
//             productUid: product?.uid || '',
//             name: product?.name || '',
//             price: selectedVariation.mrp,
//             quantity: quantity,
//             image: getVariationImage(selectedVariation),
//             variation: selectedVariation,
//             orderItemUid: itemUid,
//             posUid: fetchedPosUid,
//             stockQty: selectedVariation.stockQty || 0
//           }))
          
//           toast.success('Item added to order!', { style: { zIndex: 999999 } })
//           onClose()
//         }
//       }
//     } catch (error: any) {
//       console.error('Error:', error)
//       toast.error(error?.response?.data?.message || 'Failed to process item', { 
//         style: { zIndex: 999999 } 
//       })
//     } finally {
//       setLoading(false)
//     }
//   }

//   if (!product) return null

//   // Get price range for display
//   const prices = product.variations.map(v => v.mrp)
//   const minPrice = Math.min(...prices)
//   const maxPrice = Math.max(...prices)
//   const priceDisplay = minPrice === maxPrice ? `$${minPrice.toFixed(2)}` : `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`

//   // Get selected variation image
//   const selectedImage = selectedVariation ? getVariationImage(selectedVariation) : ''

//   return (
//     <Dialog 
//       open={open} 
//       onClose={onClose} 
//       maxWidth="md" 
//       fullWidth
//       PaperProps={{
//         sx: { borderRadius: 2, zIndex: 999999 }
//       }}
//     >
//       <DialogTitle sx={{ 
//         display: 'flex', 
//         justifyContent: 'space-between', 
//         alignItems: 'center',
//         borderBottom: '1px solid',
//         borderColor: 'divider',
//         pb: 2
//       }}>
//         <Box>
//           <Typography variant="h6">{product.name}</Typography>
//           <Typography variant="body2" color="text.secondary">
//             {isEdit ? 'Edit Item' : 'Add to Order'}
//           </Typography>
//         </Box>
//         <IconButton onClick={onClose}>
//           <Icon icon="tabler:x" />
//         </IconButton>
//       </DialogTitle>

//       <DialogContent sx={{ pt: 3 }}>
//         {/* Product Image and Description */}
//         <Box sx={{ display: 'flex', gap: 3, mb: 3 }}>
//           <Box
//             sx={{
//               width: 120,
//               height: 120,
//               borderRadius: 2,
//               overflow: 'hidden',
//               flexShrink: 0,
//               bgcolor: 'grey.100',
//               display: 'flex',
//               alignItems: 'center',
//               justifyContent: 'center'
//             }}
//           >
//             {selectedImage ? (
//               <AuthImageComponent
//                 src={selectedImage}
//                 alt={product.name}
//                 style={{
//                   width: '100%',
//                   height: '100%',
//                   objectFit: 'cover'
//                 }}
//               />
//             ) : (
//               <Typography variant="caption" color="text.secondary">No Image</Typography>
//             )}
//           </Box>
//           <Box sx={{ flex: 1 }}>
//             <Typography variant="body2" color="text.secondary">
//               {product.description || 'No description available'}
//             </Typography>
//             <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1 }}>
//               Price: {priceDisplay}
//             </Typography>
//           </Box>
//         </Box>

//         {/* Variations Table */}
//         <Typography variant="subtitle2" sx={{ mb: 2 }}>
//           Select Variation
//         </Typography>
//         <TableContainer component={Paper} sx={{ maxHeight: 300 }}>
//           <Table size="small" stickyHeader>
//             <TableHead>
//               <TableRow>
//                 <TableCell>SKU</TableCell>
//                 <TableCell>Image</TableCell>
//                 <TableCell>Stock</TableCell>
//                 <TableCell>Amount</TableCell>
//                 <TableCell>Qty</TableCell>
//                 <TableCell>Final</TableCell>
//                 <TableCell>Attributes</TableCell>
//                 <TableCell>Select</TableCell>
//               </TableRow>
//             </TableHead>
//             <TableBody>
//               {product.variations.map((variation) => {
//                 const imageUrl = getVariationImage(variation)
//                 const isSelected = selectedVariation?.uid === variation.uid
//                 const attrText = variation.attributes?.map(a => `${a.attributeName}: ${a.value}`).join(' | ') || ''
//                 const dialogQuantity = isSelected ? quantity : 0
//                 const finalAmount = variation.mrp * dialogQuantity
                
//                 return (
//                   <TableRow 
//                     key={variation.uid}
//                     selected={isSelected}
//                     sx={{ 
//                       cursor: 'pointer',
//                       '&:hover': { bgcolor: 'action.hover' },
//                       bgcolor: isSelected ? 'primary.light' : 'inherit'
//                     }}
//                     onClick={() => {
//                       setSelectedVariation(variation)
//                     }}
//                   >
//                     <TableCell>
//                       <Typography variant="body2" fontWeight={500}>
//                         {variation.sku || 'N/A'}
//                       </Typography>
//                     </TableCell>
//                     <TableCell>
//                       <Box
//                         sx={{
//                           width: 40,
//                           height: 40,
//                           borderRadius: 1,
//                           overflow: 'hidden',
//                           display: 'flex',
//                           alignItems: 'center',
//                           justifyContent: 'center',
//                           bgcolor: 'grey.100'
//                         }}
//                       >
//                         {imageUrl ? (
//                           <AuthImageComponent
//                             src={imageUrl}
//                             alt=""
//                             style={{
//                               width: '100%',
//                               height: '100%',
//                               objectFit: 'cover'
//                             }}
//                           />
//                         ) : (
//                           <Typography variant="caption" color="text.secondary">N/A</Typography>
//                         )}
//                       </Box>
//                     </TableCell>
//                     <TableCell>{variation.stockQty || 0}</TableCell>
//                     <TableCell>${variation.mrp.toFixed(2)}</TableCell>
//                     <TableCell>{isSelected ? quantity : 0}</TableCell>
//                     <TableCell>${finalAmount.toFixed(2)}</TableCell>
//                     <TableCell>
//                       <Typography variant="caption" color="text.secondary">
//                         {attrText}
//                       </Typography>
//                     </TableCell>
//                     <TableCell>
//                       {isSelected && (
//                         <Chip 
//                           label="Selected" 
//                           size="small" 
//                           color="primary" 
//                           variant="filled"
//                         />
//                       )}
//                     </TableCell>
//                   </TableRow>
//                 )
//               })}
//             </TableBody>
//           </Table>
//         </TableContainer>

//         {/* Quantity Selector */}
//         {selectedVariation && (
//           <Box sx={{ mt: 3, display: 'flex', alignItems: 'center', gap: 3, flexWrap: 'wrap' }}>
//             <Typography variant="subtitle2">Quantity:</Typography>
//             <Box sx={{ display: 'flex', alignItems: 'center' }}>
//               <IconButton 
//                 size="small" 
//                 onClick={handleDecrement}
//                 disabled={quantity <= 1}
//               >
//                 <Icon icon="tabler:minus" />
//               </IconButton>
//               <TextField
//                 type="number"
//                 value={quantity}
//                 onChange={handleQuantityChange}
//                 inputProps={{ 
//                   style: { textAlign: 'center', width: 60 },
//                   min: 1,
//                   max: selectedVariation.stockQty || 999
//                 }}
//                 size="small"
//               />
//               <IconButton 
//                 size="small" 
//                 onClick={handleIncrement}
//                 disabled={selectedVariation.stockQty ? quantity >= selectedVariation.stockQty : false}
//               >
//                 <Icon icon="tabler:plus" />
//               </IconButton>
//             </Box>
//             {selectedVariation.stockQty && (
//               <Typography variant="caption" color="text.secondary">
//                 Stock: {selectedVariation.stockQty}
//               </Typography>
//             )}
//             <Typography variant="body2" fontWeight={600} color="primary.main">
//               Total: ${totalAmount.toFixed(2)}
//             </Typography>
//           </Box>
//         )}
//       </DialogContent>

//       <DialogActions sx={{ p: 3, gap: 2, borderTop: '1px solid', borderColor: 'divider' }}>
//         <Button variant="outlined" onClick={onClose} disabled={loading}>
//           Cancel
//         </Button>
//         <Button
//           variant="contained"
//           onClick={handleAddToOrder}
//           disabled={!selectedVariation || loading}
//           startIcon={loading ? <CircularProgress size={16} color="inherit" /> : null}
//         >
//           {loading ? 'Processing...' : isEdit ? 'Update Item' : 'Add Item'}
//         </Button>
//       </DialogActions>
//     </Dialog>
//   )
// }

// export default ProductDialog


// new ////////////////////
// import React, { useState, useEffect } from 'react'

// // ** MUI Imports
// import {
//   Dialog,
//   DialogTitle,
//   DialogContent,
//   DialogActions,
//   Box,
//   Typography,
//   Button,
//   IconButton,
//   TextField,
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   Paper,
//   CircularProgress,
//   Chip
// } from '@mui/material'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// // ** Redux
// import { useDispatch } from 'react-redux'
// import { addToCart, updateQuantity, removeFromCart } from 'src/store/pages/pos/cartSlice'

// // // ** Image Utils
// // const BASE_URL = 'http://192.168.1.5:8001'

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''
//   if (path.startsWith('http://') || path.startsWith('https://')) return path
//   if (path.startsWith('blob:') || path.startsWith('data:')) return path
//   const cleanPath = path.startsWith('/') ? path : `/${path}`
//   return `${cleanPath}`
// }

// const getVariationImage = (variation: any): string => {
//   if (!variation) return ''
//   const images = variation.variationImages || []
//   if (images.length === 0) return ''
//   const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
//   return imageUrl ? getFullImageUrl(imageUrl) : ''
// }

// interface Variation {
//   uid: string
//   sku: string
//   mrp: number
//   stockQty: number
//   quantity: number
//   unit: string
//   calAmount: number
//   finalAmount: number
//   variationImages: any[]
//   attributes: any[]
// }

// interface Product {
//   uid: string
//   name: string
//   description?: string
//   variations: Variation[]
// }

// interface ProductDialogProps {
//   open: boolean
//   onClose: () => void
//   product: Product | null
//   editItem?: any
//   isEdit?: boolean
// }

// // Image component with authentication
// const AuthImageComponent: React.FC<{ src: string; alt: string; style?: React.CSSProperties }> = ({ src, alt, style }) => {
//   const [imageSrc, setImageSrc] = useState<string>('')
//   const [loading, setLoading] = useState(true)

//   useEffect(() => {
//     if (!src) {
//       setImageSrc('/images/placeholder.png')
//       setLoading(false)
//       return
//     }

//     const fetchImage = async () => {
//       try {
//         const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
//         const response = await axios.get(src, {
//           responseType: 'blob',
//           headers: {
//             'Authorization': `Bearer ${token}`
//           }
//         })

//         const blob = response.data
//         const url = URL.createObjectURL(blob)
//         setImageSrc(url)
//         setLoading(false)
//       } catch (error) {
//         console.error('Error loading image:', error)
//         setImageSrc(src)
//         setLoading(false)
//       }
//     }

//     fetchImage()

//     return () => {
//       if (imageSrc && imageSrc.startsWith('blob:')) {
//         URL.revokeObjectURL(imageSrc)
//       }
//     }
//   }, [src])

//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <CircularProgress size={24} />
//       </Box>
//     )
//   }

//   return (
//     <img
//       src={imageSrc || '/images/placeholder.png'}
//       alt={alt}
//       style={style}
//       onError={(e) => {
//         e.currentTarget.src = '/images/placeholder.png'
//       }}
//     />
//   )
// }

// const ProductDialog: React.FC<ProductDialogProps> = ({ 
//   open, 
//   onClose, 
//   product, 
//   editItem = null,
//   isEdit = false 
// }) => {
//   const dispatch = useDispatch()
//   const [loading, setLoading] = useState(false)
//   const [selectedVariation, setSelectedVariation] = useState<Variation | null>(null)
//   const [orderItemUid, setOrderItemUid] = useState<string>('')
//   const [posUid, setPosUid] = useState<string>('')
//   // Store quantities for each variation
//   const [quantities, setQuantities] = useState<{ [key: string]: number }>({})

//   // Initialize with edit data if in edit mode
//   useEffect(() => {
//     if (isEdit && editItem) {
//       if (product) {
//         const variation = product.variations.find(v => v.uid === editItem.id)
//         if (variation) {
//           setSelectedVariation(variation)
//           // Set quantity for the selected variation
//           setQuantities({
//             [variation.uid]: editItem.quantity || 1
//           })
//         }
//       }
//       setOrderItemUid(editItem.orderItemUid || '')
//       setPosUid(editItem.posUid || '')
//     } else if (product && product.variations.length > 0) {
//       // Initialize quantities for all variations with 0
//       const initialQuantities: { [key: string]: number } = {}
//       product.variations.forEach(v => {
//         initialQuantities[v.uid] = 0
//       })
//       setQuantities(initialQuantities)
//       setSelectedVariation(product.variations[0])
//     }
//   }, [product, editItem, isEdit, open])

//   // Reset when dialog closes
//   useEffect(() => {
//     if (!open) {
//       setSelectedVariation(null)
//       setOrderItemUid('')
//       setPosUid('')
//       setQuantities({})
//     }
//   }, [open])

//   // Fetch order details to get the actual item UID
//   const fetchOrderDetails = async (orderUid: string): Promise<{ itemUid: string, posUid: string }> => {
//     try {
//       const response = await axios.get(`${endpoints.pos.posOrder.get}${orderUid}`)
//       console.log('Order details response:', response.data)
      
//       const orderData = response.data?.content?.result || response.data?.content || response.data
      
//       let itemUid = orderUid
//       let posUid = orderUid
      
//       if (orderData) {
//         posUid = orderData.uid || orderData.orderUid || orderUid
        
//         if (orderData.items && orderData.items.length > 0) {
//           itemUid = orderData.items[0].uid || orderData.items[0].itemUid || posUid
//         } else if (orderData.itemUid) {
//           itemUid = orderData.itemUid
//         } else if (orderData.variationUid) {
//           itemUid = orderData.variationUid
//         }
//       }
      
//       return { itemUid, posUid }
//     } catch (error) {
//       console.error('Error fetching order details:', error)
//       return { itemUid: orderUid, posUid: orderUid }
//     }
//   }

//   // Get the variations with quantity > 0
//   const getActiveVariations = () => {
//     if (!product) return []
    
//     const activeVariations: { variation: Variation, quantity: number }[] = []
//     for (const v of product.variations) {
//       const qty = quantities[v.uid] || 0
//       if (qty > 0) {
//         activeVariations.push({ variation: v, quantity: qty })
//       }
//     }
//     return activeVariations
//   }

//   // Get quantity for a specific variation
//   const getQuantity = (variationUid: string): number => {
//     return quantities[variationUid] || 0
//   }

//   // Handle quantity change for a specific variation
//   const handleQuantityChange = (variationUid: string, newQuantity: number) => {
//     if (newQuantity < 0) return
    
//     const variation = product?.variations.find(v => v.uid === variationUid)
//     if (variation && variation.stockQty && newQuantity > variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
    
//     setQuantities(prev => ({
//       ...prev,
//       [variationUid]: newQuantity
//     }))
    
//     // If quantity > 0, set as selected variation
//     if (newQuantity > 0) {
//       const variation = product?.variations.find(v => v.uid === variationUid)
//       if (variation) {
//         setSelectedVariation(variation)
//       }
//     }
//   }

//   const handleDecrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const currentQty = getQuantity(variationUid)
//     if (currentQty > 0) {
//       handleQuantityChange(variationUid, currentQty - 1)
//     }
//   }

//   const handleIncrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const currentQty = getQuantity(variationUid)
//     const variation = product?.variations.find(v => v.uid === variationUid)
//     if (variation && variation.stockQty && currentQty >= variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
//     handleQuantityChange(variationUid, currentQty + 1)
//   }

//   const handleQtyInputChange = (e: React.ChangeEvent<HTMLInputElement>, variationUid: string) => {
//     e.stopPropagation()
//     const val = parseInt(e.target.value)
//     if (!isNaN(val) && val >= 0) {
//       handleQuantityChange(variationUid, val)
//     }
//   }

//   const handleAddToOrder = async () => {
//     // Get all variations with quantity > 0
//     const activeVariations = getActiveVariations()
    
//     if (activeVariations.length === 0) {
//       toast.error('Please add quantity for at least one variation', { style: { zIndex: 999999 } })
//       return
//     }

//     setLoading(true)

//     try {
//       if (isEdit && editItem) {
//         // UPDATE MODE - Only update the single item
//         const firstActive = activeVariations[0]
//         if (!orderItemUid) {
//           toast.error('Order item UID is missing. Please try again.', { style: { zIndex: 999999 } })
//           setLoading(false)
//           return
//         }
//         const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${orderItemUid}?quantity=${firstActive.quantity}`
//         await axios.put(updateUrl)
        
//         dispatch(updateQuantity({ 
//           id: firstActive.variation.uid, 
//           quantity: firstActive.quantity 
//         }))
        
//         toast.success('Item updated successfully!', { style: { zIndex: 999999 } })
//         onClose()
//       } else {
//         // ADD MODE - Add all variations with quantity > 0
//         // For each variation with quantity > 0, create a separate order
//         for (const active of activeVariations) {
//           const payload = {
//             items: [{
//               variationUid: active.variation.uid,
//               quantity: active.quantity
//             }]
//           }
          
//           const response = await axios.post(endpoints.pos.posOrder.create, payload)
//           const orderData = response.data
          
//           if (orderData) {
//             const orderUid = orderData.uid || orderData.orderUid || ''
//             const { itemUid, posUid: fetchedPosUid } = await fetchOrderDetails(orderUid)
            
//             dispatch(addToCart({
//               id: active.variation.uid,
//               productUid: product?.uid || '',
//               name: product?.name || '',
//               price: active.variation.mrp,
//               quantity: active.quantity,
//               image: getVariationImage(active.variation),
//               variation: active.variation,
//               orderItemUid: itemUid,
//               posUid: fetchedPosUid,
//               stockQty: active.variation.stockQty || 0
//             }))
//           }
//         }
        
//         toast.success(`${activeVariations.length} item(s) added to order!`, { style: { zIndex: 999999 } })
//         onClose()
//       }
//     } catch (error: any) {
//       console.error('Error:', error)
//       toast.error(error?.response?.data?.message || 'Failed to process item', { 
//         style: { zIndex: 999999 } 
//       })
//     } finally {
//       setLoading(false)
//     }
//   }

//   if (!product) return null

//   // Get price range for display
//   const prices = product.variations.map(v => v.mrp)
//   const minPrice = Math.min(...prices)
//   const maxPrice = Math.max(...prices)
//   const priceDisplay = minPrice === maxPrice ? `$${minPrice.toFixed(2)}` : `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`

//   // Get first variation with quantity > 0 for image
//   const activeVariations = getActiveVariations()
//   const firstActive = activeVariations.length > 0 ? activeVariations[0] : null
//   const selectedImage = firstActive ? getVariationImage(firstActive.variation) : ''

//   return (
//     <Dialog 
//       open={open} 
//       onClose={onClose} 
//       maxWidth="md" 
//       fullWidth
//       PaperProps={{
//         sx: { borderRadius: 2, zIndex: 999999 }
//       }}
//     >
//       <DialogTitle sx={{ 
//         display: 'flex', 
//         justifyContent: 'space-between', 
//         alignItems: 'center',
//         borderBottom: '1px solid',
//         borderColor: 'divider',
//         pb: 2
//       }}>
//         <Box>
//           <Typography variant="h6">{product.name}</Typography>
//           <Typography variant="body2" color="text.secondary">
//             {isEdit ? 'Edit Item' : 'Add to Order'}
//           </Typography>
//         </Box>
//         <IconButton onClick={onClose}>
//           <Icon icon="tabler:x" />
//         </IconButton>
//       </DialogTitle>

//       <DialogContent sx={{ pt: 3 }}>
//         {/* Product Description - Removed Image */}
//         <Box sx={{ mb: 3 }}>
//           <Typography variant="body2" color="text.secondary">
//             {product.description || 'No description available'}
//           </Typography>
//           <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1 }}>
//             Price Range: {priceDisplay}
//           </Typography>
//         </Box>

//         {/* Variations Table with QTY Stepper for ALL */}
//         <Typography variant="subtitle2" sx={{ mb: 2 }}>
//           Select Variation
//         </Typography>
//         <TableContainer component={Paper} sx={{ maxHeight: 300 }}>
//           <Table size="small" stickyHeader>
//             <TableHead>
//               <TableRow>
//                 <TableCell>SKU</TableCell>
//                 <TableCell>Image</TableCell>
//                 <TableCell>Stock</TableCell>
//                 <TableCell>Amount</TableCell>
//                 <TableCell>QTY</TableCell>
//                 <TableCell>Final</TableCell>
//                 <TableCell>Attributes</TableCell>
//               </TableRow>
//             </TableHead>
//             <TableBody>
//               {product.variations.map((variation) => {
//                 const imageUrl = getVariationImage(variation)
//                 const qty = getQuantity(variation.uid)
//                 const finalAmount = variation.mrp * qty
//                 const attrText = variation.attributes?.map(a => `${a.attributeName}: ${a.value}`).join(' | ') || ''
//                 const isActive = qty > 0
                
//                 return (
//                   <TableRow 
//                     key={variation.uid}
//                     sx={{ 
//                       bgcolor: isActive ? 'primary.light' : 'inherit',
//                       '&:hover': { bgcolor: isActive ? 'primary.light' : 'action.hover' }
//                     }}
//                   >
//                     <TableCell>
//                       <Typography variant="body2" fontWeight={500}>
//                         {variation.sku || 'N/A'}
//                       </Typography>
//                     </TableCell>
//                     <TableCell>
//                       <Box
//                         sx={{
//                           width: 40,
//                           height: 40,
//                           borderRadius: 1,
//                           overflow: 'hidden',
//                           display: 'flex',
//                           alignItems: 'center',
//                           justifyContent: 'center',
//                           bgcolor: 'grey.100'
//                         }}
//                       >
//                         {imageUrl ? (
//                           <AuthImageComponent
//                             src={imageUrl}
//                             alt=""
//                             style={{
//                               width: '100%',
//                               height: '100%',
//                               objectFit: 'cover'
//                             }}
//                           />
//                         ) : (
//                           <Typography variant="caption" color="text.secondary">N/A</Typography>
//                         )}
//                       </Box>
//                     </TableCell>
//                     <TableCell>{variation.stockQty || 0}</TableCell>
//                     <TableCell>${variation.mrp.toFixed(2)}</TableCell>
//                     <TableCell>
//                       <Box sx={{ display: 'flex', alignItems: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
//                         <IconButton 
//                           size="small" 
//                           onClick={(e) => handleDecrementQty(e, variation.uid)}
//                           disabled={qty <= 0}
//                           sx={{ borderRadius: 0, px: 1 }}
//                         >
//                           <Icon icon="tabler:minus" fontSize="small" />
//                         </IconButton>
//                         <TextField
//                           type="number"
//                           value={qty}
//                           onChange={(e) => handleQtyInputChange(e as React.ChangeEvent<HTMLInputElement>, variation.uid)}
//                           onClick={(e) => e.stopPropagation()}
//                           inputProps={{ 
//                             style: { textAlign: 'center', width: 40, padding: '4px 0' },
//                             min: 0,
//                             max: variation.stockQty || 999
//                           }}
//                           variant="standard"
//                           size="small"
//                           sx={{ 
//                             '& .MuiInput-underline:before': { borderBottom: 'none' },
//                             '& .MuiInput-underline:after': { borderBottom: 'none' },
//                             '& .MuiInput-root': { '&:before': { borderBottom: 'none' } }
//                           }}
//                           disabled={loading}
//                         />
//                         <IconButton 
//                           size="small" 
//                           onClick={(e) => handleIncrementQty(e, variation.uid)}
//                           disabled={variation.stockQty ? qty >= variation.stockQty : false}
//                           sx={{ borderRadius: 0, px: 1 }}
//                         >
//                           <Icon icon="tabler:plus" fontSize="small" />
//                         </IconButton>
//                       </Box>
//                     </TableCell>
//                     <TableCell sx={{ fontWeight: 600, color: isActive ? 'primary.main' : 'text.secondary' }}>
//                       ${finalAmount.toFixed(2)}
//                     </TableCell>
//                     <TableCell>
//                       <Typography variant="caption" color="text.secondary">
//                         {attrText}
//                       </Typography>
//                     </TableCell>
//                   </TableRow>
//                 )
//               })}
//             </TableBody>
//           </Table>
//         </TableContainer>

//         {/* Show count of selected variations */}
//         {activeVariations.length > 0 && (
//           <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
//             <Typography variant="body2" color="primary.main" fontWeight={600}>
//               {activeVariations.length} variation(s) selected
//             </Typography>
//           </Box>
//         )}
//       </DialogContent>

//       <DialogActions sx={{ p: 3, gap: 2, borderTop: '1px solid', borderColor: 'divider' }}>
//         <Button variant="outlined" onClick={onClose} disabled={loading}>
//           Cancel
//         </Button>
//         <Button
//           variant="contained"
//           onClick={handleAddToOrder}
//           disabled={loading || activeVariations.length === 0}
//           startIcon={loading ? <CircularProgress size={16} color="inherit" /> : null}
//         >
//           {loading ? 'Processing...' : isEdit ? 'Update Item' : 'Add Item'}
//         </Button>
//       </DialogActions>
//     </Dialog>
//   )
// }

// export default ProductDialog

// new changes 
// import React, { useState, useEffect } from 'react'

// // ** MUI Imports
// import {
//   Dialog,
//   DialogTitle,
//   DialogContent,
//   DialogActions,
//   Box,
//   Typography,
//   Button,
//   IconButton,
//   TextField,
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   Paper,
//   CircularProgress,
//   Chip
// } from '@mui/material'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// // ** Redux
// import { useDispatch } from 'react-redux'
// import { addToCart, updateQuantity, removeFromCart } from 'src/store/pages/pos/cartSlice'

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''
//   if (path.startsWith('http://') || path.startsWith('https://')) return path
//   if (path.startsWith('blob:') || path.startsWith('data:')) return path
//   const cleanPath = path.startsWith('/') ? path : `/${path}`
//   return `${cleanPath}`
// }

// const getVariationImage = (variation: any): string => {
//   if (!variation) return ''
//   const images = variation.variationImages || []
//   if (images.length === 0) return ''
//   const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
//   return imageUrl ? getFullImageUrl(imageUrl) : ''
// }

// interface Variation {
//   uid: string
//   sku: string
//   mrp: number
//   stockQty: number
//   quantity: number
//   unit: string
//   calAmount: number
//   finalAmount: number
//   variationImages: any[]
//   attributes: any[]
// }

// interface Product {
//   uid: string
//   name: string
//   description?: string
//   variations: Variation[]
// }

// interface ProductDialogProps {
//   open: boolean
//   onClose: () => void
//   product: Product | null
//   editItem?: any
//   isEdit?: boolean
// }

// // Image component with authentication
// const AuthImageComponent: React.FC<{ src: string; alt: string; style?: React.CSSProperties }> = ({ src, alt, style }) => {
//   const [imageSrc, setImageSrc] = useState<string>('')
//   const [loading, setLoading] = useState(true)

//   useEffect(() => {
//     if (!src) {
//       setImageSrc('/images/placeholder.png')
//       setLoading(false)
//       return
//     }

//     const fetchImage = async () => {
//       try {
//         const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
//         const response = await axios.get(src, {
//           responseType: 'blob',
//           headers: {
//             'Authorization': `Bearer ${token}`
//           }
//         })

//         const blob = response.data
//         const url = URL.createObjectURL(blob)
//         setImageSrc(url)
//         setLoading(false)
//       } catch (error) {
//         console.error('Error loading image:', error)
//         setImageSrc(src)
//         setLoading(false)
//       }
//     }

//     fetchImage()

//     return () => {
//       if (imageSrc && imageSrc.startsWith('blob:')) {
//         URL.revokeObjectURL(imageSrc)
//       }
//     }
//   }, [src])

//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <CircularProgress size={24} />
//       </Box>
//     )
//   }

//   return (
//     <img
//       src={imageSrc || '/images/placeholder.png'}
//       alt={alt}
//       style={style}
//       onError={(e) => {
//         e.currentTarget.src = '/images/placeholder.png'
//       }}
//     />
//   )
// }

// const ProductDialog: React.FC<ProductDialogProps> = ({ 
//   open, 
//   onClose, 
//   product, 
//   editItem = null,
//   isEdit = false 
// }) => {
//   const dispatch = useDispatch()
//   const [loading, setLoading] = useState(false)
//   const [selectedVariation, setSelectedVariation] = useState<Variation | null>(null)
//   const [orderItemUid, setOrderItemUid] = useState<string>('')
//   const [posUid, setPosUid] = useState<string>('')
//   const [orderUid, setOrderUid] = useState<string>('') // Added orderUid state
//   // Store quantities for each variation
//   const [quantities, setQuantities] = useState<{ [key: string]: number }>({})

//   // Initialize with edit data if in edit mode
//   useEffect(() => {
//     if (isEdit && editItem) {
//       if (product) {
//         const variation = product.variations.find(v => v.uid === editItem.id)
//         if (variation) {
//           setSelectedVariation(variation)
//           // Set quantity for the selected variation
//           setQuantities({
//             [variation.uid]: editItem.quantity || 1
//           })
//         }
//       }
//       setOrderItemUid(editItem.orderItemUid || '')
//       setPosUid(editItem.posUid || '')
//       setOrderUid(editItem.orderUid || '') // Set orderUid from editItem
//     } else if (product && product.variations.length > 0) {
//       // Initialize quantities for all variations with 0
//       const initialQuantities: { [key: string]: number } = {}
//       product.variations.forEach(v => {
//         initialQuantities[v.uid] = 0
//       })
//       setQuantities(initialQuantities)
//       setSelectedVariation(product.variations[0])
//     }
//   }, [product, editItem, isEdit, open])

//   // Reset when dialog closes
//   useEffect(() => {
//     if (!open) {
//       setSelectedVariation(null)
//       setOrderItemUid('')
//       setPosUid('')
//       setOrderUid('') // Reset orderUid
//       setQuantities({})
//     }
//   }, [open])

//   // Fetch order details to get the actual item UID
//   const fetchOrderDetails = async (orderUid: string): Promise<{ itemUid: string, posUid: string, orderUid: string }> => {
//     try {
//       const response = await axios.get(`${endpoints.pos.posOrder.get}${orderUid}`)
//       console.log('Order details response:', response.data)
      
//       const orderData = response.data?.content?.result || response.data?.content || response.data
      
//       let itemUid = orderUid
//       let posUid = orderUid
//       let orderUidFromResponse = orderUid
      
//       if (orderData) {
//         orderUidFromResponse = orderData.uid || orderData.orderUid || orderUid
//         posUid = orderData.uid || orderData.orderUid || orderUid
        
//         if (orderData.items && orderData.items.length > 0) {
//           itemUid = orderData.items[0].uid || orderData.items[0].itemUid || posUid
//         } else if (orderData.itemUid) {
//           itemUid = orderData.itemUid
//         } else if (orderData.variationUid) {
//           itemUid = orderData.variationUid
//         }
//       }
      
//       return { itemUid, posUid, orderUid: orderUidFromResponse }
//     } catch (error) {
//       console.error('Error fetching order details:', error)
//       return { itemUid: orderUid, posUid: orderUid, orderUid: orderUid }
//     }
//   }

//   // Get the variations with quantity > 0
//   const getActiveVariations = () => {
//     if (!product) return []
    
//     const activeVariations: { variation: Variation, quantity: number }[] = []
//     for (const v of product.variations) {
//       const qty = quantities[v.uid] || 0
//       if (qty > 0) {
//         activeVariations.push({ variation: v, quantity: qty })
//       }
//     }
//     return activeVariations
//   }

//   // Get quantity for a specific variation
//   const getQuantity = (variationUid: string): number => {
//     return quantities[variationUid] || 0
//   }

//   // Handle quantity change for a specific variation
//   const handleQuantityChange = (variationUid: string, newQuantity: number) => {
//     if (newQuantity < 0) return
    
//     const variation = product?.variations.find(v => v.uid === variationUid)
//     if (variation && variation.stockQty && newQuantity > variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
    
//     setQuantities(prev => ({
//       ...prev,
//       [variationUid]: newQuantity
//     }))
    
//     // If quantity > 0, set as selected variation
//     if (newQuantity > 0) {
//       const variation = product?.variations.find(v => v.uid === variationUid)
//       if (variation) {
//         setSelectedVariation(variation)
//       }
//     }
//   }

//   const handleDecrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const currentQty = getQuantity(variationUid)
//     if (currentQty > 0) {
//       handleQuantityChange(variationUid, currentQty - 1)
//     }
//   }

//   const handleIncrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const currentQty = getQuantity(variationUid)
//     const variation = product?.variations.find(v => v.uid === variationUid)
//     if (variation && variation.stockQty && currentQty >= variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
//     handleQuantityChange(variationUid, currentQty + 1)
//   }

//   const handleQtyInputChange = (e: React.ChangeEvent<HTMLInputElement>, variationUid: string) => {
//     e.stopPropagation()
//     const val = parseInt(e.target.value)
//     if (!isNaN(val) && val >= 0) {
//       handleQuantityChange(variationUid, val)
//     }
//   }

//   const handleAddToOrder = async () => {
//     // Get all variations with quantity > 0
//     const activeVariations = getActiveVariations()
    
//     if (activeVariations.length === 0) {
//       toast.error('Please add quantity for at least one variation', { style: { zIndex: 999999 } })
//       return
//     }

//     setLoading(true)

//     try {
//       if (isEdit && editItem) {
//         // UPDATE MODE - Only update the single item
//         const firstActive = activeVariations[0]
//         if (!orderItemUid) {
//           toast.error('Order item UID is missing. Please try again.', { style: { zIndex: 999999 } })
//           setLoading(false)
//           return
//         }
//         const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${orderItemUid}?quantity=${firstActive.quantity}`
//         await axios.put(updateUrl)
        
//         dispatch(updateQuantity({ 
//           id: firstActive.variation.uid, 
//           quantity: firstActive.quantity 
//         }))
        
//         toast.success('Item updated successfully!', { style: { zIndex: 999999 } })
//         onClose()
//       } else {
//         // ADD MODE - Add all variations with quantity > 0
//         // For each variation with quantity > 0, create a separate order
//         for (const active of activeVariations) {
//           const payload = {
//             items: [{
//               variationUid: active.variation.uid,
//               quantity: active.quantity
//             }]
//           }
          
//           const response = await axios.post(endpoints.pos.posOrder.create, payload)
//           const orderData = response.data
          
//           if (orderData) {
//             const orderUid = orderData.uid || orderData.orderUid || ''
//             const { itemUid, posUid: fetchedPosUid, orderUid: fetchedOrderUid } = await fetchOrderDetails(orderUid)
            
//             dispatch(addToCart({
//               id: active.variation.uid,
//               productUid: product?.uid || '',
//               name: product?.name || '',
//               price: active.variation.mrp,
//               quantity: active.quantity,
//               image: getVariationImage(active.variation),
//               variation: active.variation,
//               orderItemUid: itemUid,
//               posUid: fetchedPosUid,
//               orderUid: fetchedOrderUid, // Pass the orderUid here
//               stockQty: active.variation.stockQty || 0
//             }))
//           }
//         }
        
//         toast.success(`${activeVariations.length} item(s) added to order!`, { style: { zIndex: 999999 } })
//         onClose()
//       }
//     } catch (error: any) {
//       console.error('Error:', error)
//       toast.error(error?.response?.data?.message || 'Failed to process item', { 
//         style: { zIndex: 999999 } 
//       })
//     } finally {
//       setLoading(false)
//     }
//   }

//   if (!product) return null

//   // Get price range for display
//   const prices = product.variations.map(v => v.mrp)
//   const minPrice = Math.min(...prices)
//   const maxPrice = Math.max(...prices)
//   const priceDisplay = minPrice === maxPrice ? `$${minPrice.toFixed(2)}` : `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`

//   // Get first variation with quantity > 0 for image
//   const activeVariations = getActiveVariations()
//   const firstActive = activeVariations.length > 0 ? activeVariations[0] : null
//   const selectedImage = firstActive ? getVariationImage(firstActive.variation) : ''

//   return (
//     <Dialog 
//       open={open} 
//       onClose={onClose} 
//       maxWidth="md" 
//       fullWidth
//       PaperProps={{
//         sx: { borderRadius: 2, zIndex: 999999 }
//       }}
//     >
//       <DialogTitle sx={{ 
//         display: 'flex', 
//         justifyContent: 'space-between', 
//         alignItems: 'center',
//         borderBottom: '1px solid',
//         borderColor: 'divider',
//         pb: 2
//       }}>
//         <Box>
//           <Typography variant="h6">{product.name}</Typography>
//           <Typography variant="body2" color="text.secondary">
//             {isEdit ? 'Edit Item' : 'Add to Order'}
//           </Typography>
//         </Box>
//         <IconButton onClick={onClose}>
//           <Icon icon="tabler:x" />
//         </IconButton>
//       </DialogTitle>

//       <DialogContent sx={{ pt: 3 }}>
//         {/* Product Description - Removed Image */}
//         <Box sx={{ mb: 3 }}>
//           <Typography variant="body2" color="text.secondary">
//             {product.description || 'No description available'}
//           </Typography>
//           <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1 }}>
//             Price Range: {priceDisplay}
//           </Typography>
//         </Box>

//         {/* Variations Table with QTY Stepper for ALL */}
//         <Typography variant="subtitle2" sx={{ mb: 2 }}>
//           Select Variation
//         </Typography>
//         <TableContainer component={Paper} sx={{ maxHeight: 300 }}>
//           <Table size="small" stickyHeader>
//             <TableHead>
//               <TableRow>
//                 <TableCell>SKU</TableCell>
//                 <TableCell>Image</TableCell>
//                 <TableCell>Stock</TableCell>
//                 <TableCell>Amount</TableCell>
//                 <TableCell>QTY</TableCell>
//                 <TableCell>Final</TableCell>
//                 <TableCell>Attributes</TableCell>
//               </TableRow>
//             </TableHead>
//             <TableBody>
//               {product.variations.map((variation) => {
//                 const imageUrl = getVariationImage(variation)
//                 const qty = getQuantity(variation.uid)
//                 const finalAmount = variation.mrp * qty
//                 const attrText = variation.attributes?.map(a => `${a.attributeName}: ${a.value}`).join(' | ') || ''
//                 const isActive = qty > 0
                
//                 return (
//                   <TableRow 
//                     key={variation.uid}
//                     sx={{ 
//                       bgcolor: isActive ? 'primary.light' : 'inherit',
//                       '&:hover': { bgcolor: isActive ? 'primary.light' : 'action.hover' }
//                     }}
//                   >
//                     <TableCell>
//                       <Typography variant="body2" fontWeight={500}>
//                         {variation.sku || 'N/A'}
//                       </Typography>
//                     </TableCell>
//                     <TableCell>
//                       <Box
//                         sx={{
//                           width: 40,
//                           height: 40,
//                           borderRadius: 1,
//                           overflow: 'hidden',
//                           display: 'flex',
//                           alignItems: 'center',
//                           justifyContent: 'center',
//                           bgcolor: 'grey.100'
//                         }}
//                       >
//                         {imageUrl ? (
//                           <AuthImageComponent
//                             src={imageUrl}
//                             alt=""
//                             style={{
//                               width: '100%',
//                               height: '100%',
//                               objectFit: 'cover'
//                             }}
//                           />
//                         ) : (
//                           <Typography variant="caption" color="text.secondary">N/A</Typography>
//                         )}
//                       </Box>
//                     </TableCell>
//                     <TableCell>{variation.stockQty || 0}</TableCell>
//                     <TableCell>${variation.mrp.toFixed(2)}</TableCell>
//                     <TableCell>
//                       <Box sx={{ display: 'flex', alignItems: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
//                         <IconButton 
//                           size="small" 
//                           onClick={(e) => handleDecrementQty(e, variation.uid)}
//                           disabled={qty <= 0}
//                           sx={{ borderRadius: 0, px: 1 }}
//                         >
//                           <Icon icon="tabler:minus" fontSize="small" />
//                         </IconButton>
//                         <TextField
//                           type="number"
//                           value={qty}
//                           onChange={(e) => handleQtyInputChange(e as React.ChangeEvent<HTMLInputElement>, variation.uid)}
//                           onClick={(e) => e.stopPropagation()}
//                           inputProps={{ 
//                             style: { textAlign: 'center', width: 40, padding: '4px 0' },
//                             min: 0,
//                             max: variation.stockQty || 999
//                           }}
//                           variant="standard"
//                           size="small"
//                           sx={{ 
//                             '& .MuiInput-underline:before': { borderBottom: 'none' },
//                             '& .MuiInput-underline:after': { borderBottom: 'none' },
//                             '& .MuiInput-root': { '&:before': { borderBottom: 'none' } }
//                           }}
//                           disabled={loading}
//                         />
//                         <IconButton 
//                           size="small" 
//                           onClick={(e) => handleIncrementQty(e, variation.uid)}
//                           disabled={variation.stockQty ? qty >= variation.stockQty : false}
//                           sx={{ borderRadius: 0, px: 1 }}
//                         >
//                           <Icon icon="tabler:plus" fontSize="small" />
//                         </IconButton>
//                       </Box>
//                     </TableCell>
//                     <TableCell sx={{ fontWeight: 600, color: isActive ? 'primary.main' : 'text.secondary' }}>
//                       ${finalAmount.toFixed(2)}
//                     </TableCell>
//                     <TableCell>
//                       <Typography variant="caption" color="text.secondary">
//                         {attrText}
//                       </Typography>
//                     </TableCell>
//                   </TableRow>
//                 )
//               })}
//             </TableBody>
//           </Table>
//         </TableContainer>

//         {/* Show count of selected variations */}
//         {activeVariations.length > 0 && (
//           <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
//             <Typography variant="body2" color="primary.main" fontWeight={600}>
//               {activeVariations.length} variation(s) selected
//             </Typography>
//           </Box>
//         )}
//       </DialogContent>

//       <DialogActions sx={{ p: 3, gap: 2, borderTop: '1px solid', borderColor: 'divider' }}>
//         <Button variant="outlined" onClick={onClose} disabled={loading}>
//           Cancel
//         </Button>
//         <Button
//           variant="contained"
//           onClick={handleAddToOrder}
//           disabled={loading || activeVariations.length === 0}
//           startIcon={loading ? <CircularProgress size={16} color="inherit" /> : null}
//         >
//           {loading ? 'Processing...' : isEdit ? 'Update Item' : 'Add Item'}
//         </Button>
//       </DialogActions>
//     </Dialog>
//   )
// }

// export default ProductDialog


// final 
// import React, { useState, useEffect } from 'react'

// // ** MUI Imports
// import {
//   Dialog,
//   DialogTitle,
//   DialogContent,
//   DialogActions,
//   Box,
//   Typography,
//   Button,
//   IconButton,
//   TextField,
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   Paper,
//   CircularProgress,
//   Chip,
//   FormControl,
//   Select,
//   MenuItem,
//   OutlinedInput
// } from '@mui/material'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// // ** Redux
// import { useDispatch, useSelector } from 'react-redux'
// import { addToCart, updateQuantity } from 'src/store/pages/pos/cartSlice'
// import { RootState } from 'src/store'

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''
//   if (path.startsWith('http://') || path.startsWith('https://')) return path
//   if (path.startsWith('blob:') || path.startsWith('data:')) return path
//   const cleanPath = path.startsWith('/') ? path : `/${path}`
//   return `${cleanPath}`
// }

// const getVariationImage = (variation: any): string => {
//   if (!variation) return ''
//   const images = variation.variationImages || []
//   if (images.length === 0) return ''
//   const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
//   return imageUrl ? getFullImageUrl(imageUrl) : ''
// }

// interface Variation {
//   uid: string
//   sku: string
//   mrp: number
//   stockQty: number | null
//   quantity: number
//   unit: string
//   calAmount: number
//   finalAmount: number
//   variationImages: any[]
//   attributes: any[]
// }

// interface Product {
//   uid: string
//   name: string
//   description?: string
//   productType?: string
//   isInventoryManaged?: boolean
//   variations: Variation[]
//   staffs?: any[]
// }

// interface ProductDialogProps {
//   open: boolean
//   onClose: () => void
//   product: Product | null
//   editItem?: any
//   isEdit?: boolean
// }

// // Image component with authentication
// const AuthImageComponent: React.FC<{ src: string; alt: string; style?: React.CSSProperties }> = ({ src, alt, style }) => {
//   const [imageSrc, setImageSrc] = useState<string>('')
//   const [loading, setLoading] = useState(true)

//   useEffect(() => {
//     if (!src) {
//       setImageSrc('/images/placeholder.png')
//       setLoading(false)
//       return
//     }

//     const fetchImage = async () => {
//       try {
//         const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
//         const response = await axios.get(src, {
//           responseType: 'blob',
//           headers: {
//             'Authorization': `Bearer ${token}`
//           }
//         })

//         const blob = response.data
//         const url = URL.createObjectURL(blob)
//         setImageSrc(url)
//         setLoading(false)
//       } catch (error) {
//         console.error('Error loading image:', error)
//         setImageSrc(src)
//         setLoading(false)
//       }
//     }

//     fetchImage()

//     return () => {
//       if (imageSrc && imageSrc.startsWith('blob:')) {
//         URL.revokeObjectURL(imageSrc)
//       }
//     }
//   }, [src])

//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <CircularProgress size={24} />
//       </Box>
//     )
//   }

//   return (
//     <img
//       src={imageSrc || '/images/placeholder.png'}
//       alt={alt}
//       style={style}
//       onError={(e) => {
//         e.currentTarget.src = '/images/placeholder.png'
//       }}
//     />
//   )
// }

// const ProductDialog: React.FC<ProductDialogProps> = ({ 
//   open, 
//   onClose, 
//   product, 
//   editItem = null,
//   isEdit = false 
// }) => {
//   const dispatch = useDispatch()
//   const cartEntities = useSelector((state: RootState) => state.cartSlice.entities)
  
//   const [loading, setLoading] = useState(false)
//   const [selectedVariation, setSelectedVariation] = useState<Variation | null>(null)
//   const [orderItemUid, setOrderItemUid] = useState<string>('')
//   const [posUid, setPosUid] = useState<string>('')
//   const [orderUid, setOrderUid] = useState<string>('')
  
//   // Store quantities for each variation
//   const [quantities, setQuantities] = useState<{ [key: string]: number }>({})
  
//   // Staff selection for service-based products
//   const [selectedStaff, setSelectedStaff] = useState<{ [key: string]: string[] }>({})
//   const [availableStaff, setAvailableStaff] = useState<any[]>([])

//   const isServiceBased = product?.productType === 'ServiceBased'
//   const isReadyToSell = product?.productType === 'ReadyToSell'
//   const isInventoryNotManaged = product?.isInventoryManaged === false

//   // Initialize with edit data if in edit mode
//   useEffect(() => {
//     if (isEdit && editItem) {
//       if (product) {
//         const variation = product.variations.find(v => v.uid === editItem.id)
//         if (variation) {
//           setSelectedVariation(variation)
//           setQuantities({
//             [variation.uid]: editItem.quantity || 1
//           })
//           // If service-based, restore selected staff
//           if (isServiceBased && editItem.selectedStaff) {
//             setSelectedStaff({
//               [variation.uid]: editItem.selectedStaff
//             })
//           }
//         }
//       }
//       setOrderItemUid(editItem.orderItemUid || '')
//       setPosUid(editItem.posUid || '')
//       setOrderUid(editItem.orderUid || '')
//     } else if (product && product.variations.length > 0) {
//       const initialQuantities: { [key: string]: number } = {}
//       const initialStaff: { [key: string]: string[] } = {}
      
//       product.variations.forEach(v => {
//         // For service-based, quantity is always 1 (controlled by staff selection)
//         if (isServiceBased) {
//           initialQuantities[v.uid] = 0
//         }
//         // For ReadyToSell with inventory not managed, start with 0 (user must select)
//         else if (isReadyToSell && isInventoryNotManaged) {
//           initialQuantities[v.uid] = 0
//         }
//         // For ReadyToSell with inventory managed and stockQty === 0, quantity is 0 (out of stock)
//         else if (isReadyToSell && product.isInventoryManaged && v.stockQty === 0) {
//           initialQuantities[v.uid] = 0
//         }
//         // Normal case - start with 0
//         else {
//           initialQuantities[v.uid] = 0
//         }
//         initialStaff[v.uid] = []
//       })
      
//       setQuantities(initialQuantities)
//       setSelectedStaff(initialStaff)
//       setSelectedVariation(product.variations[0])
      
//       // Load staff for service-based products
//       if (isServiceBased && product.staffs) {
//         setAvailableStaff(product.staffs)
//       }
//     }
//   }, [product, editItem, isEdit, open, isServiceBased, isReadyToSell, isInventoryNotManaged])

//   // Reset when dialog closes
//   useEffect(() => {
//     if (!open) {
//       setSelectedVariation(null)
//       setOrderItemUid('')
//       setPosUid('')
//       setOrderUid('')
//       setQuantities({})
//       setSelectedStaff({})
//       setAvailableStaff([])
//     }
//   }, [open])

//   // Check if variation already exists in cart
//   const findExistingCartItem = (variationUid: string): any => {
//     const cartItems = Object.values(cartEntities) as any[]
//     return cartItems.find(item => item.id === variationUid)
//   }

//   // Fetch order details to get the actual item UID
//   const fetchOrderDetails = async (orderUid: string): Promise<{ itemUid: string, posUid: string, orderUid: string }> => {
//     try {
//       const response = await axios.get(`${endpoints.pos.posOrder.get}${orderUid}`)
//       console.log('Order details response:', response.data)
      
//       const orderData = response.data?.content?.result || response.data?.content || response.data
      
//       let itemUid = orderUid
//       let posUid = orderUid
//       let orderUidFromResponse = orderUid
      
//       if (orderData) {
//         orderUidFromResponse = orderData.uid || orderData.orderUid || orderUid
//         posUid = orderData.uid || orderData.orderUid || orderUid
        
//         if (orderData.items && orderData.items.length > 0) {
//           itemUid = orderData.items[0].uid || orderData.items[0].itemUid || posUid
//         } else if (orderData.itemUid) {
//           itemUid = orderData.itemUid
//         } else if (orderData.variationUid) {
//           itemUid = orderData.variationUid
//         }
//       }
      
//       return { itemUid, posUid, orderUid: orderUidFromResponse }
//     } catch (error) {
//       console.error('Error fetching order details:', error)
//       return { itemUid: orderUid, posUid: orderUid, orderUid: orderUid }
//     }
//   }

//   // Get the variations with quantity > 0
//   const getActiveVariations = () => {
//     if (!product) return []
    
//     const activeVariations: { variation: Variation, quantity: number }[] = []
//     for (const v of product.variations) {
//       const qty = quantities[v.uid] || 0
//       if (qty > 0) {
//         activeVariations.push({ variation: v, quantity: qty })
//       }
//     }
//     return activeVariations
//   }

//   // Get quantity for a specific variation
//   const getQuantity = (variationUid: string): number => {
//     return quantities[variationUid] || 0
//   }

//   // Get selected staff for a variation
//   const getSelectedStaff = (variationUid: string): string[] => {
//     return selectedStaff[variationUid] || []
//   }

//   // Check if quantity controls should be disabled (hide +/- buttons)
//   const shouldDisableQuantityControls = (variation: Variation): boolean => {
//     // Service-based: always disabled
//     if (isServiceBased) return true
    
//     // ReadyToSell with inventory not managed: disabled (fixed quantity 1 when selected)
//     if (isReadyToSell && isInventoryNotManaged) {
//       return true
//     }
    
//     // ReadyToSell with inventory managed and stockQty === 0: disabled (out of stock)
//     if (isReadyToSell && product?.isInventoryManaged && variation.stockQty === 0) {
//       return true
//     }
    
//     // ReadyToSell with inventory managed and stockQty > 0: enabled
//     return false
//   }

//   // Check if stock should show "Out of Stock" (only for inventory managed with stock 0)
//   const shouldShowOutOfStock = (variation: Variation): boolean => {
//     return isReadyToSell && product?.isInventoryManaged && variation.stockQty === 0
//   }

//   // Check if quantity should be fixed to 1 (no controls, just display)
//   const shouldShowFixedQuantity = (variation: Variation): boolean => {
//     // Service-based: fixed quantity (but controlled by staff selection)
//     if (isServiceBased) return true
    
//     // ReadyToSell with inventory not managed: fixed quantity 1 when selected
//     if (isReadyToSell && isInventoryNotManaged) {
//       return true
//     }
    
//     return false
//   }

//   // Toggle variation selection (for inventory not managed)
//   const toggleVariationSelection = (variationUid: string) => {
//     if (!isReadyToSell || !isInventoryNotManaged) return
    
//     const currentQty = getQuantity(variationUid)
//     // If currently 0, set to 1 (select), if 1, set to 0 (deselect)
//     handleQuantityChange(variationUid, currentQty === 0 ? 1 : 0)
//   }

//   // Handle quantity change for a specific variation
//   const handleQuantityChange = (variationUid: string, newQuantity: number) => {
//     const variation = product?.variations.find(v => v.uid === variationUid)
//     if (!variation) return
    
//     // Check if quantity controls are disabled
//     if (shouldDisableQuantityControls(variation)) {
//       // For inventory not managed, allow toggling between 0 and 1
//       if (isReadyToSell && isInventoryNotManaged) {
//         // Only allow 0 or 1
//         if (newQuantity > 1) return
//         if (newQuantity < 0) return
//       } else {
//         return
//       }
//     }
    
//     if (newQuantity < 0) return
    
//     if (variation.stockQty && newQuantity > variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
    
//     setQuantities(prev => ({
//       ...prev,
//       [variationUid]: newQuantity
//     }))
    
//     if (newQuantity > 0) {
//       const variation = product?.variations.find(v => v.uid === variationUid)
//       if (variation) {
//         setSelectedVariation(variation)
//       }
//     }
//   }

//   // Handle staff selection for service-based products
//   const handleStaffChange = (variationUid: string, staffUids: string[]) => {
//     setSelectedStaff(prev => ({
//       ...prev,
//       [variationUid]: staffUids
//     }))
    
//     // Update quantity based on number of selected staff (for service-based)
//     if (isServiceBased) {
//       const staffCount = staffUids.length
//       setQuantities(prev => ({
//         ...prev,
//         [variationUid]: staffCount > 0 ? 1 : 0
//       }))
//     }
//   }

//   const handleDecrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const variation = product?.variations.find(v => v.uid === variationUid)
//     if (!variation || shouldDisableQuantityControls(variation)) return
    
//     const currentQty = getQuantity(variationUid)
//     if (currentQty > 0) {
//       handleQuantityChange(variationUid, currentQty - 1)
//     }
//   }

//   const handleIncrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const variation = product?.variations.find(v => v.uid === variationUid)
//     if (!variation || shouldDisableQuantityControls(variation)) return
    
//     const currentQty = getQuantity(variationUid)
//     if (variation.stockQty && currentQty >= variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
//     handleQuantityChange(variationUid, currentQty + 1)
//   }

//   const handleQtyInputChange = (e: React.ChangeEvent<HTMLInputElement>, variationUid: string) => {
//     const variation = product?.variations.find(v => v.uid === variationUid)
//     if (!variation || shouldDisableQuantityControls(variation)) return
    
//     e.stopPropagation()
//     const val = parseInt(e.target.value)
//     if (!isNaN(val) && val >= 0) {
//       handleQuantityChange(variationUid, val)
//     }
//   }

//   const handleAddToOrder = async () => {
//     // Get all variations with quantity > 0
//     const activeVariations = getActiveVariations()
    
//     if (activeVariations.length === 0) {
//       toast.error('Please select at least one variation', { style: { zIndex: 999999 } })
//       return
//     }

//     setLoading(true)

//     try {
//       if (isEdit && editItem) {
//         // UPDATE MODE - Only update the single item
//         const firstActive = activeVariations[0]
//         if (!orderItemUid) {
//           toast.error('Order item UID is missing. Please try again.', { style: { zIndex: 999999 } })
//           setLoading(false)
//           return
//         }
//         const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${orderItemUid}?quantity=${firstActive.quantity}`
//         await axios.put(updateUrl)
        
//         dispatch(updateQuantity({ 
//           id: firstActive.variation.uid, 
//           quantity: firstActive.quantity 
//         }))
        
//         toast.success('Item updated successfully!', { style: { zIndex: 999999 } })
//         onClose()
//       } else {
//         // ADD MODE - Add all variations with quantity > 0
//         for (const active of activeVariations) {
//           // Check if this variation already exists in cart
//           const existingItem = findExistingCartItem(active.variation.uid)
          
//           if (existingItem) {
//             // Update existing item - Call Update Quantity API
//             const existingOrderItemUid = existingItem.orderItemUid
//             if (!existingOrderItemUid) {
//               toast.error('Order item UID is missing for existing item', { style: { zIndex: 999999 } })
//               continue
//             }
            
//             const newQuantity = existingItem.quantity + active.quantity
//             const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${existingOrderItemUid}?quantity=${newQuantity}`
//             await axios.put(updateUrl)
            
//             // Update Redux
//             dispatch(updateQuantity({ 
//               id: active.variation.uid, 
//               quantity: newQuantity 
//             }))
            
//             toast.success(`Item quantity updated to ${newQuantity}!`, { style: { zIndex: 999999 } })
//           } else {
//             // Create new order for this variation
//             let payload: any = {}
            
//             if (isServiceBased) {
//               // Service-based payload with staffUids
//               const staffUids = getSelectedStaff(active.variation.uid)
//               if (staffUids.length === 0) {
//                 toast.error('Please select at least one staff member', { style: { zIndex: 999999 } })
//                 setLoading(false)
//                 return
//               }
              
//               // Create items array with each staff member as a separate item
//               payload = {
//                 items: staffUids.map(staffUid => ({
//                   staffUid: staffUid,
//                   variationUid: active.variation.uid,
//                   quantity: 1
//                 })),
//                 productType: product?.productType || 'ServiceBased'
//               }
//             } else {
//               // ReadyToSell payload
//               payload = {
//                 items: [{
//                   variationUid: active.variation.uid,
//                   quantity: active.quantity
//                 }],
//                 productType: product?.productType || 'ReadyToSell'
//               }
//             }
            
//             const response = await axios.post(endpoints.pos.posOrder.create, payload)
//             const orderData = response.data
            
//             if (orderData) {
//               const orderUid = orderData.uid || orderData.orderUid || ''
//               const { itemUid, posUid: fetchedPosUid, orderUid: fetchedOrderUid } = await fetchOrderDetails(orderUid)
              
//               dispatch(addToCart({
//                 id: active.variation.uid,
//                 productUid: product?.uid || '',
//                 name: product?.name || '',
//                 price: active.variation.mrp,
//                 quantity: isServiceBased ? getSelectedStaff(active.variation.uid).length : active.quantity,
//                 image: getVariationImage(active.variation),
//                 variation: active.variation,
//                 orderItemUid: itemUid,
//                 posUid: fetchedPosUid,
//                 orderUid: fetchedOrderUid,
//                 stockQty: active.variation.stockQty || 0,
//                 productType: product?.productType || 'ReadyToSell',
//                 isInventoryManaged: product?.isInventoryManaged || false,
//                 // For service-based, store selected staff
//                 ...(isServiceBased && {
//                   selectedStaff: getSelectedStaff(active.variation.uid)
//                 })
//               }))
//             }
//           }
//         }
        
//         toast.success(`${activeVariations.length} item(s) added to order!`, { style: { zIndex: 999999 } })
//         onClose()
//       }
//     } catch (error: any) {
//       console.error('Error:', error)
//       toast.error(error?.response?.data?.message || 'Failed to process item', { 
//         style: { zIndex: 999999 } 
//       })
//     } finally {
//       setLoading(false)
//     }
//   }

//   if (!product) return null

//   // Get price range for display
//   const prices = product.variations.map(v => v.mrp)
//   const minPrice = Math.min(...prices)
//   const maxPrice = Math.max(...prices)
//   const priceDisplay = minPrice === maxPrice ? `$${minPrice.toFixed(2)}` : `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`

//   // Get first variation with quantity > 0 for image
//   const activeVariations = getActiveVariations()

//   // Check if product should hide edit in order details
//   const shouldHideEdit = () => {
//     if (isServiceBased) return true
//     if (isReadyToSell) {
//       const variation = product.variations[0]
//       // Hide edit if inventory not managed OR stock is 0 (inventory managed)
//       if (!product.isInventoryManaged || variation?.stockQty === 0) return true
//     }
//     return false
//   }

//   return (
//     <Dialog 
//       open={open} 
//       onClose={onClose} 
//       maxWidth="md" 
//       fullWidth
//       PaperProps={{
//         sx: { borderRadius: 2, zIndex: 999999 }
//       }}
//     >
//       <DialogTitle sx={{ 
//         display: 'flex', 
//         justifyContent: 'space-between', 
//         alignItems: 'center',
//         borderBottom: '1px solid',
//         borderColor: 'divider',
//         pb: 2
//       }}>
//         <Box>
//           <Typography variant="h6">{product.name}</Typography>
//           <Typography variant="body2" color="text.secondary">
//             {isEdit ? 'Edit Item' : 'Add to Order'}
//             {product.productType && (
//               <Chip 
//                 label={product.productType} 
//                 size="small" 
//                 color={product.productType === 'ServiceBased' ? 'secondary' : 'primary'}
//                 sx={{ ml: 1 }}
//               />
//             )}
//           </Typography>
//         </Box>
//         <IconButton onClick={onClose}>
//           <Icon icon="tabler:x" />
//         </IconButton>
//       </DialogTitle>

//       <DialogContent sx={{ pt: 3 }}>
//         {/* Product Description - Removed Image */}
//         <Box sx={{ mb: 3 }}>
//           <Typography variant="body2" color="text.secondary">
//             Product Description: {product.description || 'No description available'}
//           </Typography>
//           <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1 }}>
//             Price Range: {priceDisplay}
//           </Typography>
//         </Box>

//         {/* Variations Table with QTY Stepper for ALL */}
//         <Typography variant="subtitle2" sx={{ mb: 2 }}>
//           Select Variation{isInventoryNotManaged && ' (Click row to select/deselect)'}
//         </Typography>
//         <TableContainer component={Paper} sx={{ maxHeight: 300 }}>
//           <Table size="small" stickyHeader>
//             <TableHead>
//               <TableRow>
//                 {!isServiceBased && <TableCell>SKU</TableCell>}
//                 <TableCell>Image</TableCell>
//                 {!isServiceBased && <TableCell>Stock</TableCell>}
//                 <TableCell>Amount</TableCell>
//                 <TableCell>{isServiceBased ? 'Staff Members' : 'QTY'}</TableCell>
//                 <TableCell>Final</TableCell>
//                 <TableCell>Attributes</TableCell>
//               </TableRow>
//             </TableHead>
//             <TableBody>
//               {product.variations.map((variation) => {
//                 const imageUrl = getVariationImage(variation)
//                 const qty = getQuantity(variation.uid)
//                 const selectedStaffUids = getSelectedStaff(variation.uid)
//                 const showOutOfStock = shouldShowOutOfStock(variation)
//                 const showFixedQty = shouldShowFixedQuantity(variation)
//                 const disableControls = shouldDisableQuantityControls(variation)
//                 const isSelected = qty > 0
                
//                 // Calculate final amount
//                 let finalAmount = variation.mrp * qty
//                 // For service-based, final amount = price × number of selected staff
//                 if (isServiceBased) {
//                   finalAmount = variation.mrp * selectedStaffUids.length
//                 }
                
//                 // Determine if row should be clickable
//                 const isRowClickable = isReadyToSell && isInventoryNotManaged
                
//                 return (
//                   <TableRow 
//                     key={variation.uid}
//                     onClick={() => {
//                       // For inventory not managed, click to toggle selection
//                       if (isRowClickable) {
//                         toggleVariationSelection(variation.uid)
//                       }
//                     }}
//                     sx={{ 
//                       bgcolor: isSelected ? 'primary.light' : 'inherit',
//                       cursor: isRowClickable ? 'pointer' : 'default',
//                       '&:hover': { 
//                         bgcolor: isSelected ? 'primary.main' : 'action.hover',
//                         '& .MuiTypography-root': {
//                           color: isSelected ? 'white' : 'inherit'
//                         }
//                       },
//                       transition: 'background-color 0.2s ease'
//                     }}
//                   >
//                     {!isServiceBased && (
//                       <TableCell>
//                         <Typography variant="body2" fontWeight={500}>
//                           {variation.sku || 'N/A'}
//                         </Typography>
//                       </TableCell>
//                     )}
//                     <TableCell>
//                       <Box
//                         sx={{
//                           width: 40,
//                           height: 40,
//                           borderRadius: 1,
//                           overflow: 'hidden',
//                           display: 'flex',
//                           alignItems: 'center',
//                           justifyContent: 'center',
//                           bgcolor: 'grey.100'
//                         }}
//                       >
//                         {imageUrl ? (
//                           <AuthImageComponent
//                             src={imageUrl}
//                             alt=""
//                             style={{
//                               width: '100%',
//                               height: '100%',
//                               objectFit: 'cover'
//                             }}
//                           />
//                         ) : (
//                           <Typography variant="caption" color="text.secondary">N/A</Typography>
//                         )}
//                       </Box>
//                     </TableCell>
//                     {!isServiceBased && (
//                       <TableCell>
//                         {showOutOfStock ? (
//                           <Typography variant="body2" color="error" fontWeight="bold">
//                             Out of Stock
//                           </Typography>
//                         ) : (
//                           <Typography variant="body2">
//                             {variation.stockQty ?? 'N/A'}
//                           </Typography>
//                         )}
//                       </TableCell>
//                     )}
//                     <TableCell>${variation.mrp.toFixed(2)}</TableCell>
//                     <TableCell>
//                       {isServiceBased ? (
//                         // Staff Member Multi Select Dropdown
//                         <FormControl size="small" sx={{ minWidth: 150 }}>
//                           <Select
//                             multiple
//                             value={selectedStaffUids}
//                             onChange={(e) => handleStaffChange(variation.uid, e.target.value as string[])}
//                             input={<OutlinedInput size="small" />}
//                             renderValue={(selected) => {
//                               const selectedNames = availableStaff
//                                 .filter(s => (selected as string[]).includes(s.uid))
//                                 .map(s => `${s.firstName} ${s.lastName}`)
//                               return selectedNames.join(', ') || 'Select staff'
//                             }}
//                             disabled={loading}
//                           >
//                             {availableStaff.map((staff) => (
//                               <MenuItem key={staff.uid} value={staff.uid}>
//                                 <Typography variant="body2">
//                                   {staff.firstName} {staff.lastName}
//                                 </Typography>
//                               </MenuItem>
//                             ))}
//                           </Select>
//                         </FormControl>
//                       ) : isInventoryNotManaged ? (
//                         // For inventory not managed - just show the quantity (1 if selected, 0 if not)
//                         <Typography 
//                           variant="body2" 
//                           fontWeight={isSelected ? 600 : 400}
//                           color={isSelected ? 'primary.main' : 'text.secondary'}
//                           sx={{ textAlign: 'center' }}
//                         >
//                           {qty}
//                         </Typography>
//                       ) : showFixedQty ? (
//                         // Fixed quantity display - NO +/- buttons, just the number
//                         <Typography variant="body2" fontWeight={500} sx={{ px: 2, py: 1, textAlign: 'center' }}>
//                           {qty}
//                         </Typography>
//                       ) : disableControls ? (
//                         // Disabled state (out of stock with inventory managed)
//                         <Typography variant="body2" color="text.secondary" sx={{ px: 2, py: 1, textAlign: 'center' }}>
//                           {qty}
//                         </Typography>
//                       ) : (
//                         // Normal quantity controls with +/- buttons
//                         <Box sx={{ display: 'flex', alignItems: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
//                           <IconButton 
//                             size="small" 
//                             onClick={(e) => handleDecrementQty(e, variation.uid)}
//                             disabled={qty <= 0}
//                             sx={{ borderRadius: 0, px: 1 }}
//                           >
//                             <Icon icon="tabler:minus" fontSize="small" />
//                           </IconButton>
//                           <TextField
//                             type="number"
//                             value={qty}
//                             onChange={(e) => handleQtyInputChange(e as React.ChangeEvent<HTMLInputElement>, variation.uid)}
//                             onClick={(e) => e.stopPropagation()}
//                             inputProps={{ 
//                               style: { textAlign: 'center', width: 40, padding: '4px 0' },
//                               min: 0,
//                               max: variation.stockQty || 999
//                             }}
//                             variant="standard"
//                             size="small"
//                             sx={{ 
//                               '& .MuiInput-underline:before': { borderBottom: 'none' },
//                               '& .MuiInput-underline:after': { borderBottom: 'none' },
//                               '& .MuiInput-root': { '&:before': { borderBottom: 'none' } }
//                             }}
//                             disabled={loading}
//                           />
//                           <IconButton 
//                             size="small" 
//                             onClick={(e) => handleIncrementQty(e, variation.uid)}
//                             disabled={variation.stockQty ? qty >= variation.stockQty : false}
//                             sx={{ borderRadius: 0, px: 1 }}
//                           >
//                             <Icon icon="tabler:plus" fontSize="small" />
//                           </IconButton>
//                         </Box>
//                       )}
//                     </TableCell>
//                     <TableCell sx={{ fontWeight: 600, color: isSelected ? 'primary.main' : 'text.secondary' }}>
//                       ${finalAmount.toFixed(2)}
//                     </TableCell>
//                     <TableCell>
//                       <Typography variant="caption" color="text.secondary">
//                         {variation.attributes?.map(a => `${a.attributeName}: ${a.value}`).join(' | ') || ''}
//                       </Typography>
//                     </TableCell>
//                   </TableRow>
//                 )
//               })}
//             </TableBody>
//           </Table>
//         </TableContainer>

//         {/* Show count of selected variations */}
//         {activeVariations.length > 0 && (
//           <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
//             <Typography variant="body2" color="primary.main" fontWeight={600}>
//               {activeVariations.length} variation(s) selected
//             </Typography>
//           </Box>
//         )}
//       </DialogContent>

//       <DialogActions sx={{ p: 3, gap: 2, borderTop: '1px solid', borderColor: 'divider' }}>
//         <Button variant="outlined" onClick={onClose} disabled={loading}>
//           Cancel
//         </Button>
//         <Button
//           variant="contained"
//           onClick={handleAddToOrder}
//           disabled={loading || activeVariations.length === 0}
//           startIcon={loading ? <CircularProgress size={16} color="inherit" /> : null}
//         >
//           {loading ? 'Processing...' : isEdit ? 'Update Item' : 'Add Item'}
//         </Button>
//       </DialogActions>
//     </Dialog>
//   )
// }

// export default ProductDialog


// product issue solved 
// import React, { useState, useEffect } from 'react'

// // ** MUI Imports
// import {
//   Dialog,
//   DialogTitle,
//   DialogContent,
//   DialogActions,
//   Box,
//   Typography,
//   Button,
//   IconButton,
//   TextField,
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   Paper,
//   CircularProgress,
//   Chip,
//   FormControl,
//   Select,
//   MenuItem,
//   OutlinedInput
// } from '@mui/material'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// // ** Redux
// import { useDispatch, useSelector } from 'react-redux'
// import { addToCart, updateQuantity } from 'src/store/pages/pos/cartSlice'
// import { RootState } from 'src/store'

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''
//   if (path.startsWith('http://') || path.startsWith('https://')) return path
//   if (path.startsWith('blob:') || path.startsWith('data:')) return path
//   const cleanPath = path.startsWith('/') ? path : `/${path}`
//   return `${cleanPath}`
// }

// const getVariationImage = (variation: any): string => {
//   if (!variation) return ''
//   const images = variation.variationImages || []
//   if (images.length === 0) return ''
//   const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
//   return imageUrl ? getFullImageUrl(imageUrl) : ''
// }

// interface Variation {
//   uid: string
//   sku: string
//   mrp: number
//   stockQty: number | null
//   quantity: number
//   unit: string
//   calAmount: number
//   finalAmount: number
//   variationImages: any[]
//   attributes: any[]
// }

// interface Product {
//   uid: string
//   name: string
//   description?: string
//   productType?: string
//   isInventoryManaged?: boolean
//   variations: Variation[]
//   staffs?: any[]
// }

// interface ProductDialogProps {
//   open: boolean
//   onClose: () => void
//   product: Product | null
//   editItem?: any
//   isEdit?: boolean
// }

// // Image component with authentication
// const AuthImageComponent: React.FC<{ src: string; alt: string; style?: React.CSSProperties }> = ({ src, alt, style }) => {
//   const [imageSrc, setImageSrc] = useState<string>('')
//   const [loading, setLoading] = useState(true)

//   useEffect(() => {
//     if (!src) {
//       setImageSrc('/images/placeholder.png')
//       setLoading(false)
//       return
//     }

//     const fetchImage = async () => {
//       try {
//         const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
//         const response = await axios.get(src, {
//           responseType: 'blob',
//           headers: {
//             'Authorization': `Bearer ${token}`
//           }
//         })

//         const blob = response.data
//         const url = URL.createObjectURL(blob)
//         setImageSrc(url)
//         setLoading(false)
//       } catch (error) {
//         console.error('Error loading image:', error)
//         setImageSrc(src)
//         setLoading(false)
//       }
//     }

//     fetchImage()

//     return () => {
//       if (imageSrc && imageSrc.startsWith('blob:')) {
//         URL.revokeObjectURL(imageSrc)
//       }
//     }
//   }, [src])

//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <CircularProgress size={24} />
//       </Box>
//     )
//   }

//   return (
//     <img
//       src={imageSrc || '/images/placeholder.png'}
//       alt={alt}
//       style={style}
//       onError={(e) => {
//         e.currentTarget.src = '/images/placeholder.png'
//       }}
//     />
//   )
// }

// const ProductDialog: React.FC<ProductDialogProps> = ({ 
//   open, 
//   onClose, 
//   product, 
//   editItem = null,
//   isEdit = false 
// }) => {
//   const dispatch = useDispatch()
//   const cartEntities = useSelector((state: RootState) => state.cartSlice.entities)
//   const productList = useSelector((state: RootState) => state.pos.list)
  
//   const [loading, setLoading] = useState(false)
//   const [selectedVariation, setSelectedVariation] = useState<Variation | null>(null)
//   const [orderItemUid, setOrderItemUid] = useState<string>('')
//   const [posUid, setPosUid] = useState<string>('')
//   const [orderUid, setOrderUid] = useState<string>('')
  
//   // Store quantities for each variation
//   const [quantities, setQuantities] = useState<{ [key: string]: number }>({})
  
//   // Staff selection for service-based products
//   const [selectedStaff, setSelectedStaff] = useState<{ [key: string]: string[] }>({})
//   const [availableStaff, setAvailableStaff] = useState<any[]>([])

//   // ✅ Get fresh product data from Redux store
//   const freshProduct = React.useMemo(() => {
//     if (!product) return null
//     // Find the product in the list with updated stock
//     const found = productList.find(p => p.uid === product.uid)
//     return found || product
//   }, [product, productList])

//   const isServiceBased = freshProduct?.productType === 'ServiceBased'
//   const isReadyToSell = freshProduct?.productType === 'ReadyToSell'
//   const isInventoryNotManaged = freshProduct?.isInventoryManaged === false

//   // Initialize with edit data if in edit mode - ✅ Use freshProduct
//   useEffect(() => {
//     if (!freshProduct) return

//     if (isEdit && editItem) {
//       const variation = freshProduct.variations.find(v => v.uid === editItem.id)
//       if (variation) {
//         setSelectedVariation(variation)
//         setQuantities({
//           [variation.uid]: editItem.quantity || 1
//         })
//         if (isServiceBased && editItem.selectedStaff) {
//           setSelectedStaff({
//             [variation.uid]: editItem.selectedStaff
//           })
//         }
//       }
//       setOrderItemUid(editItem.orderItemUid || '')
//       setPosUid(editItem.posUid || '')
//       setOrderUid(editItem.orderUid || '')
//     } else if (freshProduct.variations.length > 0) {
//       const initialQuantities: { [key: string]: number } = {}
//       const initialStaff: { [key: string]: string[] } = {}
      
//       freshProduct.variations.forEach(v => {
//         if (isServiceBased) {
//           initialQuantities[v.uid] = 0
//         } else if (isReadyToSell && isInventoryNotManaged) {
//           initialQuantities[v.uid] = 0
//         } else if (isReadyToSell && freshProduct.isInventoryManaged && v.stockQty === 0) {
//           initialQuantities[v.uid] = 0
//         } else {
//           initialQuantities[v.uid] = 0
//         }
//         initialStaff[v.uid] = []
//       })
      
//       setQuantities(initialQuantities)
//       setSelectedStaff(initialStaff)
//       setSelectedVariation(freshProduct.variations[0])
      
//       if (isServiceBased && freshProduct.staffs) {
//         setAvailableStaff(freshProduct.staffs)
//       }
//     }
//   }, [freshProduct, editItem, isEdit, open, isServiceBased, isReadyToSell, isInventoryNotManaged])

//   // Reset when dialog closes
//   useEffect(() => {
//     if (!open) {
//       setSelectedVariation(null)
//       setOrderItemUid('')
//       setPosUid('')
//       setOrderUid('')
//       setQuantities({})
//       setSelectedStaff({})
//       setAvailableStaff([])
//     }
//   }, [open])

//   // Check if variation already exists in cart
//   const findExistingCartItem = (variationUid: string): any => {
//     const cartItems = Object.values(cartEntities) as any[]
//     return cartItems.find(item => item.id === variationUid)
//   }

//   // Fetch order details to get the actual item UID
//   const fetchOrderDetails = async (orderUid: string): Promise<{ itemUid: string, posUid: string, orderUid: string }> => {
//     try {
//       const response = await axios.get(`${endpoints.pos.posOrder.get}${orderUid}`)
//       console.log('Order details response:', response.data)
      
//       const orderData = response.data?.content?.result || response.data?.content || response.data
      
//       let itemUid = orderUid
//       let posUid = orderUid
//       let orderUidFromResponse = orderUid
      
//       if (orderData) {
//         orderUidFromResponse = orderData.uid || orderData.orderUid || orderUid
//         posUid = orderData.uid || orderData.orderUid || orderUid
        
//         if (orderData.items && orderData.items.length > 0) {
//           itemUid = orderData.items[0].uid || orderData.items[0].itemUid || posUid
//         } else if (orderData.itemUid) {
//           itemUid = orderData.itemUid
//         } else if (orderData.variationUid) {
//           itemUid = orderData.variationUid
//         }
//       }
      
//       return { itemUid, posUid, orderUid: orderUidFromResponse }
//     } catch (error) {
//       console.error('Error fetching order details:', error)
//       return { itemUid: orderUid, posUid: orderUid, orderUid: orderUid }
//     }
//   }

//   // Get the variations with quantity > 0
//   const getActiveVariations = () => {
//     if (!freshProduct) return []
    
//     const activeVariations: { variation: Variation, quantity: number }[] = []
//     for (const v of freshProduct.variations) {
//       const qty = quantities[v.uid] || 0
//       if (qty > 0) {
//         activeVariations.push({ variation: v, quantity: qty })
//       }
//     }
//     return activeVariations
//   }

//   // Get quantity for a specific variation
//   const getQuantity = (variationUid: string): number => {
//     return quantities[variationUid] || 0
//   }

//   // Get selected staff for a variation
//   const getSelectedStaff = (variationUid: string): string[] => {
//     return selectedStaff[variationUid] || []
//   }

//   // Check if quantity controls should be disabled (hide +/- buttons)
//   const shouldDisableQuantityControls = (variation: Variation): boolean => {
//     if (isServiceBased) return true
//     if (isReadyToSell && isInventoryNotManaged) {
//       return true
//     }
//     if (isReadyToSell && freshProduct?.isInventoryManaged && variation.stockQty === 0) {
//       return true
//     }
//     return false
//   }

//   // Check if stock should show "Out of Stock" (only for inventory managed with stock 0)
//   const shouldShowOutOfStock = (variation: Variation): boolean => {
//     return isReadyToSell && freshProduct?.isInventoryManaged && variation.stockQty === 0
//   }

//   // Check if quantity should be fixed to 1 (no controls, just display)
//   const shouldShowFixedQuantity = (variation: Variation): boolean => {
//     if (isServiceBased) return true
//     if (isReadyToSell && isInventoryNotManaged) {
//       return true
//     }
//     return false
//   }

//   // Toggle variation selection (for inventory not managed)
//   const toggleVariationSelection = (variationUid: string) => {
//     if (!isReadyToSell || !isInventoryNotManaged) return
    
//     const currentQty = getQuantity(variationUid)
//     handleQuantityChange(variationUid, currentQty === 0 ? 1 : 0)
//   }

//   // Handle quantity change for a specific variation
//   const handleQuantityChange = (variationUid: string, newQuantity: number) => {
//     const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//     if (!variation) return
    
//     if (shouldDisableQuantityControls(variation)) {
//       if (isReadyToSell && isInventoryNotManaged) {
//         if (newQuantity > 1) return
//         if (newQuantity < 0) return
//       } else {
//         return
//       }
//     }
    
//     if (newQuantity < 0) return
    
//     if (variation.stockQty && newQuantity > variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
    
//     setQuantities(prev => ({
//       ...prev,
//       [variationUid]: newQuantity
//     }))
    
//     if (newQuantity > 0) {
//       const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//       if (variation) {
//         setSelectedVariation(variation)
//       }
//     }
//   }

//   // Handle staff selection for service-based products
//   const handleStaffChange = (variationUid: string, staffUids: string[]) => {
//     setSelectedStaff(prev => ({
//       ...prev,
//       [variationUid]: staffUids
//     }))
    
//     if (isServiceBased) {
//       const staffCount = staffUids.length
//       setQuantities(prev => ({
//         ...prev,
//         [variationUid]: staffCount > 0 ? 1 : 0
//       }))
//     }
//   }

//   const handleDecrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//     if (!variation || shouldDisableQuantityControls(variation)) return
    
//     const currentQty = getQuantity(variationUid)
//     if (currentQty > 0) {
//       handleQuantityChange(variationUid, currentQty - 1)
//     }
//   }

//   const handleIncrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//     if (!variation || shouldDisableQuantityControls(variation)) return
    
//     const currentQty = getQuantity(variationUid)
//     if (variation.stockQty && currentQty >= variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
//     handleQuantityChange(variationUid, currentQty + 1)
//   }

//   const handleQtyInputChange = (e: React.ChangeEvent<HTMLInputElement>, variationUid: string) => {
//     const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//     if (!variation || shouldDisableQuantityControls(variation)) return
    
//     e.stopPropagation()
//     const val = parseInt(e.target.value)
//     if (!isNaN(val) && val >= 0) {
//       handleQuantityChange(variationUid, val)
//     }
//   }

//   const handleAddToOrder = async () => {
//     const activeVariations = getActiveVariations()
    
//     if (activeVariations.length === 0) {
//       toast.error('Please select at least one variation', { style: { zIndex: 999999 } })
//       return
//     }

//     setLoading(true)

//     try {
//       if (isEdit && editItem) {
//         const firstActive = activeVariations[0]
//         if (!orderItemUid) {
//           toast.error('Order item UID is missing. Please try again.', { style: { zIndex: 999999 } })
//           setLoading(false)
//           return
//         }
//         const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${orderItemUid}?quantity=${firstActive.quantity}`
//         await axios.put(updateUrl)
        
//         dispatch(updateQuantity({ 
//           id: firstActive.variation.uid, 
//           quantity: firstActive.quantity 
//         }))
        
//         toast.success('Item updated successfully!', { style: { zIndex: 999999 } })
//         onClose()
//       } else {
//         for (const active of activeVariations) {
//           const existingItem = findExistingCartItem(active.variation.uid)
          
//           if (existingItem) {
//             const existingOrderItemUid = existingItem.orderItemUid
//             if (!existingOrderItemUid) {
//               toast.error('Order item UID is missing for existing item', { style: { zIndex: 999999 } })
//               continue
//             }
            
//             const newQuantity = existingItem.quantity + active.quantity
//             const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${existingOrderItemUid}?quantity=${newQuantity}`
//             await axios.put(updateUrl)
            
//             dispatch(updateQuantity({ 
//               id: active.variation.uid, 
//               quantity: newQuantity 
//             }))
            
//             toast.success(`Item quantity updated to ${newQuantity}!`, { style: { zIndex: 999999 } })
//           } else {
//             let payload: any = {}
            
//             if (isServiceBased) {
//               const staffUids = getSelectedStaff(active.variation.uid)
//               if (staffUids.length === 0) {
//                 toast.error('Please select at least one staff member', { style: { zIndex: 999999 } })
//                 setLoading(false)
//                 return
//               }
              
//               payload = {
//                 items: staffUids.map(staffUid => ({
//                   staffUid: staffUid,
//                   variationUid: active.variation.uid,
//                   quantity: 1
//                 })),
//                 productType: freshProduct?.productType || 'ServiceBased'
//               }
//             } else {
//               payload = {
//                 items: [{
//                   variationUid: active.variation.uid,
//                   quantity: active.quantity
//                 }],
//                 productType: freshProduct?.productType || 'ReadyToSell'
//               }
//             }
            
//             const response = await axios.post(endpoints.pos.posOrder.create, payload)
//             const orderData = response.data
            
//             if (orderData) {
//               const orderUid = orderData.uid || orderData.orderUid || ''
//               const { itemUid, posUid: fetchedPosUid, orderUid: fetchedOrderUid } = await fetchOrderDetails(orderUid)
              
//               // ✅ Use fresh product data for stock
//               const variation = freshProduct?.variations.find(v => v.uid === active.variation.uid)
              
//               dispatch(addToCart({
//                 id: active.variation.uid,
//                 productUid: freshProduct?.uid || '',
//                 name: freshProduct?.name || '',
//                 price: active.variation.mrp,
//                 quantity: isServiceBased ? getSelectedStaff(active.variation.uid).length : active.quantity,
//                 image: getVariationImage(active.variation),
//                 variation: active.variation,
//                 orderItemUid: itemUid,
//                 posUid: fetchedPosUid,
//                 orderUid: fetchedOrderUid,
//                 stockQty: variation?.stockQty || 0,
//                 productType: freshProduct?.productType || 'ReadyToSell',
//                 isInventoryManaged: freshProduct?.isInventoryManaged || false,
//                 ...(isServiceBased && {
//                   selectedStaff: getSelectedStaff(active.variation.uid)
//                 })
//               }))
//             }
//           }
//         }
        
//         toast.success(`${activeVariations.length} item(s) added to order!`, { style: { zIndex: 999999 } })
//         onClose()
//       }
//     } catch (error: any) {
//       console.error('Error:', error)
//       toast.error(error?.response?.data?.message || 'Failed to process item', { 
//         style: { zIndex: 999999 } 
//       })
//     } finally {
//       setLoading(false)
//     }
//   }

//   if (!freshProduct) return null

//   // Get price range for display
//   const prices = freshProduct.variations.map(v => v.mrp)
//   const minPrice = Math.min(...prices)
//   const maxPrice = Math.max(...prices)
//   const priceDisplay = minPrice === maxPrice ? `$${minPrice.toFixed(2)}` : `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`

//   const activeVariations = getActiveVariations()

//   return (
//     <Dialog 
//       open={open} 
//       onClose={onClose} 
//       maxWidth="md" 
//       fullWidth
//       PaperProps={{
//         sx: { borderRadius: 2, zIndex: 999999 }
//       }}
//     >
//       <DialogTitle sx={{ 
//         display: 'flex', 
//         justifyContent: 'space-between', 
//         alignItems: 'center',
//         borderBottom: '1px solid',
//         borderColor: 'divider',
//         pb: 2
//       }}>
//         <Box>
//           <Typography variant="h6">{freshProduct.name}</Typography>
//           <Typography variant="body2" color="text.secondary">
//             {isEdit ? 'Edit Item' : 'Add to Order'}
//             {freshProduct.productType && (
//               <Chip 
//                 label={freshProduct.productType} 
//                 size="small" 
//                 color={freshProduct.productType === 'ServiceBased' ? 'secondary' : 'primary'}
//                 sx={{ ml: 1 }}
//               />
//             )}
//           </Typography>
//         </Box>
//         <IconButton onClick={onClose}>
//           <Icon icon="tabler:x" />
//         </IconButton>
//       </DialogTitle>

//       <DialogContent sx={{ pt: 3 }}>
//         <Box sx={{ mb: 3 }}>
//           <Typography variant="body2" color="text.secondary">
//             Product Description: {freshProduct.description || 'No description available'}
//           </Typography>
//           <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1 }}>
//             Price Range: {priceDisplay}
//           </Typography>
//         </Box>

//         <Typography variant="subtitle2" sx={{ mb: 2 }}>
//           Select Variation{isInventoryNotManaged && ' (Click row to select/deselect)'}
//         </Typography>
//         <TableContainer component={Paper} sx={{ maxHeight: 300 }}>
//           <Table size="small" stickyHeader>
//             <TableHead>
//               <TableRow>
//                 {!isServiceBased && <TableCell>SKU</TableCell>}
//                 <TableCell>Image</TableCell>
//                 {!isServiceBased && <TableCell>Stock</TableCell>}
//                 <TableCell>Amount</TableCell>
//                 <TableCell>{isServiceBased ? 'Staff Members' : 'QTY'}</TableCell>
//                 <TableCell>Final</TableCell>
//                 <TableCell>Attributes</TableCell>
//               </TableRow>
//             </TableHead>
//             <TableBody>
//               {freshProduct.variations.map((variation) => {
//                 const imageUrl = getVariationImage(variation)
//                 const qty = getQuantity(variation.uid)
//                 const selectedStaffUids = getSelectedStaff(variation.uid)
//                 const showOutOfStock = shouldShowOutOfStock(variation)
//                 const showFixedQty = shouldShowFixedQuantity(variation)
//                 const disableControls = shouldDisableQuantityControls(variation)
//                 const isSelected = qty > 0
                
//                 let finalAmount = variation.mrp * qty
//                 if (isServiceBased) {
//                   finalAmount = variation.mrp * selectedStaffUids.length
//                 }
                
//                 const isRowClickable = isReadyToSell && isInventoryNotManaged
                
//                 return (
//                   <TableRow 
//                     key={variation.uid}
//                     onClick={() => {
//                       if (isRowClickable) {
//                         toggleVariationSelection(variation.uid)
//                       }
//                     }}
//                     sx={{ 
//                       bgcolor: isSelected ? 'primary.light' : 'inherit',
//                       cursor: isRowClickable ? 'pointer' : 'default',
//                       '&:hover': { 
//                         bgcolor: isSelected ? 'primary.main' : 'action.hover',
//                         '& .MuiTypography-root': {
//                           color: isSelected ? 'white' : 'inherit'
//                         }
//                       },
//                       transition: 'background-color 0.2s ease'
//                     }}
//                   >
//                     {!isServiceBased && (
//                       <TableCell>
//                         <Typography variant="body2" fontWeight={500}>
//                           {variation.sku || 'N/A'}
//                         </Typography>
//                       </TableCell>
//                     )}
//                     <TableCell>
//                       <Box
//                         sx={{
//                           width: 40,
//                           height: 40,
//                           borderRadius: 1,
//                           overflow: 'hidden',
//                           display: 'flex',
//                           alignItems: 'center',
//                           justifyContent: 'center',
//                           bgcolor: 'grey.100'
//                         }}
//                       >
//                         {imageUrl ? (
//                           <AuthImageComponent
//                             src={imageUrl}
//                             alt=""
//                             style={{
//                               width: '100%',
//                               height: '100%',
//                               objectFit: 'cover'
//                             }}
//                           />
//                         ) : (
//                           <Typography variant="caption" color="text.secondary">N/A</Typography>
//                         )}
//                       </Box>
//                     </TableCell>
//                     {!isServiceBased && (
//                       <TableCell>
//                         {showOutOfStock ? (
//                           <Typography variant="body2" color="error" fontWeight="bold">
//                             Out of Stock
//                           </Typography>
//                         ) : (
//                           <Typography variant="body2">
//                             {variation.stockQty ?? 'N/A'}
//                           </Typography>
//                         )}
//                       </TableCell>
//                     )}
//                     <TableCell>${variation.mrp.toFixed(2)}</TableCell>
//                     <TableCell>
//                       {isServiceBased ? (
//                         <FormControl size="small" sx={{ minWidth: 150 }}>
//                           <Select
//                             multiple
//                             value={selectedStaffUids}
//                             onChange={(e) => handleStaffChange(variation.uid, e.target.value as string[])}
//                             input={<OutlinedInput size="small" />}
//                             renderValue={(selected) => {
//                               const selectedNames = availableStaff
//                                 .filter(s => (selected as string[]).includes(s.uid))
//                                 .map(s => `${s.firstName} ${s.lastName}`)
//                               return selectedNames.join(', ') || 'Select staff'
//                             }}
//                             disabled={loading}
//                           >
//                             {availableStaff.map((staff) => (
//                               <MenuItem key={staff.uid} value={staff.uid}>
//                                 <Typography variant="body2">
//                                   {staff.firstName} {staff.lastName}
//                                 </Typography>
//                               </MenuItem>
//                             ))}
//                           </Select>
//                         </FormControl>
//                       ) : isInventoryNotManaged ? (
//                         <Typography 
//                           variant="body2" 
//                           fontWeight={isSelected ? 600 : 400}
//                           color={isSelected ? 'primary.main' : 'text.secondary'}
//                           sx={{ textAlign: 'center' }}
//                         >
//                           {qty}
//                         </Typography>
//                       ) : showFixedQty ? (
//                         <Typography variant="body2" fontWeight={500} sx={{ px: 2, py: 1, textAlign: 'center' }}>
//                           {qty}
//                         </Typography>
//                       ) : disableControls ? (
//                         <Typography variant="body2" color="text.secondary" sx={{ px: 2, py: 1, textAlign: 'center' }}>
//                           {qty}
//                         </Typography>
//                       ) : (
//                         <Box sx={{ display: 'flex', alignItems: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
//                           <IconButton 
//                             size="small" 
//                             onClick={(e) => handleDecrementQty(e, variation.uid)}
//                             disabled={qty <= 0}
//                             sx={{ borderRadius: 0, px: 1 }}
//                           >
//                             <Icon icon="tabler:minus" fontSize="small" />
//                           </IconButton>
//                           <TextField
//                             type="number"
//                             value={qty}
//                             onChange={(e) => handleQtyInputChange(e as React.ChangeEvent<HTMLInputElement>, variation.uid)}
//                             onClick={(e) => e.stopPropagation()}
//                             inputProps={{ 
//                               style: { textAlign: 'center', width: 40, padding: '4px 0' },
//                               min: 0,
//                               max: variation.stockQty || 999
//                             }}
//                             variant="standard"
//                             size="small"
//                             sx={{ 
//                               '& .MuiInput-underline:before': { borderBottom: 'none' },
//                               '& .MuiInput-underline:after': { borderBottom: 'none' },
//                               '& .MuiInput-root': { '&:before': { borderBottom: 'none' } }
//                             }}
//                             disabled={loading}
//                           />
//                           <IconButton 
//                             size="small" 
//                             onClick={(e) => handleIncrementQty(e, variation.uid)}
//                             disabled={variation.stockQty ? qty >= variation.stockQty : false}
//                             sx={{ borderRadius: 0, px: 1 }}
//                           >
//                             <Icon icon="tabler:plus" fontSize="small" />
//                           </IconButton>
//                         </Box>
//                       )}
//                     </TableCell>
//                     <TableCell sx={{ fontWeight: 600, color: isSelected ? 'primary.main' : 'text.secondary' }}>
//                       ${finalAmount.toFixed(2)}
//                     </TableCell>
//                     <TableCell>
//                       <Typography variant="caption" color="text.secondary">
//                         {variation.attributes?.map(a => `${a.attributeName}: ${a.value}`).join(' | ') || ''}
//                       </Typography>
//                     </TableCell>
//                   </TableRow>
//                 )
//               })}
//             </TableBody>
//           </Table>
//         </TableContainer>

//         {activeVariations.length > 0 && (
//           <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
//             <Typography variant="body2" color="primary.main" fontWeight={600}>
//               {activeVariations.length} variation(s) selected
//             </Typography>
//           </Box>
//         )}
//       </DialogContent>

//       <DialogActions sx={{ p: 3, gap: 2, borderTop: '1px solid', borderColor: 'divider' }}>
//         <Button variant="outlined" onClick={onClose} disabled={loading}>
//           Cancel
//         </Button>
//         <Button
//           variant="contained"
//           onClick={handleAddToOrder}
//           disabled={loading || activeVariations.length === 0}
//           startIcon={loading ? <CircularProgress size={16} color="inherit" /> : null}
//         >
//           {loading ? 'Processing...' : isEdit ? 'Update Item' : 'Add Item'}
//         </Button>
//       </DialogActions>
//     </Dialog>
//   )
// }

// export default ProductDialog


// image issue 
// import React, { useState, useEffect } from 'react'

// // ** MUI Imports
// import {
//   Dialog,
//   DialogTitle,
//   DialogContent,
//   DialogActions,
//   Box,
//   Typography,
//   Button,
//   IconButton,
//   TextField,
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   Paper,
//   CircularProgress,
//   Chip,
//   FormControl,
//   Select,
//   MenuItem,
//   OutlinedInput,
//   Tooltip
// } from '@mui/material'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// // ** Redux
// import { useDispatch, useSelector } from 'react-redux'
// import { addToCart, updateQuantity } from 'src/store/pages/pos/cartSlice'
// import { RootState } from 'src/store'

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''
//   if (path.startsWith('http://') || path.startsWith('https://')) return path
//   if (path.startsWith('blob:') || path.startsWith('data:')) return path
//   const cleanPath = path.startsWith('/') ? path : `/${path}`
//   return `${cleanPath}`
// }

// const getVariationImage = (variation: any): string => {
//   if (!variation) return ''
//   const images = variation.variationImages || []
//   if (images.length === 0) return ''
//   const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
//   return imageUrl ? getFullImageUrl(imageUrl) : ''
// }

// interface Variation {
//   uid: string
//   sku: string
//   mrp: number
//   stockQty: number | null
//   quantity: number
//   unit: string
//   calAmount: number
//   finalAmount: number
//   variationImages: any[]
//   attributes: any[]
// }

// interface Product {
//   uid: string
//   name: string
//   description?: string
//   productType?: string
//   isInventoryManaged?: boolean
//   variations: Variation[]
//   staffs?: any[]
// }

// interface ProductDialogProps {
//   open: boolean
//   onClose: () => void
//   product: Product | null
//   editItem?: any
//   isEdit?: boolean
// }

// // Image component with authentication - FIXED
// const AuthImageComponent: React.FC<{ src: string; alt: string; style?: React.CSSProperties }> = ({ src, alt, style }) => {
//   const [imageSrc, setImageSrc] = useState<string | null>(null)
//   const [loading, setLoading] = useState(true)
//   const [error, setError] = useState(false)

//   useEffect(() => {
//     let objectUrl: string | null = null
//     let isMounted = true

//     const fetchImage = async () => {
//       // Reset states when src changes
//       setLoading(true)
//       setError(false)
//       setImageSrc(null)

//       // If no src is provided, show fallback without loading
//       if (!src) {
//         if (isMounted) {
//           setLoading(false)
//           setError(true)
//           setImageSrc(null)
//         }
//         return
//       }

//       try {
//         const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
//         const response = await axios.get(src, {
//           responseType: 'blob',
//           headers: {
//             'Authorization': `Bearer ${token}`
//           },
//           timeout: 10000 // 10 second timeout
//         })

//         if (!isMounted) return

//         const blob = response.data
//         // Revoke previous object URL if exists
//         if (objectUrl) {
//           URL.revokeObjectURL(objectUrl)
//         }
//         objectUrl = URL.createObjectURL(blob)
        
//         if (isMounted) {
//           setImageSrc(objectUrl)
//           setLoading(false)
//           setError(false)
//         }
//       } catch (err) {
//         console.error('Error loading image:', err)
//         if (isMounted) {
//           setLoading(false)
//           setError(true)
//           setImageSrc(null)
//         }
//       }
//     }

//     fetchImage()

//     // Cleanup function
//     return () => {
//       isMounted = false
//       if (objectUrl) {
//         URL.revokeObjectURL(objectUrl)
//       }
//     }
//   }, [src]) // Only re-run when src changes

//   // Render loading state
//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <CircularProgress size={24} />
//       </Box>
//     )
//   }

//   // Render error/fallback state - NO IMAGE REQUEST
//   if (error || !imageSrc) {
//     return (
//       <Box 
//         sx={{ 
//           width: '100%', 
//           height: '100%', 
//           display: 'flex', 
//           alignItems: 'center', 
//           justifyContent: 'center',
//           bgcolor: 'grey.100',
//           borderRadius: 1
//         }}
//       >
//         <Icon icon="tabler:photo-off" fontSize={24} color="action" />
//       </Box>
//     )
//   }

//   // Render image with error handling that doesn't trigger network requests
//   return (
//     <img
//       src={imageSrc}
//       alt={alt}
//       style={style}
//       onError={(e) => {
//         // Prevent infinite error loops
//         e.currentTarget.style.display = 'none'
//         setError(true)
//         setImageSrc(null)
//       }}
//     />
//   )
// }

// const ProductDialog: React.FC<ProductDialogProps> = ({ 
//   open, 
//   onClose, 
//   product, 
//   editItem = null,
//   isEdit = false 
// }) => {
//   const dispatch = useDispatch()
//   const cartEntities = useSelector((state: RootState) => state.cartSlice.entities)
//   const productList = useSelector((state: RootState) => state.pos.list)
  
//   const [loading, setLoading] = useState(false)
//   const [selectedVariation, setSelectedVariation] = useState<Variation | null>(null)
//   const [orderItemUid, setOrderItemUid] = useState<string>('')
//   const [posUid, setPosUid] = useState<string>('')
//   const [orderUid, setOrderUid] = useState<string>('')
  
//   // Store quantities for each variation
//   const [quantities, setQuantities] = useState<{ [key: string]: number }>({})
  
//   // Staff selection for service-based products
//   const [selectedStaff, setSelectedStaff] = useState<{ [key: string]: string[] }>({})
//   const [availableStaff, setAvailableStaff] = useState<any[]>([])

//   // ✅ Get fresh product data from Redux store
//   const freshProduct = React.useMemo(() => {
//     if (!product) return null
//     // Find the product in the list with updated stock
//     const found = productList.find(p => p.uid === product.uid)
//     return found || product
//   }, [product, productList])

//   const isServiceBased = freshProduct?.productType === 'ServiceBased'
//   const isReadyToSell = freshProduct?.productType === 'ReadyToSell'
//   const isInventoryNotManaged = freshProduct?.isInventoryManaged === false

//   // Initialize with edit data if in edit mode - ✅ Use freshProduct
//   useEffect(() => {
//     if (!freshProduct) return

//     if (isEdit && editItem) {
//       const variation = freshProduct.variations.find(v => v.uid === editItem.id)
//       if (variation) {
//         setSelectedVariation(variation)
//         setQuantities({
//           [variation.uid]: editItem.quantity || 1
//         })
//         if (isServiceBased && editItem.selectedStaff) {
//           setSelectedStaff({
//             [variation.uid]: editItem.selectedStaff
//           })
//         }
//       }
//       setOrderItemUid(editItem.orderItemUid || '')
//       setPosUid(editItem.posUid || '')
//       setOrderUid(editItem.orderUid || '')
//     } else if (freshProduct.variations.length > 0) {
//       const initialQuantities: { [key: string]: number } = {}
//       const initialStaff: { [key: string]: string[] } = {}
      
//       freshProduct.variations.forEach(v => {
//         if (isServiceBased) {
//           initialQuantities[v.uid] = 0
//         } else if (isReadyToSell && isInventoryNotManaged) {
//           initialQuantities[v.uid] = 0
//         } else if (isReadyToSell && freshProduct.isInventoryManaged && v.stockQty === 0) {
//           initialQuantities[v.uid] = 0
//         } else {
//           initialQuantities[v.uid] = 0
//         }
//         initialStaff[v.uid] = []
//       })
      
//       setQuantities(initialQuantities)
//       setSelectedStaff(initialStaff)
//       setSelectedVariation(freshProduct.variations[0])
      
//       if (isServiceBased && freshProduct.staffs) {
//         setAvailableStaff(freshProduct.staffs)
//       }
//     }
//   }, [freshProduct, editItem, isEdit, open, isServiceBased, isReadyToSell, isInventoryNotManaged])

//   // Reset when dialog closes
//   useEffect(() => {
//     if (!open) {
//       setSelectedVariation(null)
//       setOrderItemUid('')
//       setPosUid('')
//       setOrderUid('')
//       setQuantities({})
//       setSelectedStaff({})
//       setAvailableStaff([])
//     }
//   }, [open])

//   // Check if variation already exists in cart
//   const findExistingCartItem = (variationUid: string): any => {
//     const cartItems = Object.values(cartEntities) as any[]
//     return cartItems.find(item => item.id === variationUid)
//   }

//   // Fetch order details to get the actual item UID
//   const fetchOrderDetails = async (orderUid: string): Promise<{ itemUid: string, posUid: string, orderUid: string }> => {
//     try {
//       const response = await axios.get(`${endpoints.pos.posOrder.get}${orderUid}`)
//       console.log('Order details response:', response.data)
      
//       const orderData = response.data?.content?.result || response.data?.content || response.data
      
//       let itemUid = orderUid
//       let posUid = orderUid
//       let orderUidFromResponse = orderUid
      
//       if (orderData) {
//         orderUidFromResponse = orderData.uid || orderData.orderUid || orderUid
//         posUid = orderData.uid || orderData.orderUid || orderUid
        
//         if (orderData.items && orderData.items.length > 0) {
//           itemUid = orderData.items[0].uid || orderData.items[0].itemUid || posUid
//         } else if (orderData.itemUid) {
//           itemUid = orderData.itemUid
//         } else if (orderData.variationUid) {
//           itemUid = orderData.variationUid
//         }
//       }
      
//       return { itemUid, posUid, orderUid: orderUidFromResponse }
//     } catch (error) {
//       console.error('Error fetching order details:', error)
//       return { itemUid: orderUid, posUid: orderUid, orderUid: orderUid }
//     }
//   }

//   // Get the variations with quantity > 0
//   const getActiveVariations = () => {
//     if (!freshProduct) return []
    
//     const activeVariations: { variation: Variation, quantity: number }[] = []
//     for (const v of freshProduct.variations) {
//       const qty = quantities[v.uid] || 0
//       if (qty > 0) {
//         activeVariations.push({ variation: v, quantity: qty })
//       }
//     }
//     return activeVariations
//   }

//   // Get quantity for a specific variation
//   const getQuantity = (variationUid: string): number => {
//     return quantities[variationUid] || 0
//   }

//   // Get selected staff for a variation
//   const getSelectedStaff = (variationUid: string): string[] => {
//     return selectedStaff[variationUid] || []
//   }

//   // Check if quantity controls should be disabled (hide +/- buttons)
//   const shouldDisableQuantityControls = (variation: Variation): boolean => {
//     if (isServiceBased) return true
//     if (isReadyToSell && isInventoryNotManaged) {
//       return true
//     }
//     if (isReadyToSell && freshProduct?.isInventoryManaged && variation.stockQty === 0) {
//       return true
//     }
//     return false
//   }

//   // Check if stock should show "Out of Stock" (only for inventory managed with stock 0)
//   const shouldShowOutOfStock = (variation: Variation): boolean => {
//     return isReadyToSell && freshProduct?.isInventoryManaged && variation.stockQty === 0
//   }

//   // Check if quantity should be fixed to 1 (no controls, just display)
//   const shouldShowFixedQuantity = (variation: Variation): boolean => {
//     if (isServiceBased) return true
//     if (isReadyToSell && isInventoryNotManaged) {
//       return true
//     }
//     return false
//   }

//   // Toggle variation selection (for inventory not managed)
//   const toggleVariationSelection = (variationUid: string) => {
//     if (!isReadyToSell || !isInventoryNotManaged) return
    
//     const currentQty = getQuantity(variationUid)
//     handleQuantityChange(variationUid, currentQty === 0 ? 1 : 0)
//   }

//   // Handle quantity change for a specific variation
//   const handleQuantityChange = (variationUid: string, newQuantity: number) => {
//     const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//     if (!variation) return
    
//     if (shouldDisableQuantityControls(variation)) {
//       if (isReadyToSell && isInventoryNotManaged) {
//         if (newQuantity > 1) return
//         if (newQuantity < 0) return
//       } else {
//         return
//       }
//     }
    
//     if (newQuantity < 0) return
    
//     if (variation.stockQty && newQuantity > variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
    
//     setQuantities(prev => ({
//       ...prev,
//       [variationUid]: newQuantity
//     }))
    
//     if (newQuantity > 0) {
//       const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//       if (variation) {
//         setSelectedVariation(variation)
//       }
//     }
//   }

//   // Handle staff selection for service-based products
//   const handleStaffChange = (variationUid: string, staffUids: string[]) => {
//     setSelectedStaff(prev => ({
//       ...prev,
//       [variationUid]: staffUids
//     }))
    
//     if (isServiceBased) {
//       const staffCount = staffUids.length
//       setQuantities(prev => ({
//         ...prev,
//         [variationUid]: staffCount > 0 ? 1 : 0
//       }))
//     }
//   }

//   const handleDecrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//     if (!variation || shouldDisableQuantityControls(variation)) return
    
//     const currentQty = getQuantity(variationUid)
//     if (currentQty > 0) {
//       handleQuantityChange(variationUid, currentQty - 1)
//     }
//   }

//   const handleIncrementQty = (e: React.MouseEvent, variationUid: string) => {
//     e.stopPropagation()
//     const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//     if (!variation || shouldDisableQuantityControls(variation)) return
    
//     const currentQty = getQuantity(variationUid)
//     if (variation.stockQty && currentQty >= variation.stockQty) {
//       toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
//       return
//     }
//     handleQuantityChange(variationUid, currentQty + 1)
//   }

//   const handleQtyInputChange = (e: React.ChangeEvent<HTMLInputElement>, variationUid: string) => {
//     const variation = freshProduct?.variations.find(v => v.uid === variationUid)
//     if (!variation || shouldDisableQuantityControls(variation)) return
    
//     e.stopPropagation()
//     const val = parseInt(e.target.value)
//     if (!isNaN(val) && val >= 0) {
//       handleQuantityChange(variationUid, val)
//     }
//   }

//   const handleAddToOrder = async () => {
//     const activeVariations = getActiveVariations()
    
//     if (activeVariations.length === 0) {
//       toast.error('Please select at least one variation', { style: { zIndex: 999999 } })
//       return
//     }

//     setLoading(true)

//     try {
//       if (isEdit && editItem) {
//         const firstActive = activeVariations[0]
//         if (!orderItemUid) {
//           toast.error('Order item UID is missing. Please try again.', { style: { zIndex: 999999 } })
//           setLoading(false)
//           return
//         }
//         const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${orderItemUid}?quantity=${firstActive.quantity}`
//         await axios.put(updateUrl)
        
//         dispatch(updateQuantity({ 
//           id: firstActive.variation.uid, 
//           quantity: firstActive.quantity 
//         }))
        
//         toast.success('Item updated successfully!', { style: { zIndex: 999999 } })
//         onClose()
//       } else {
//         for (const active of activeVariations) {
//           const existingItem = findExistingCartItem(active.variation.uid)
          
//           if (existingItem) {
//             const existingOrderItemUid = existingItem.orderItemUid
//             if (!existingOrderItemUid) {
//               toast.error('Order item UID is missing for existing item', { style: { zIndex: 999999 } })
//               continue
//             }
            
//             const newQuantity = existingItem.quantity + active.quantity
//             const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${existingOrderItemUid}?quantity=${newQuantity}`
//             await axios.put(updateUrl)
            
//             dispatch(updateQuantity({ 
//               id: active.variation.uid, 
//               quantity: newQuantity 
//             }))
            
//             toast.success(`Item quantity updated to ${newQuantity}!`, { style: { zIndex: 999999 } })
//           } else {
//             let payload: any = {}
            
//             if (isServiceBased) {
//               const staffUids = getSelectedStaff(active.variation.uid)
//               if (staffUids.length === 0) {
//                 toast.error('Please select at least one staff member', { style: { zIndex: 999999 } })
//                 setLoading(false)
//                 return
//               }
              
//               payload = {
//                 items: staffUids.map(staffUid => ({
//                   staffUid: staffUid,
//                   variationUid: active.variation.uid,
//                   quantity: 1
//                 })),
//                 productType: freshProduct?.productType || 'ServiceBased'
//               }
//             } else {
//               payload = {
//                 items: [{
//                   variationUid: active.variation.uid,
//                   quantity: active.quantity
//                 }],
//                 productType: freshProduct?.productType || 'ReadyToSell'
//               }
//             }
            
//             const response = await axios.post(endpoints.pos.posOrder.create, payload)
//             const orderData = response.data
            
//             if (orderData) {
//               const orderUid = orderData.uid || orderData.orderUid || ''
//               const { itemUid, posUid: fetchedPosUid, orderUid: fetchedOrderUid } = await fetchOrderDetails(orderUid)
              
//               // ✅ Use fresh product data for stock
//               const variation = freshProduct?.variations.find(v => v.uid === active.variation.uid)
              
//               // Use finalAmount instead of mrp for the price
//               const itemPrice = active.variation.finalAmount || active.variation.mrp
              
//               dispatch(addToCart({
//                 id: active.variation.uid,
//                 productUid: freshProduct?.uid || '',
//                 name: freshProduct?.name || '',
//                 price: itemPrice,
//                 mrp: active.variation.mrp,
//                 taxAmount: active.variation.calAmount || 0,
//                 quantity: isServiceBased ? getSelectedStaff(active.variation.uid).length : active.quantity,
//                 image: getVariationImage(active.variation),
//                 variation: active.variation,
//                 orderItemUid: itemUid,
//                 posUid: fetchedPosUid,
//                 orderUid: fetchedOrderUid,
//                 stockQty: variation?.stockQty || 0,
//                 productType: freshProduct?.productType || 'ReadyToSell',
//                 isInventoryManaged: freshProduct?.isInventoryManaged || false,
//                 ...(isServiceBased && {
//                   selectedStaff: getSelectedStaff(active.variation.uid)
//                 })
//               }))
//             }
//           }
//         }
        
//         toast.success(`${activeVariations.length} item(s) added to order!`, { style: { zIndex: 999999 } })
//         onClose()
//       }
//     } catch (error: any) {
//       console.error('Error:', error)
//       toast.error(error?.response?.data?.message || 'Failed to process item', { 
//         style: { zIndex: 999999 } 
//       })
//     } finally {
//       setLoading(false)
//     }
//   }

//   if (!freshProduct) return null

//   // Get price range for display using finalAmount
//   const finalPrices = freshProduct.variations.map(v => v.finalAmount || v.mrp)
//   const minPrice = Math.min(...finalPrices)
//   const maxPrice = Math.max(...finalPrices)
//   const priceDisplay = minPrice === maxPrice ? `$${minPrice.toFixed(2)}` : `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`

//   const activeVariations = getActiveVariations()

//   return (
//     <Dialog 
//       open={open} 
//       onClose={onClose} 
//       maxWidth="md" 
//       fullWidth
//       PaperProps={{
//         sx: { borderRadius: 2, zIndex: 999999 }
//       }}
//     >
//       <DialogTitle sx={{ 
//         display: 'flex', 
//         justifyContent: 'space-between', 
//         alignItems: 'center',
//         borderBottom: '1px solid',
//         borderColor: 'divider',
//         pb: 2
//       }}>
//         <Box>
//           <Typography variant="h6">{freshProduct.name}</Typography>
//           <Typography variant="body2" color="text.secondary">
//             {isEdit ? 'Edit Item' : 'Add to Order'}
//             {freshProduct.productType && (
//               <Chip 
//                 label={freshProduct.productType} 
//                 size="small" 
//                 color={freshProduct.productType === 'ServiceBased' ? 'secondary' : 'primary'}
//                 sx={{ ml: 1 }}
//               />
//             )}
//           </Typography>
//         </Box>
//         <IconButton onClick={onClose}>
//           <Icon icon="tabler:x" />
//         </IconButton>
//       </DialogTitle>

//       <DialogContent sx={{ pt: 3 }}>
//         <Box sx={{ mb: 3 }}>
//           <Typography variant="body2" color="text.secondary">
//             Product Description: {freshProduct.description || 'No description available'}
//           </Typography>
//           <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1 }}>
//             Price Range: {priceDisplay}
//           </Typography>
//         </Box>

//         <Typography variant="subtitle2" sx={{ mb: 2 }}>
//           Select Variation{isInventoryNotManaged && ' (Click row to select/deselect)'}
//         </Typography>
//         <TableContainer component={Paper} sx={{ maxHeight: 300 }}>
//           <Table size="small" stickyHeader>
//             <TableHead>
//               <TableRow>
//                 {!isServiceBased && <TableCell>SKU</TableCell>}
//                 <TableCell>Image</TableCell>
//                 {!isServiceBased && <TableCell>Stock</TableCell>}
//                 <TableCell>Amount (Final)</TableCell>
//                 <TableCell>{isServiceBased ? 'Staff Members' : 'QTY'}</TableCell>
//                 <TableCell>Total</TableCell>
//                 <TableCell>Attributes</TableCell>
//               </TableRow>
//             </TableHead>
//             <TableBody>
//               {freshProduct.variations.map((variation) => {
//                 const imageUrl = getVariationImage(variation)
//                 const qty = getQuantity(variation.uid)
//                 const selectedStaffUids = getSelectedStaff(variation.uid)
//                 const showOutOfStock = shouldShowOutOfStock(variation)
//                 const showFixedQty = shouldShowFixedQuantity(variation)
//                 const disableControls = shouldDisableQuantityControls(variation)
//                 const isSelected = qty > 0
                
//                 // Calculate total using finalAmount
//                 const unitPrice = variation.finalAmount || variation.mrp
//                 let totalAmount = unitPrice * qty
//                 if (isServiceBased) {
//                   totalAmount = unitPrice * selectedStaffUids.length
//                 }
                
//                 const isRowClickable = isReadyToSell && isInventoryNotManaged
                
//                 return (
//                   <TableRow 
//                     key={variation.uid}
//                     onClick={() => {
//                       if (isRowClickable) {
//                         toggleVariationSelection(variation.uid)
//                       }
//                     }}
//                     sx={{ 
//                       bgcolor: isSelected ? 'primary.light' : 'inherit',
//                       cursor: isRowClickable ? 'pointer' : 'default',
//                       '&:hover': { 
//                         bgcolor: isSelected ? 'primary.main' : 'action.hover',
//                         '& .MuiTypography-root': {
//                           color: isSelected ? 'white' : 'inherit'
//                         }
//                       },
//                       transition: 'background-color 0.2s ease'
//                     }}
//                   >
//                     {!isServiceBased && (
//                       <TableCell>
//                         <Typography variant="body2" fontWeight={500}>
//                           {variation.sku || 'N/A'}
//                         </Typography>
//                       </TableCell>
//                     )}
//                     <TableCell>
//                       <Box
//                         sx={{
//                           width: 40,
//                           height: 40,
//                           borderRadius: 1,
//                           overflow: 'hidden',
//                           display: 'flex',
//                           alignItems: 'center',
//                           justifyContent: 'center',
//                           bgcolor: 'grey.100'
//                         }}
//                       >
//                         {imageUrl ? (
//                           <AuthImageComponent
//                             src={imageUrl}
//                             alt=""
//                             style={{
//                               width: '100%',
//                               height: '100%',
//                               objectFit: 'cover'
//                             }}
//                           />
//                         ) : (
//                           <Icon icon="tabler:photo-off" fontSize={20} color="action" />
//                         )}
//                       </Box>
//                     </TableCell>
//                     {!isServiceBased && (
//                       <TableCell>
//                         {showOutOfStock ? (
//                           <Typography variant="body2" color="error" fontWeight="bold">
//                             Out of Stock
//                           </Typography>
//                         ) : (
//                           <Typography variant="body2">
//                             {variation.stockQty ?? 'N/A'}
//                           </Typography>
//                         )}
//                       </TableCell>
//                     )}
//                     <TableCell>
//                       <Box>
//                         <Typography variant="body2" fontWeight={600} color="primary.main">
//                           ${(variation.finalAmount || variation.mrp).toFixed(2)}
//                         </Typography>
//                         {variation.calAmount > 0 && variation.mrp && (
//                           <Tooltip title={`MRP: $${variation.mrp.toFixed(2)} + Tax: $${variation.calAmount.toFixed(2)}`}>
//                             <Typography variant="caption" color="text.secondary" display="block">
//                               MRP: ${variation.mrp.toFixed(2)} + Tax: ${variation.calAmount.toFixed(2)}
//                             </Typography>
//                           </Tooltip>
//                         )}
//                       </Box>
//                     </TableCell>
//                     <TableCell>
//                       {isServiceBased ? (
//                         <FormControl size="small" sx={{ minWidth: 150 }}>
//                           <Select
//                             multiple
//                             value={selectedStaffUids}
//                             onChange={(e) => handleStaffChange(variation.uid, e.target.value as string[])}
//                             input={<OutlinedInput size="small" />}
//                             renderValue={(selected) => {
//                               const selectedNames = availableStaff
//                                 .filter(s => (selected as string[]).includes(s.uid))
//                                 .map(s => `${s.firstName} ${s.lastName}`)
//                               return selectedNames.join(', ') || 'Select staff'
//                             }}
//                             disabled={loading}
//                           >
//                             {availableStaff.map((staff) => (
//                               <MenuItem key={staff.uid} value={staff.uid}>
//                                 <Typography variant="body2">
//                                   {staff.firstName} {staff.lastName}
//                                 </Typography>
//                               </MenuItem>
//                             ))}
//                           </Select>
//                         </FormControl>
//                       ) : isInventoryNotManaged ? (
//                         <Typography 
//                           variant="body2" 
//                           fontWeight={isSelected ? 600 : 400}
//                           color={isSelected ? 'primary.main' : 'text.secondary'}
//                           sx={{ textAlign: 'center' }}
//                         >
//                           {qty}
//                         </Typography>
//                       ) : showFixedQty ? (
//                         <Typography variant="body2" fontWeight={500} sx={{ px: 2, py: 1, textAlign: 'center' }}>
//                           {qty}
//                         </Typography>
//                       ) : disableControls ? (
//                         <Typography variant="body2" color="text.secondary" sx={{ px: 2, py: 1, textAlign: 'center' }}>
//                           {qty}
//                         </Typography>
//                       ) : (
//                         <Box sx={{ display: 'flex', alignItems: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
//                           <IconButton 
//                             size="small" 
//                             onClick={(e) => handleDecrementQty(e, variation.uid)}
//                             disabled={qty <= 0}
//                             sx={{ borderRadius: 0, px: 1 }}
//                           >
//                             <Icon icon="tabler:minus" fontSize="small" />
//                           </IconButton>
//                           <TextField
//                             type="number"
//                             value={qty}
//                             onChange={(e) => handleQtyInputChange(e as React.ChangeEvent<HTMLInputElement>, variation.uid)}
//                             onClick={(e) => e.stopPropagation()}
//                             inputProps={{ 
//                               style: { textAlign: 'center', width: 40, padding: '4px 0' },
//                               min: 0,
//                               max: variation.stockQty || 999
//                             }}
//                             variant="standard"
//                             size="small"
//                             sx={{ 
//                               '& .MuiInput-underline:before': { borderBottom: 'none' },
//                               '& .MuiInput-underline:after': { borderBottom: 'none' },
//                               '& .MuiInput-root': { '&:before': { borderBottom: 'none' } }
//                             }}
//                             disabled={loading}
//                           />
//                           <IconButton 
//                             size="small" 
//                             onClick={(e) => handleIncrementQty(e, variation.uid)}
//                             disabled={variation.stockQty ? qty >= variation.stockQty : false}
//                             sx={{ borderRadius: 0, px: 1 }}
//                           >
//                             <Icon icon="tabler:plus" fontSize="small" />
//                           </IconButton>
//                         </Box>
//                       )}
//                     </TableCell>
//                     <TableCell sx={{ fontWeight: 600, color: isSelected ? 'primary.main' : 'text.secondary' }}>
//                       ${totalAmount.toFixed(2)}
//                     </TableCell>
//                     <TableCell>
//                       <Typography variant="caption" color="text.secondary">
//                         {variation.attributes?.map(a => `${a.attributeName}: ${a.value}`).join(' | ') || ''}
//                       </Typography>
//                     </TableCell>
//                   </TableRow>
//                 )
//               })}
//             </TableBody>
//           </Table>
//         </TableContainer>

//         {activeVariations.length > 0 && (
//           <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
//             <Typography variant="body2" color="primary.main" fontWeight={600}>
//               {activeVariations.length} variation(s) selected
//             </Typography>
//           </Box>
//         )}
//       </DialogContent>

//       <DialogActions sx={{ p: 3, gap: 2, borderTop: '1px solid', borderColor: 'divider' }}>
//         <Button variant="outlined" onClick={onClose} disabled={loading}>
//           Cancel
//         </Button>
//         <Button
//           variant="contained"
//           onClick={handleAddToOrder}
//           disabled={loading || activeVariations.length === 0}
//           startIcon={loading ? <CircularProgress size={16} color="inherit" /> : null}
//         >
//           {loading ? 'Processing...' : isEdit ? 'Update Item' : 'Add Item'}
//         </Button>
//       </DialogActions>
//     </Dialog>
//   )
// }

// export default ProductDialog

// tyscript issue 
import React, { useState, useEffect } from 'react'

// ** MUI Imports
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Box,
  Typography,
  Button,
  IconButton,
  TextField,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  CircularProgress,
  Chip,
  FormControl,
  Select,
  MenuItem,
  OutlinedInput,
  Tooltip
} from '@mui/material'

// ** Icon Imports
import Icon from 'src/@core/components/icon'

// ** Toast
import toast from 'react-hot-toast'

// ** Axios
import axios from 'src/configs/axios'
import endpoints from 'src/configs/endpoints'

// ** Redux
import { useDispatch, useSelector } from 'react-redux'
import { addToCart, updateQuantity } from 'src/store/pages/pos/cartSlice'
import { RootState } from 'src/store'

interface Variation {
  uid: string
  sku: string
  mrp: number
  stockQty: number | null
  quantity: number
  unit: string
  calAmount: number
  finalAmount: number
  variationImages: any[]
  attributes: any[]
}

interface Product {
  uid: string
  name: string
  description?: string
  productType?: string
  isInventoryManaged?: boolean
  variations: Variation[]
  staffs?: any[]
}

interface ProductDialogProps {
  open: boolean
  onClose: () => void
  product: Product | null
  editItem?: any
  isEdit?: boolean
}

const getFullImageUrl = (path: string): string => {
  if (!path) return ''
  if (path.startsWith('http://') || path.startsWith('https://')) return path
  if (path.startsWith('blob:') || path.startsWith('data:')) return path
  const cleanPath = path.startsWith('/') ? path : `/${path}`
  return `${cleanPath}`
}

const getVariationImage = (variation: any): string => {
  if (!variation) return ''
  const images = variation.variationImages || []
  if (images.length === 0) return ''
  const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
  return imageUrl ? getFullImageUrl(imageUrl) : ''
}

// Image component with authentication
const AuthImageComponent: React.FC<{ src: string; alt: string; style?: React.CSSProperties }> = ({ src, alt, style }) => {
  const [imageSrc, setImageSrc] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  useEffect(() => {
    let objectUrl: string | null = null
    let isMounted = true

    const fetchImage = async () => {
      setLoading(true)
      setError(false)
      setImageSrc(null)

      if (!src) {
        if (isMounted) {
          setLoading(false)
          setError(true)
          setImageSrc(null)
        }
        return
      }

      try {
        const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
        const response = await axios.get(src, {
          responseType: 'blob',
          headers: {
            'Authorization': `Bearer ${token}`
          },
          timeout: 10000
        })

        if (!isMounted) return

        const blob = response.data
        if (objectUrl) {
          URL.revokeObjectURL(objectUrl)
        }
        objectUrl = URL.createObjectURL(blob)
        
        if (isMounted) {
          setImageSrc(objectUrl)
          setLoading(false)
          setError(false)
        }
      } catch (err) {
        console.error('Error loading image:', err)
        if (isMounted) {
          setLoading(false)
          setError(true)
          setImageSrc(null)
        }
      }
    }

    fetchImage()

    return () => {
      isMounted = false
      if (objectUrl) {
        URL.revokeObjectURL(objectUrl)
      }
    }
  }, [src])

  if (loading) {
    return (
      <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <CircularProgress size={24} />
      </Box>
    )
  }

  if (error || !imageSrc) {
    return (
      <Box 
        sx={{ 
          width: '100%', 
          height: '100%', 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center',
          bgcolor: 'grey.100',
          borderRadius: 1
        }}
      >
        <Icon icon="tabler:photo-off" fontSize={24} color="action" />
      </Box>
    )
  }

  return (
    <img
      src={imageSrc}
      alt={alt}
      style={style}
      onError={(e) => {
        e.currentTarget.style.display = 'none'
        setError(true)
        setImageSrc(null)
      }}
    />
  )
}

const ProductDialog: React.FC<ProductDialogProps> = ({ 
  open, 
  onClose, 
  product, 
  editItem = null,
  isEdit = false 
}) => {
  const dispatch = useDispatch()
  const cartEntities = useSelector((state: RootState) => state.cartSlice.entities)
  const productList = useSelector((state: RootState) => state.pos.list)
  
  const [loading, setLoading] = useState(false)
  const [selectedVariation, setSelectedVariation] = useState<Variation | null>(null)
  const [orderItemUid, setOrderItemUid] = useState<string>('')
  const [posUid, setPosUid] = useState<string>('')
  const [orderUid, setOrderUid] = useState<string>('')
  
  const [quantities, setQuantities] = useState<{ [key: string]: number }>({})
  const [selectedStaff, setSelectedStaff] = useState<{ [key: string]: string[] }>({})
  const [availableStaff, setAvailableStaff] = useState<any[]>([])

  // ✅ Get fresh product data from Redux store with type assertion
  const freshProduct = React.useMemo(() => {
    if (!product) return null
    const found = productList.find(p => p.uid === product.uid)
    return (found || product) as Product
  }, [product, productList])

  // ✅ Safe checks for boolean properties
  const isServiceBased = freshProduct?.productType === 'ServiceBased'
  const isReadyToSell = freshProduct?.productType === 'ReadyToSell'
  const isInventoryNotManaged = freshProduct?.isInventoryManaged === false

  // Initialize with edit data if in edit mode
  useEffect(() => {
    if (!freshProduct) return

    if (isEdit && editItem) {
      const variation = freshProduct.variations.find(v => v.uid === editItem.id)
      if (variation) {
        setSelectedVariation(variation)
        setQuantities({
          [variation.uid]: editItem.quantity || 1
        })
        if (isServiceBased && editItem.selectedStaff) {
          setSelectedStaff({
            [variation.uid]: editItem.selectedStaff
          })
        }
      }
      setOrderItemUid(editItem.orderItemUid || '')
      setPosUid(editItem.posUid || '')
      setOrderUid(editItem.orderUid || '')
    } else if (freshProduct.variations.length > 0) {
      const initialQuantities: { [key: string]: number } = {}
      const initialStaff: { [key: string]: string[] } = {}
      
      freshProduct.variations.forEach(v => {
        if (isServiceBased) {
          initialQuantities[v.uid] = 0
        } else if (isReadyToSell && isInventoryNotManaged) {
          initialQuantities[v.uid] = 0
        } else if (isReadyToSell && freshProduct.isInventoryManaged && v.stockQty === 0) {
          initialQuantities[v.uid] = 0
        } else {
          initialQuantities[v.uid] = 0
        }
        initialStaff[v.uid] = []
      })
      
      setQuantities(initialQuantities)
      setSelectedStaff(initialStaff)
      setSelectedVariation(freshProduct.variations[0])
      
      if (isServiceBased && freshProduct.staffs) {
        setAvailableStaff(freshProduct.staffs)
      }
    }
  }, [freshProduct, editItem, isEdit, open, isServiceBased, isReadyToSell, isInventoryNotManaged])

  // Reset when dialog closes
  useEffect(() => {
    if (!open) {
      setSelectedVariation(null)
      setOrderItemUid('')
      setPosUid('')
      setOrderUid('')
      setQuantities({})
      setSelectedStaff({})
      setAvailableStaff([])
    }
  }, [open])

  // Check if variation already exists in cart
  const findExistingCartItem = (variationUid: string): any => {
    const cartItems = Object.values(cartEntities) as any[]
    return cartItems.find(item => item.id === variationUid)
  }

  // Fetch order details to get the actual item UID
  const fetchOrderDetails = async (orderUid: string): Promise<{ itemUid: string, posUid: string, orderUid: string }> => {
    try {
      const response = await axios.get(`${endpoints.pos.posOrder.get}${orderUid}`)
      console.log('Order details response:', response.data)
      
      const orderData = response.data?.content?.result || response.data?.content || response.data
      
      let itemUid = orderUid
      let posUid = orderUid
      let orderUidFromResponse = orderUid
      
      if (orderData) {
        orderUidFromResponse = orderData.uid || orderData.orderUid || orderUid
        posUid = orderData.uid || orderData.orderUid || orderUid
        
        if (orderData.items && orderData.items.length > 0) {
          itemUid = orderData.items[0].uid || orderData.items[0].itemUid || posUid
        } else if (orderData.itemUid) {
          itemUid = orderData.itemUid
        } else if (orderData.variationUid) {
          itemUid = orderData.variationUid
        }
      }
      
      return { itemUid, posUid, orderUid: orderUidFromResponse }
    } catch (error) {
      console.error('Error fetching order details:', error)
      return { itemUid: orderUid, posUid: orderUid, orderUid: orderUid }
    }
  }

  // Get the variations with quantity > 0
  const getActiveVariations = () => {
    if (!freshProduct) return []
    
    const activeVariations: { variation: Variation, quantity: number }[] = []
    for (const v of freshProduct.variations) {
      const qty = quantities[v.uid] || 0
      if (qty > 0) {
        activeVariations.push({ variation: v, quantity: qty })
      }
    }
    return activeVariations
  }

  // Get quantity for a specific variation
  const getQuantity = (variationUid: string): number => {
    return quantities[variationUid] || 0
  }

  // Get selected staff for a variation
  const getSelectedStaff = (variationUid: string): string[] => {
    return selectedStaff[variationUid] || []
  }

  // ✅ Check if quantity controls should be disabled (fixed boolean return)
  const shouldDisableQuantityControls = (variation: Variation): boolean => {
    if (isServiceBased) return true
    if (isReadyToSell && isInventoryNotManaged) {
      return true
    }
    if (isReadyToSell && (freshProduct?.isInventoryManaged === true) && variation.stockQty === 0) {
      return true
    }
    return false
  }

  // ✅ Check if stock should show "Out of Stock" (fixed boolean return)
  const shouldShowOutOfStock = (variation: Variation): boolean => {
    return isReadyToSell && (freshProduct?.isInventoryManaged === true) && variation.stockQty === 0
  }

  // ✅ Check if quantity should be fixed to 1 (fixed boolean return)
  const shouldShowFixedQuantity = (variation: Variation): boolean => {
    if (isServiceBased) return true
    if (isReadyToSell && isInventoryNotManaged) {
      return true
    }
    return false
  }

  // Toggle variation selection (for inventory not managed)
  const toggleVariationSelection = (variationUid: string) => {
    if (!isReadyToSell || !isInventoryNotManaged) return
    
    const currentQty = getQuantity(variationUid)
    handleQuantityChange(variationUid, currentQty === 0 ? 1 : 0)
  }

  // Handle quantity change for a specific variation
  const handleQuantityChange = (variationUid: string, newQuantity: number) => {
    const variation = freshProduct?.variations.find(v => v.uid === variationUid)
    if (!variation) return
    
    if (shouldDisableQuantityControls(variation)) {
      if (isReadyToSell && isInventoryNotManaged) {
        if (newQuantity > 1) return
        if (newQuantity < 0) return
      } else {
        return
      }
    }
    
    if (newQuantity < 0) return
    
    if (variation.stockQty && newQuantity > variation.stockQty) {
      toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
      return
    }
    
    setQuantities(prev => ({
      ...prev,
      [variationUid]: newQuantity
    }))
    
    if (newQuantity > 0) {
      const variation = freshProduct?.variations.find(v => v.uid === variationUid)
      if (variation) {
        setSelectedVariation(variation)
      }
    }
  }

  // Handle staff selection for service-based products
  const handleStaffChange = (variationUid: string, staffUids: string[]) => {
    setSelectedStaff(prev => ({
      ...prev,
      [variationUid]: staffUids
    }))
    
    if (isServiceBased) {
      const staffCount = staffUids.length
      setQuantities(prev => ({
        ...prev,
        [variationUid]: staffCount > 0 ? 1 : 0
      }))
    }
  }

  const handleDecrementQty = (e: React.MouseEvent, variationUid: string) => {
    e.stopPropagation()
    const variation = freshProduct?.variations.find(v => v.uid === variationUid)
    if (!variation || shouldDisableQuantityControls(variation)) return
    
    const currentQty = getQuantity(variationUid)
    if (currentQty > 0) {
      handleQuantityChange(variationUid, currentQty - 1)
    }
  }

  const handleIncrementQty = (e: React.MouseEvent, variationUid: string) => {
    e.stopPropagation()
    const variation = freshProduct?.variations.find(v => v.uid === variationUid)
    if (!variation || shouldDisableQuantityControls(variation)) return
    
    const currentQty = getQuantity(variationUid)
    if (variation.stockQty && currentQty >= variation.stockQty) {
      toast.error(`Stock limit exceeded. Max: ${variation.stockQty}`, { style: { zIndex: 999999 } })
      return
    }
    handleQuantityChange(variationUid, currentQty + 1)
  }

  const handleQtyInputChange = (e: React.ChangeEvent<HTMLInputElement>, variationUid: string) => {
    const variation = freshProduct?.variations.find(v => v.uid === variationUid)
    if (!variation || shouldDisableQuantityControls(variation)) return
    
    e.stopPropagation()
    const val = parseInt(e.target.value)
    if (!isNaN(val) && val >= 0) {
      handleQuantityChange(variationUid, val)
    }
  }

  const handleAddToOrder = async () => {
  const activeVariations = getActiveVariations()
  
  if (activeVariations.length === 0) {
    toast.error('Please select at least one variation', { style: { zIndex: 999999 } })
    return
  }

  setLoading(true)

  try {
    if (isEdit && editItem) {
      const firstActive = activeVariations[0]
      if (!orderItemUid) {
        toast.error('Order item UID is missing. Please try again.', { style: { zIndex: 999999 } })
        setLoading(false)
        return
      }
      const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${orderItemUid}?quantity=${firstActive.quantity}`
      await axios.put(updateUrl)
      
      dispatch(updateQuantity({ 
        id: firstActive.variation.uid, 
        quantity: firstActive.quantity 
      }))
      
      toast.success('Item updated successfully!', { style: { zIndex: 999999 } })
      onClose()
    } else {
      for (const active of activeVariations) {
        const existingItem = findExistingCartItem(active.variation.uid)
        
        if (existingItem) {
          const existingOrderItemUid = existingItem.orderItemUid
          if (!existingOrderItemUid) {
            toast.error('Order item UID is missing for existing item', { style: { zIndex: 999999 } })
            continue
          }
          
          const newQuantity = existingItem.quantity + active.quantity
          const updateUrl = `${endpoints.pos.posOrder.updateQuantity}${existingOrderItemUid}?quantity=${newQuantity}`
          await axios.put(updateUrl)
          
          dispatch(updateQuantity({ 
            id: active.variation.uid, 
            quantity: newQuantity 
          }))
          
          toast.success(`Item quantity updated to ${newQuantity}!`, { style: { zIndex: 999999 } })
        } else {
          let payload: any = {}
          
          if (isServiceBased) {
            const staffUids = getSelectedStaff(active.variation.uid)
            if (staffUids.length === 0) {
              toast.error('Please select at least one staff member', { style: { zIndex: 999999 } })
              setLoading(false)
              return
            }
            
            payload = {
              items: staffUids.map(staffUid => ({
                staffUid: staffUid,
                variationUid: active.variation.uid,
                quantity: 1
              })),
              productType: freshProduct?.productType || 'ServiceBased'
            }
          } else {
            payload = {
              items: [{
                variationUid: active.variation.uid,
                quantity: active.quantity
              }],
              productType: freshProduct?.productType || 'ReadyToSell'
            }
          }
          
          const response = await axios.post(endpoints.pos.posOrder.create, payload)
          const orderData = response.data
          
          if (orderData) {
            const orderUid = orderData.uid || orderData.orderUid || ''
            const { itemUid, posUid: fetchedPosUid, orderUid: fetchedOrderUid } = await fetchOrderDetails(orderUid)
            
            const variation = freshProduct?.variations.find(v => v.uid === active.variation.uid)
            
            const itemPrice = active.variation.finalAmount || active.variation.mrp
            
            dispatch(addToCart({
              id: active.variation.uid,
              productUid: freshProduct?.uid || '',
              name: freshProduct?.name || '',
              price: itemPrice,

              // ❌ Removed: mrp: active.variation.mrp,
              // ❌ Removed: taxAmount: active.variation.calAmount || 0,
              quantity: isServiceBased ? getSelectedStaff(active.variation.uid).length : active.quantity,
              image: getVariationImage(active.variation),
              variation: active.variation,
              orderItemUid: itemUid,
              posUid: fetchedPosUid,
              orderUid: fetchedOrderUid,
              stockQty: variation?.stockQty || 0,
              productType: freshProduct?.productType || 'ReadyToSell',
              isInventoryManaged: freshProduct?.isInventoryManaged || false,
              ...(isServiceBased && {
                selectedStaff: getSelectedStaff(active.variation.uid)
              })
            }))
          }
        }
      }
      
      toast.success(`${activeVariations.length} item(s) added to order!`, { style: { zIndex: 999999 } })
      onClose()
    }
  } catch (error: any) {
    console.error('Error:', error)
    toast.error(error?.response?.data?.message || 'Failed to process item', { 
      style: { zIndex: 999999 } 
    })
  } finally {
    setLoading(false)
  }
}

  if (!freshProduct) return null

  const finalPrices = freshProduct.variations.map(v => v.finalAmount || v.mrp)
  const minPrice = Math.min(...finalPrices)
  const maxPrice = Math.max(...finalPrices)
  const priceDisplay = minPrice === maxPrice ? `$${minPrice.toFixed(2)}` : `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`

  const activeVariations = getActiveVariations()

  return (
    <Dialog 
      open={open} 
      onClose={onClose} 
      maxWidth="md" 
      fullWidth
      PaperProps={{
        sx: { borderRadius: 2, zIndex: 999999 }
      }}
    >
      <DialogTitle sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        borderBottom: '1px solid',
        borderColor: 'divider',
        pb: 2
      }}>
        <Box>
          <Typography variant="h6">{freshProduct.name}</Typography>
          <Typography variant="body2" color="text.secondary">
            {isEdit ? 'Edit Item' : 'Add to Order'}
            {freshProduct.productType && (
              <Chip 
                label={freshProduct.productType} 
                size="small" 
                color={freshProduct.productType === 'ServiceBased' ? 'secondary' : 'primary'}
                sx={{ ml: 1 }}
              />
            )}
          </Typography>
        </Box>
        <IconButton onClick={onClose}>
          <Icon icon="tabler:x" />
        </IconButton>
      </DialogTitle>

      <DialogContent sx={{ pt: 3 }}>
        <Box sx={{ mb: 3 }}>
          <Typography variant="body2" color="text.secondary">
            Product Description: {freshProduct.description || 'No description available'}
          </Typography>
          <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1 }}>
            Price Range: {priceDisplay}
          </Typography>
        </Box>

        <Typography variant="subtitle2" sx={{ mb: 2 }}>
          Select Variation{isInventoryNotManaged && ' (Click row to select/deselect)'}
        </Typography>
        <TableContainer component={Paper} sx={{ maxHeight: 300 }}>
          <Table size="small" stickyHeader>
            <TableHead>
              <TableRow>
                {!isServiceBased && <TableCell>SKU</TableCell>}
                <TableCell>Image</TableCell>
                {!isServiceBased && <TableCell>Stock</TableCell>}
                <TableCell>Amount (Final)</TableCell>
                <TableCell>{isServiceBased ? 'Staff Members' : 'QTY'}</TableCell>
                <TableCell>Total</TableCell>
                <TableCell>Attributes</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {freshProduct.variations.map((variation) => {
                const imageUrl = getVariationImage(variation)
                const qty = getQuantity(variation.uid)
                const selectedStaffUids = getSelectedStaff(variation.uid)
                const showOutOfStock = shouldShowOutOfStock(variation)
                const showFixedQty = shouldShowFixedQuantity(variation)
                const disableControls = shouldDisableQuantityControls(variation)
                const isSelected = qty > 0
                
                const unitPrice = variation.finalAmount || variation.mrp
                let totalAmount = unitPrice * qty
                if (isServiceBased) {
                  totalAmount = unitPrice * selectedStaffUids.length
                }
                
                const isRowClickable = isReadyToSell && isInventoryNotManaged
                
                return (
                  <TableRow 
                    key={variation.uid}
                    onClick={() => {
                      if (isRowClickable) {
                        toggleVariationSelection(variation.uid)
                      }
                    }}
                    sx={{ 
                      bgcolor: isSelected ? 'primary.light' : 'inherit',
                      cursor: isRowClickable ? 'pointer' : 'default',
                      '&:hover': { 
                        bgcolor: isSelected ? 'primary.main' : 'action.hover',
                        '& .MuiTypography-root': {
                          color: isSelected ? 'white' : 'inherit'
                        }
                      },
                      transition: 'background-color 0.2s ease'
                    }}
                  >
                    {!isServiceBased && (
                      <TableCell>
                        <Typography variant="body2" fontWeight={500}>
                          {variation.sku || 'N/A'}
                        </Typography>
                      </TableCell>
                    )}
                    <TableCell>
                      <Box
                        sx={{
                          width: 40,
                          height: 40,
                          borderRadius: 1,
                          overflow: 'hidden',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          bgcolor: 'grey.100'
                        }}
                      >
                        {imageUrl ? (
                          <AuthImageComponent
                            src={imageUrl}
                            alt=""
                            style={{
                              width: '100%',
                              height: '100%',
                              objectFit: 'cover'
                            }}
                          />
                        ) : (
                          <Icon icon="tabler:photo-off" fontSize={20} color="action" />
                        )}
                      </Box>
                    </TableCell>
                    {!isServiceBased && (
                      <TableCell>
                        {showOutOfStock ? (
                          <Typography variant="body2" color="error" fontWeight="bold">
                            Out of Stock
                          </Typography>
                        ) : (
                          <Typography variant="body2">
                            {variation.stockQty ?? 'N/A'}
                          </Typography>
                        )}
                      </TableCell>
                    )}
                    <TableCell>
                      <Box>
                        <Typography variant="body2" fontWeight={600} color="primary.main">
                          ${(variation.finalAmount || variation.mrp).toFixed(2)}
                        </Typography>
                        {variation.calAmount > 0 && variation.mrp && (
                          <Tooltip title={`MRP: $${variation.mrp.toFixed(2)} + Tax: $${variation.calAmount.toFixed(2)}`}>
                            <Typography variant="caption" color="text.secondary" display="block">
                              MRP: ${variation.mrp.toFixed(2)} + Tax: ${variation.calAmount.toFixed(2)}
                            </Typography>
                          </Tooltip>
                        )}
                      </Box>
                    </TableCell>
                    <TableCell>
                      {isServiceBased ? (
                        <FormControl size="small" sx={{ minWidth: 150 }}>
                          <Select
                            multiple
                            value={selectedStaffUids}
                            onChange={(e) => handleStaffChange(variation.uid, e.target.value as string[])}
                            input={<OutlinedInput size="small" />}
                            renderValue={(selected) => {
                              const selectedNames = availableStaff
                                .filter(s => (selected as string[]).includes(s.uid))
                                .map(s => `${s.firstName} ${s.lastName}`)
                              return selectedNames.join(', ') || 'Select staff'
                            }}
                            disabled={loading}
                          >
                            {availableStaff.map((staff) => (
                              <MenuItem key={staff.uid} value={staff.uid}>
                                <Typography variant="body2">
                                  {staff.firstName} {staff.lastName}
                                </Typography>
                              </MenuItem>
                            ))}
                          </Select>
                        </FormControl>
                      ) : isInventoryNotManaged ? (
                        <Typography 
                          variant="body2" 
                          fontWeight={isSelected ? 600 : 400}
                          color={isSelected ? 'primary.main' : 'text.secondary'}
                          sx={{ textAlign: 'center' }}
                        >
                          {qty}
                        </Typography>
                      ) : showFixedQty ? (
                        <Typography variant="body2" fontWeight={500} sx={{ px: 2, py: 1, textAlign: 'center' }}>
                          {qty}
                        </Typography>
                      ) : disableControls ? (
                        <Typography variant="body2" color="text.secondary" sx={{ px: 2, py: 1, textAlign: 'center' }}>
                          {qty}
                        </Typography>
                      ) : (
                        <Box sx={{ display: 'flex', alignItems: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
                          <IconButton 
                            size="small" 
                            onClick={(e) => handleDecrementQty(e, variation.uid)}
                            disabled={qty <= 0}
                            sx={{ borderRadius: 0, px: 1 }}
                          >
                            <Icon icon="tabler:minus" fontSize="small" />
                          </IconButton>
                          <TextField
                            type="number"
                            value={qty}
                            onChange={(e) => handleQtyInputChange(e as React.ChangeEvent<HTMLInputElement>, variation.uid)}
                            onClick={(e) => e.stopPropagation()}
                            inputProps={{ 
                              style: { textAlign: 'center', width: 40, padding: '4px 0' },
                              min: 0,
                              max: variation.stockQty || 999
                            }}
                            variant="standard"
                            size="small"
                            sx={{ 
                              '& .MuiInput-underline:before': { borderBottom: 'none' },
                              '& .MuiInput-underline:after': { borderBottom: 'none' },
                              '& .MuiInput-root': { '&:before': { borderBottom: 'none' } }
                            }}
                            disabled={loading}
                          />
                          <IconButton 
                            size="small" 
                            onClick={(e) => handleIncrementQty(e, variation.uid)}
                            disabled={variation.stockQty ? qty >= variation.stockQty : false}
                            sx={{ borderRadius: 0, px: 1 }}
                          >
                            <Icon icon="tabler:plus" fontSize="small" />
                          </IconButton>
                        </Box>
                      )}
                    </TableCell>
                    <TableCell sx={{ fontWeight: 600, color: isSelected ? 'primary.main' : 'text.secondary' }}>
                      ${totalAmount.toFixed(2)}
                    </TableCell>
                    <TableCell>
                      <Typography variant="caption" color="text.secondary">
                        {variation.attributes?.map(a => `${a.attributeName}: ${a.value}`).join(' | ') || ''}
                      </Typography>
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        </TableContainer>

        {activeVariations.length > 0 && (
          <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
            <Typography variant="body2" color="primary.main" fontWeight={600}>
              {activeVariations.length} variation(s) selected
            </Typography>
          </Box>
        )}
      </DialogContent>

      <DialogActions sx={{ p: 3, gap: 2, borderTop: '1px solid', borderColor: 'divider' }}>
        <Button variant="outlined" onClick={onClose} disabled={loading}>
          Cancel
        </Button>
        <Button
          variant="contained"
          onClick={handleAddToOrder}
          disabled={loading || activeVariations.length === 0}
          startIcon={loading ? <CircularProgress size={16} color="inherit" /> : null}
        >
          {loading ? 'Processing...' : isEdit ? 'Update Item' : 'Add Item'}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

export default ProductDialog