// import React, { Fragment, useState } from 'react'
// import {
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   IconButton,
//   TextField,
//   Box,
//   Paper,
//   Typography,
//   Button
// } from '@mui/material'

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

// // ** Hooks
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'

// // ** Forms Modal
// import EditCart from './forms/EditCart'

// // ** Action
// import { removeFromCart } from 'src/store/pages/pos/cartSlice'

// // ** Dispatch
// import { useDispatch } from 'react-redux'

// import { motion, AnimatePresence } from 'framer-motion'

// // ** Types
// interface CartItem {
//   id: string
//   name: string
//   price: number
//   quantity: number
//   image: string
// }

// const MotionTableRow = motion.create(TableRow)

// const OrderListTable = () => {
//   // ** State
//   const [openEditModal, setOpenEditModal] = useState<boolean>(false)
//   const [selectedProduct, setSelectedProduct] = useState<CartItem | null>(null)
//   const [deleteLoader, setDeleteLoader] = useState<string | null>(null)

//   // ** Hooks
//   const cartList = useSelector(
//     (state: RootState) =>
//       state.cartSlice as {
//         entities: { [key: string]: CartItem }
//       }
//   )
//   const { entities } = cartList

//   // ** Product List
//   const products = Object.values(entities) as CartItem[]

//   // ** Dispatch
//   const dispatch = useDispatch()

//   // ** Toggle
//   const handleToggleEditModal = (product: CartItem | null) => {
//     setSelectedProduct(product)
//     setOpenEditModal(!openEditModal)
//   }

//   const handleRemove = (id: string) => {
//     setDeleteLoader(id)
//     setTimeout(() => {
//       dispatch(removeFromCart(id))
//       setDeleteLoader(null)
//     }, 800)
//   }

//   return (
//     <Fragment>
//       {products.length ? (
//         <Box>
//           <Box
//             sx={{
//               display: 'flex',
//               alignItems: 'center',
//               justifyContent: 'space-between',

//               borderRadius: 1,
//               mt: 4
//             }}
//           >
//             <Typography variant='h6' sx={{ mt: 4, mb: 2 }}>
//               Order Details
//             </Typography>
//             <Button variant='outlined' size='small' color='error'>
//               Clear All
//             </Button>
//           </Box>
//           <TableContainer component={Paper}>
//             <Table size='small'>
//               <TableHead>
//                 <TableRow>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100' }}>Item</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100' }}>QTY</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right' }}>Cost</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right' }}>Edit</TableCell>
//                 </TableRow>
//               </TableHead>

//               <TableBody sx={{ maxHeight: '300px', position: 'relative' }}>
//                 <AnimatePresence>
//                   {products.map((product: any) => (
//                     <MotionTableRow
//                       key={product.id}
//                       layout
//                       initial={{ opacity: 0, y: -10 }}
//                       animate={{ opacity: 1, y: 0 }}
//                       exit={{
//                         opacity: 0,
//                         x: -100,
//                         scale: 0.95,
//                         transition: { duration: 0.3 }
//                       }}
//                       sx={{
//                         backgroundColor: deleteLoader === product.id ? 'rgba(255,0,0,0.04)' : 'transparent',
//                         transition: 'background-color 0.3s ease'
//                       }}
//                     >
//                       <TableCell>
//                         <Box display='flex' alignItems='center' gap={1}>
//                           <motion.div
//                             whileTap={{ scale: 0.8, rotate: -10 }}
//                             whileHover={{ rotate: -10 }}
//                             transition={{ type: 'spring', stiffness: 200 }}
//                           >
//                             <IconButton
//                               aria-label='delete'
//                               color='error'
//                               size='small'
//                               onClick={() => handleRemove(product.id)}
//                             >
//                               <Icon icon='tabler:trash' fontSize='inherit' />
//                             </IconButton>
//                           </motion.div>
//                           <Typography variant='body2'>{product.name}</Typography>
//                         </Box>
//                       </TableCell>

//                       <TableCell>
//                         <TextField
//                           size='small'
//                           type='number'
//                           value={product.quantity}
//                           inputProps={{ style: { textAlign: 'center', width: 40 } }}
//                           disabled
//                         />
//                       </TableCell>

//                       <TableCell sx={{ textAlign: 'right', fontWeight: 600 }}>${product.price}</TableCell>

//                       <TableCell sx={{ textAlign: 'right' }}>
//                         <IconButton
//                           aria-label='edit'
//                           color='secondary'
//                           size='small'
//                           onClick={() => handleToggleEditModal(product)}
//                           sx={{ bgcolor: 'grey.100' }}
//                         >
//                           <Icon icon='tabler:edit' fontSize='inherit' />
//                         </IconButton>
//                       </TableCell>
//                     </MotionTableRow>
//                   ))}
//                 </AnimatePresence>
//               </TableBody>
//             </Table>
//           </TableContainer>
//         </Box>
//       ) : (
//         <Typography variant='body2' sx={{ mb: 2, textAlign: 'center', mt: 4 }}>
//           {products.length} items in cart
//         </Typography>
//       )}
//       {/* <OrderListSkeleton /> */}
//       <EditCart open={openEditModal} onClose={() => handleToggleEditModal(null)} product={selectedProduct} />
//     </Fragment>
//   )
// }

// export default OrderListTable


// sagar changes //////////////
// import React, { Fragment, useState } from 'react'
// import {
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   IconButton,
//   TextField,
//   Box,
//   Paper,
//   Typography,
//   Button,
//   CircularProgress
// } from '@mui/material'

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

// // ** Hooks
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'

// // ** Action
// import { removeFromCart, updateQuantity } from 'src/store/pages/pos/cartSlice'

// // ** Dispatch
// import { useDispatch } from 'react-redux'

// // ** Components


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

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

// import { motion, AnimatePresence } from 'framer-motion'
// import ProductDialog from './payment/modal/AddToCartModal'

// // ** Types
// interface CartItem {
//   id: string
//   productUid: string
//   name: string
//   price: number
//   quantity: number
//   image: string
//   stockQty?: number
//   variation: any
//   orderItemUid?: string
//   posUid?: string
// }

// const MotionTableRow = motion.create(TableRow)

// const OrderListTable = () => {
//   const [editDialogOpen, setEditDialogOpen] = useState<boolean>(false)
//   const [selectedProduct, setSelectedProduct] = useState<any>(null)
//   const [selectedCartItem, setSelectedCartItem] = useState<CartItem | null>(null)
//   const [deleteLoader, setDeleteLoader] = useState<string | null>(null)
//   const [updatingQuantity, setUpdatingQuantity] = useState<string | null>(null)

//   const cartSlice = useSelector((state: RootState) => state.cartSlice)
//   const entities = cartSlice?.entities || {}
//   const products = Object.values(entities) as CartItem[]

//   console.log('Cart Products:', products)

//   const dispatch = useDispatch()

//   const handleEditClick = (product: CartItem) => {
//     setSelectedCartItem(product)
//     // Create product data with all variations from the product
//     const productData = {
//       uid: product.productUid || product.id,
//       name: product.name,
//       description: '',
//       variations: product.variation ? [product.variation] : []
//     }
//     setSelectedProduct(productData)
//     setEditDialogOpen(true)
//   }

//   const handleRemove = async (id: string, posUid?: string, orderItemUid?: string) => {
//     console.log('Delete - id:', id, 'posUid:', posUid, 'orderItemUid:', orderItemUid)
    
//     // If no order info, just remove from Redux
//     if (!posUid || !orderItemUid) {
//       dispatch(removeFromCart(id))
//       toast.success('Item removed from cart', { style: { zIndex: 999999 } })
//       return
//     }

//     setDeleteLoader(id)
//     try {
//       // CORRECT: DELETE /pos/{posUid}/items/{itemUid}
//       const deleteUrl = `${endpoints.pos.posOrder.removeItem}${posUid}/items/${orderItemUid}`
//       console.log('Delete URL:', deleteUrl)
//       await axios.delete(deleteUrl)
      
//       // Remove from Redux
//       dispatch(removeFromCart(id))
      
//       toast.success('Item removed from order!', { style: { zIndex: 999999 } })
//     } catch (error: any) {
//       console.error('Error deleting item:', error)
//       toast.error(error?.response?.data?.message || 'Failed to delete item', { 
//         style: { zIndex: 999999 } 
//       })
//       // Even if API fails, remove from Redux to keep UI in sync
//       dispatch(removeFromCart(id))
//     } finally {
//       setDeleteLoader(null)
//     }
//   }

//   const handleQuantityChange = (id: string, newQuantity: number) => {
//     if (newQuantity < 1) return
    
//     const item = entities[id]
//     if (item && item.stockQty && newQuantity > item.stockQty) {
//       setUpdatingQuantity(id)
//       dispatch(updateQuantity({ id, quantity: item.stockQty }))
//       setTimeout(() => {
//         setUpdatingQuantity(null)
//       }, 500)
//       return
//     }
    
//     setUpdatingQuantity(id)
//     dispatch(updateQuantity({ id, quantity: newQuantity }))
//     setTimeout(() => {
//       setUpdatingQuantity(null)
//     }, 500)
//   }

//   const handleClearAll = () => {
//     if (products.length === 0) return
//     products.forEach(item => {
//       dispatch(removeFromCart(item.id))
//     })
//   }

//   const totalItems = products.reduce((sum, item) => sum + item.quantity, 0)

//   return (
//     <Fragment>
//       {products.length > 0 ? (
//         <Box>
//           <Box
//             sx={{
//               display: 'flex',
//               alignItems: 'center',
//               justifyContent: 'space-between',
//               borderRadius: 1,
//               mt: 4
//             }}
//           >
//             <Typography variant='h6' sx={{ mt: 4, mb: 2 }}>
//               Order Details ({totalItems} items)
//             </Typography>
//             <Button variant='outlined' size='small' color='error' onClick={handleClearAll}>
//               Clear All
//             </Button>
//           </Box>
//           <TableContainer component={Paper}>
//             <Table size='small'>
//               <TableHead>
//                 <TableRow>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100' }}>Item</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100' }}>QTY</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right' }}>Cost</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right' }}>Edit</TableCell>
//                 </TableRow>
//               </TableHead>

//               <TableBody>
//                 <AnimatePresence>
//                   {products.map((product) => (
//                     <MotionTableRow
//                       key={product.id}
//                       layout
//                       initial={{ opacity: 0, y: -10 }}
//                       animate={{ opacity: 1, y: 0 }}
//                       exit={{
//                         opacity: 0,
//                         x: -100,
//                         scale: 0.95,
//                         transition: { duration: 0.3 }
//                       }}
//                       sx={{
//                         backgroundColor: deleteLoader === product.id ? 'rgba(255,0,0,0.04)' : 'transparent',
//                         transition: 'background-color 0.3s ease'
//                       }}
//                     >
//                       <TableCell>
//                         <Box display='flex' alignItems='center' gap={1}>
//                           <motion.div
//                             whileTap={{ scale: 0.8, rotate: -10 }}
//                             whileHover={{ rotate: -10 }}
//                             transition={{ type: 'spring', stiffness: 200 }}
//                           >
//                             <IconButton
//                               aria-label='delete'
//                               color='error'
//                               size='small'
//                               onClick={() => handleRemove(product.id, product.posUid, product.orderItemUid)}
//                               disabled={deleteLoader === product.id}
//                             >
//                               {deleteLoader === product.id ? (
//                                 <CircularProgress size={16} />
//                               ) : (
//                                 <Icon icon='tabler:trash' fontSize='inherit' />
//                               )}
//                             </IconButton>
//                           </motion.div>
//                           <Box>
//                             <Typography variant='body2'>{product.name}</Typography>
//                             {product.variation?.attributes && product.variation.attributes.length > 0 && (
//                               <Typography variant='caption' color='text.secondary'>
//                                 {product.variation.attributes.map((attr: any) => 
//                                   `${attr.attributeName}: ${attr.value}`
//                                 ).join(' | ')}
//                               </Typography>
//                             )}
//                           </Box>
//                         </Box>
//                       </TableCell>

//                       <TableCell>
//                         <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
//                           <IconButton
//                             size='small'
//                             onClick={() => handleQuantityChange(product.id, product.quantity - 1)}
//                             disabled={product.quantity <= 1 || updatingQuantity === product.id}
//                           >
//                             <Icon icon='tabler:minus' fontSize='small' />
//                           </IconButton>
//                           <TextField
//                             size='small'
//                             type='number'
//                             value={product.quantity}
//                             inputProps={{ 
//                               style: { textAlign: 'center', width: 50, minWidth: 50 },
//                               min: 1,
//                               max: product.stockQty || 999
//                             }}
//                             onChange={(e) => {
//                               const val = parseInt(e.target.value)
//                               if (!isNaN(val) && val > 0) {
//                                 handleQuantityChange(product.id, val)
//                               }
//                             }}
//                             disabled={updatingQuantity === product.id}
//                           />
//                           <IconButton
//                             size='small'
//                             onClick={() => handleQuantityChange(product.id, product.quantity + 1)}
//                             disabled={updatingQuantity === product.id || (product.stockQty && product.quantity >= product.stockQty)}
//                           >
//                             <Icon icon='tabler:plus' fontSize='small' />
//                           </IconButton>
//                         </Box>
//                       </TableCell>

//                       <TableCell sx={{ textAlign: 'right', fontWeight: 600 }}>
//                         ${(product.price * product.quantity).toFixed(2)}
//                       </TableCell>

//                       <TableCell sx={{ textAlign: 'right' }}>
//                         <IconButton
//                           aria-label='edit'
//                           color='secondary'
//                           size='small'
//                           onClick={() => handleEditClick(product)}
//                           sx={{ bgcolor: 'grey.100' }}
//                         >
//                           <Icon icon='tabler:edit' fontSize='inherit' />
//                         </IconButton>
//                       </TableCell>
//                     </MotionTableRow>
//                   ))}
//                 </AnimatePresence>
//               </TableBody>
//             </Table>
//           </TableContainer>
//         </Box>
//       ) : (
//         <Typography variant='body2' sx={{ mb: 2, textAlign: 'center', mt: 4, py: 4 }}>
//           🛒 No items in cart. Add products to get started.
//         </Typography>
//       )}

//       {/* Edit Dialog */}
//       {selectedProduct && (
//         <ProductDialog
//           open={editDialogOpen}
//           onClose={() => {
//             setEditDialogOpen(false)
//             setSelectedProduct(null)
//             setSelectedCartItem(null)
//           }}
//           product={selectedProduct}
//           editItem={selectedCartItem}
//           isEdit={true}
//         />
//       )}
//     </Fragment>
//   )
// }

// export default OrderListTable

// fixed //////////////
// import React, { Fragment, useState } from 'react'
// import {
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   IconButton,
//   Box,
//   Paper,
//   Typography,
//   Button,
//   CircularProgress
// } from '@mui/material'

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

// // ** Hooks
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'

// // ** Action
// import { removeFromCart } from 'src/store/pages/pos/cartSlice'

// // ** Dispatch
// import { useDispatch } from 'react-redux'

// // ** Components


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

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

// import { motion, AnimatePresence } from 'framer-motion'
// import ProductDialog from './payment/modal/AddToCartModal'

// // ** Types
// interface CartItem {
//   id: string
//   productUid: string
//   name: string
//   price: number
//   quantity: number
//   image: string
//   stockQty?: number
//   variation: any
//   orderItemUid?: string
//   posUid?: string
// }

// const MotionTableRow = motion.create(TableRow)

// const OrderListTable = () => {
//   const [editDialogOpen, setEditDialogOpen] = useState<boolean>(false)
//   const [selectedProduct, setSelectedProduct] = useState<any>(null)
//   const [selectedCartItem, setSelectedCartItem] = useState<CartItem | null>(null)
//   const [deleteLoader, setDeleteLoader] = useState<string | null>(null)
//   const cartSlice = useSelector((state: RootState) => state.cartSlice)
//   const entities = cartSlice?.entities || {}
//   const products = Object.values(entities) as CartItem[]

//   const dispatch = useDispatch()

//   const handleEditClick = (product: CartItem) => {
//     setSelectedCartItem(product)
//     const productData = {
//       uid: product.productUid || product.id,
//       name: product.name,
//       description: '',
//       variations: product.variation ? [product.variation] : []
//     }
//     setSelectedProduct(productData)
//     setEditDialogOpen(true)
//   }

//   const handleRemove = async (id: string, posUid?: string, orderItemUid?: string) => {
//     if (!posUid || !orderItemUid) {
//       dispatch(removeFromCart(id))
//       toast.success('Item removed from cart', { style: { zIndex: 999999 } })
//       return
//     }

//     setDeleteLoader(id)
//     try {
//       const deleteUrl = `${endpoints.pos.posOrder.removeItem}${posUid}/items/${orderItemUid}`
//       await axios.delete(deleteUrl)
//       dispatch(removeFromCart(id))
//       toast.success('Item removed from order!', { style: { zIndex: 999999 } })
//     } catch (error: any) {
//       console.error('Error deleting item:', error)
//       toast.error(error?.response?.data?.message || 'Failed to delete item', { 
//         style: { zIndex: 999999 } 
//       })
//       dispatch(removeFromCart(id))
//     } finally {
//       setDeleteLoader(null)
//     }
//   }

//   const handleClearAll = () => {
//     if (products.length === 0) return
//     products.forEach(item => {
//       dispatch(removeFromCart(item.id))
//     })
//   }

//   const totalItems = products.reduce((sum, item) => sum + item.quantity, 0)

//   return (
//     <Fragment>
//       {products.length > 0 ? (
//         <Box>
//           <Box
//             sx={{
//               display: 'flex',
//               alignItems: 'center',
//               justifyContent: 'space-between',
//               borderRadius: 1,
//               mt: 4
//             }}
//           >
//             <Typography variant='h6' sx={{ mt: 4, mb: 2 }}>
//               Order Details ({totalItems} items)
//             </Typography>
//             <Button variant='outlined' size='small' color='error' onClick={handleClearAll}>
//               Clear All
//             </Button>
//           </Box>
//           <TableContainer component={Paper}>
//             <Table size='small'>
//               <TableHead>
//                 <TableRow>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100' }}>Item</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'center' }}>QTY</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right' }}>Price</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right' }}>Total Cost</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'center' }}>Actions</TableCell>
//                 </TableRow>
//               </TableHead>

//               <TableBody>
//                 <AnimatePresence>
//                   {products.map((product) => (
//                     <MotionTableRow
//                       key={product.id}
//                       layout
//                       initial={{ opacity: 0, y: -10 }}
//                       animate={{ opacity: 1, y: 0 }}
//                       exit={{
//                         opacity: 0,
//                         x: -100,
//                         scale: 0.95,
//                         transition: { duration: 0.3 }
//                       }}
//                       sx={{
//                         backgroundColor: deleteLoader === product.id ? 'rgba(255,0,0,0.04)' : 'transparent',
//                         transition: 'background-color 0.3s ease'
//                       }}
//                     >
//                       <TableCell>
//                         <Box>
//                           <Typography variant='body2'>{product.name}</Typography>
//                           {product.variation?.attributes && product.variation.attributes.length > 0 && (
//                             <Typography variant='caption' color='text.secondary'>
//                               {product.variation.attributes.map((attr: any) => 
//                                 `${attr.attributeName}: ${attr.value}`
//                               ).join(' | ')}
//                             </Typography>
//                           )}
//                         </Box>
//                       </TableCell>

//                       <TableCell sx={{ textAlign: 'center' }}>
//                         <Typography variant='body2' fontWeight={500}>
//                           {product.quantity}
//                         </Typography>
//                       </TableCell>

//                       <TableCell sx={{ textAlign: 'right' }}>
//                         ${product.price.toFixed(2)}
//                       </TableCell>

//                       <TableCell sx={{ textAlign: 'right', fontWeight: 600 }}>
//                         ${(product.price * product.quantity).toFixed(2)}
//                       </TableCell>

//                       <TableCell sx={{ textAlign: 'center' }}>
//                         <Box sx={{ display: 'flex', justifyContent: 'center', gap: 0.5 }}>
//                           <IconButton
//                             aria-label='delete'
//                             color='error'
//                             size='small'
//                             onClick={() => handleRemove(product.id, product.posUid, product.orderItemUid)}
//                             disabled={deleteLoader === product.id}
//                           >
//                             {deleteLoader === product.id ? (
//                               <CircularProgress size={16} />
//                             ) : (
//                               <Icon icon='tabler:trash' fontSize='inherit' />
//                             )}
//                           </IconButton>
//                           <IconButton
//                             aria-label='edit'
//                             color='primary'
//                             size='small'
//                             onClick={() => handleEditClick(product)}
//                           >
//                             <Icon icon='tabler:edit' fontSize='inherit' />
//                           </IconButton>
//                         </Box>
//                       </TableCell>
//                     </MotionTableRow>
//                   ))}
//                 </AnimatePresence>
//               </TableBody>
//             </Table>
//           </TableContainer>
//         </Box>
//       ) : (
//         <Typography variant='body2' sx={{ mb: 2, textAlign: 'center', mt: 4, py: 4 }}>
//           🛒 No items in cart. Add products to get started.
//         </Typography>
//       )}

//       {/* Edit Dialog */}
//       {selectedProduct && (
//         <ProductDialog
//           open={editDialogOpen}
//           onClose={() => {
//             setEditDialogOpen(false)
//             setSelectedProduct(null)
//             setSelectedCartItem(null)
//           }}
//           product={selectedProduct}
//           editItem={selectedCartItem}
//           isEdit={true}
//         />
//       )}
//     </Fragment>
//   )
// }

// export default OrderListTable


// final 
// import React, { Fragment, useState } from 'react'
// import {
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   IconButton,
//   Box,
//   Paper,
//   Typography,
//   Button,
//   CircularProgress,
//   Chip
// } from '@mui/material'

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

// // ** Hooks
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'

// // ** Action
// import { removeFromCart } from 'src/store/pages/pos/cartSlice'

// // ** Dispatch
// import { useDispatch } from 'react-redux'

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

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

// import { motion, AnimatePresence } from 'framer-motion'
// import ProductDialog from './payment/modal/AddToCartModal'

// // ** Types
// interface CartItem {
//   id: string
//   productUid: string
//   name: string
//   price: number
//   quantity: number
//   image: string
//   stockQty?: number
//   variation: any
//   orderItemUid?: string
//   posUid?: string
//   productType?: string
//   isInventoryManaged?: boolean
//   selectedStaff?: string[]
// }

// const MotionTableRow = motion.create(TableRow)

// const OrderListTable = () => {
//   const [editDialogOpen, setEditDialogOpen] = useState<boolean>(false)
//   const [selectedProduct, setSelectedProduct] = useState<any>(null)
//   const [selectedCartItem, setSelectedCartItem] = useState<CartItem | null>(null)
//   const [deleteLoader, setDeleteLoader] = useState<string | null>(null)
//   const cartSlice = useSelector((state: RootState) => state.cartSlice)
//   const entities = cartSlice?.entities || {}
//   const products = Object.values(entities) as CartItem[]

//   const dispatch = useDispatch()

//   // Check if edit should be hidden for this product
//   const shouldHideEdit = (product: CartItem): boolean => {
//     // Service-based products: hide edit
//     if (product.productType === 'ServiceBased') {
//       return true
//     }
//     // ReadyToSell products: hide edit if inventory not managed OR stock is 0
//     if (product.productType === 'ReadyToSell') {
//       // If inventory is not managed, hide edit
//       if (!product.isInventoryManaged) return true
//       // If inventory is managed but stock is 0, hide edit
//       if (product.isInventoryManaged && product.stockQty === 0) return true
//     }
//     return false
//   }

//   const handleEditClick = (product: CartItem) => {
//     // If edit should be hidden, return early
//     if (shouldHideEdit(product)) {
//       toast.error('This item cannot be edited', { style: { zIndex: 999999 } })
//       return
//     }
    
//     setSelectedCartItem(product)
//     const productData = {
//       uid: product.productUid || product.id,
//       name: product.name,
//       description: '',
//       productType: product.productType || 'ReadyToSell',
//       isInventoryManaged: product.isInventoryManaged || false,
//       variations: product.variation ? [product.variation] : [],
//       // Include staff data if service-based
//       ...(product.productType === 'ServiceBased' && {
//         staffs: product.selectedStaff?.map(uid => ({ uid })) || []
//       })
//     }
//     setSelectedProduct(productData)
//     setEditDialogOpen(true)
//   }

//   const handleRemove = async (id: string, posUid?: string, orderItemUid?: string) => {
//     if (!posUid || !orderItemUid) {
//       dispatch(removeFromCart(id))
//       toast.success('Item removed from cart', { style: { zIndex: 999999 } })
//       return
//     }

//     setDeleteLoader(id)
//     try {
//       const deleteUrl = `${endpoints.pos.posOrder.removeItem}${posUid}/items/${orderItemUid}`
//       await axios.delete(deleteUrl)
//       dispatch(removeFromCart(id))
//       toast.success('Item removed from order!', { style: { zIndex: 999999 } })
//     } catch (error: any) {
//       console.error('Error deleting item:', error)
//       toast.error(error?.response?.data?.message || 'Failed to delete item', { 
//         style: { zIndex: 999999 } 
//       })
//       dispatch(removeFromCart(id))
//     } finally {
//       setDeleteLoader(null)
//     }
//   }

//   const handleClearAll = () => {
//     if (products.length === 0) return
//     products.forEach(item => {
//       dispatch(removeFromCart(item.id))
//     })
//   }

//   const totalItems = products.reduce((sum, item) => sum + item.quantity, 0)

//   return (
//     <Fragment>
//       {products.length > 0 ? (
//         <Box>
//           <Box
//             sx={{
//               display: 'flex',
//               alignItems: 'center',
//               justifyContent: 'space-between',
//               borderRadius: 1,
//               mt: 4
//             }}
//           >
//             <Typography variant='h6' sx={{ mt: 4, mb: 2 }}>
//               Order Details ({totalItems} items)
//             </Typography>
//             <Button variant='outlined' size='small' color='error' onClick={handleClearAll}>
//               Clear All
//             </Button>
//           </Box>
//           <TableContainer component={Paper}>
//             <Table size='small'>
//               <TableHead>
//                 <TableRow>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100' }}>Item</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'center' }}>QTY</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right' }}>Price</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right' }}>Total Cost</TableCell>
//                   <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'center' }}>Actions</TableCell>
//                 </TableRow>
//               </TableHead>

//               <TableBody>
//                 <AnimatePresence>
//                   {products.map((product) => {
//                     const hideEdit = shouldHideEdit(product)
//                     // Only show "Out of Stock" for inventory managed products with stock 0
//                     const showOutOfStock = product.productType === 'ReadyToSell' && 
//                                           product.isInventoryManaged === true &&
//                                           product.stockQty === 0
                    
//                     return (
//                       <MotionTableRow
//                         key={product.id}
//                         layout
//                         initial={{ opacity: 0, y: -10 }}
//                         animate={{ opacity: 1, y: 0 }}
//                         exit={{
//                           opacity: 0,
//                           x: -100,
//                           scale: 0.95,
//                           transition: { duration: 0.3 }
//                         }}
//                         sx={{
//                           backgroundColor: deleteLoader === product.id ? 'rgba(255,0,0,0.04)' : 'transparent',
//                           transition: 'background-color 0.3s ease'
//                         }}
//                       >
//                         <TableCell>
//                           <Box>
//                             <Typography variant='body2'>{product.name}</Typography>
//                             {product.productType && (
//                               <Chip 
//                                 label={product.productType} 
//                                 size="small" 
//                                 color={product.productType === 'ServiceBased' ? 'secondary' : 'primary'}
//                                 sx={{ mr: 0.5 }}
//                               />
//                             )}
//                             {product.variation?.attributes && product.variation.attributes.length > 0 && (
//                               <Typography variant='caption' color='text.secondary' display="block">
//                                 {product.variation.attributes.map((attr: any) => 
//                                   `${attr.attributeName}: ${attr.value}`
//                                 ).join(' | ')}
//                               </Typography>
//                             )}
//                             {product.productType === 'ServiceBased' && product.selectedStaff && product.selectedStaff.length > 0 && (
//                               <Typography variant='caption' color='secondary'>
//                                 Staff: {product.selectedStaff.length} selected
//                               </Typography>
//                             )}
//                             {showOutOfStock && (
//                               <Typography variant='caption' color='error' fontWeight='bold'>
//                                 Out of Stock
//                               </Typography>
//                             )}
//                           </Box>
//                         </TableCell>

//                         <TableCell sx={{ textAlign: 'center' }}>
//                           <Typography variant='body2' fontWeight={500}>
//                             {product.quantity}
//                           </Typography>
//                         </TableCell>

//                         <TableCell sx={{ textAlign: 'right' }}>
//                           ${product.price.toFixed(2)}
//                         </TableCell>

//                         <TableCell sx={{ textAlign: 'right', fontWeight: 600 }}>
//                           ${(product.price * product.quantity).toFixed(2)}
//                         </TableCell>

//                         <TableCell sx={{ textAlign: 'center' }}>
//                           <Box sx={{ display: 'flex', justifyContent: 'center', gap: 0.5 }}>
//                             <IconButton
//                               aria-label='delete'
//                               color='error'
//                               size='small'
//                               onClick={() => handleRemove(product.id, product.posUid, product.orderItemUid)}
//                               disabled={deleteLoader === product.id}
//                             >
//                               {deleteLoader === product.id ? (
//                                 <CircularProgress size={16} />
//                               ) : (
//                                 <Icon icon='tabler:trash' fontSize='inherit' />
//                               )}
//                             </IconButton>
//                             {!hideEdit && (
//                               <IconButton
//                                 aria-label='edit'
//                                 color='primary'
//                                 size='small'
//                                 onClick={() => handleEditClick(product)}
//                               >
//                                 <Icon icon='tabler:edit' fontSize='inherit' />
//                               </IconButton>
//                             )}
//                           </Box>
//                         </TableCell>
//                       </MotionTableRow>
//                     )
//                   })}
//                 </AnimatePresence>
//               </TableBody>
//             </Table>
//           </TableContainer>
//         </Box>
//       ) : (
//         <Typography variant='body2' sx={{ mb: 2, textAlign: 'center', mt: 4, py: 4 }}>
//           🛒 No items in cart. Add products to get started.
//         </Typography>
//       )}

//       {/* Edit Dialog */}
//       {selectedProduct && (
//         <ProductDialog
//           open={editDialogOpen}
//           onClose={() => {
//             setEditDialogOpen(false)
//             setSelectedProduct(null)
//             setSelectedCartItem(null)
//           }}
//           product={selectedProduct}
//           editItem={selectedCartItem}
//           isEdit={true}
//         />
//       )}
//     </Fragment>
//   )
// }

// export default OrderListTable

// image issue 
import React, { Fragment, useState } from 'react'
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Box,
  Paper,
  Typography,
  Button,
  CircularProgress,
  Chip,
  Tooltip
} from '@mui/material'

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

// ** Hooks
import { useSelector } from 'react-redux'
import { RootState } from 'src/store'

// ** Action
import { removeFromCart } from 'src/store/pages/pos/cartSlice'

// ** Dispatch
import { useDispatch } from 'react-redux'

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

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

import { motion, AnimatePresence } from 'framer-motion'
import ProductDialog from './payment/modal/AddToCartModal'

// ** Types
interface CartItem {
  id: string
  productUid: string
  name: string
  price: number
  mrp?: number
  taxAmount?: number
  quantity: number
  image: string
  stockQty?: number
  variation: any
  orderItemUid?: string
  posUid?: string
  productType?: string
  isInventoryManaged?: boolean
  selectedStaff?: string[]
}

const MotionTableRow = motion.create(TableRow)

const OrderListTable = () => {
  const [editDialogOpen, setEditDialogOpen] = useState<boolean>(false)
  const [selectedProduct, setSelectedProduct] = useState<any>(null)
  const [selectedCartItem, setSelectedCartItem] = useState<CartItem | null>(null)
  const [deleteLoader, setDeleteLoader] = useState<string | null>(null)
  const cartSlice = useSelector((state: RootState) => state.cartSlice)
  const entities = cartSlice?.entities || {}
  const products = Object.values(entities) as CartItem[]

  const dispatch = useDispatch()

  // Check if edit should be hidden for this product
  const shouldHideEdit = (product: CartItem): boolean => {
    // Service-based products: hide edit
    if (product.productType === 'ServiceBased') {
      return true
    }

    // ReadyToSell products: hide edit if inventory not managed OR stock is 0
    if (product.productType === 'ReadyToSell') {
      // If inventory is not managed, hide edit
      if (!product.isInventoryManaged) return true

      // If inventory is managed but stock is 0, hide edit
      if (product.isInventoryManaged && product.stockQty === 0) return true
    }
    return false
  }

  const handleEditClick = (product: CartItem) => {
    // If edit should be hidden, return early
    if (shouldHideEdit(product)) {
      toast.error('This item cannot be edited', { style: { zIndex: 999999 } })
      return
    }
    
    setSelectedCartItem(product)
    const productData = {
      uid: product.productUid || product.id,
      name: product.name,
      description: '',
      productType: product.productType || 'ReadyToSell',
      isInventoryManaged: product.isInventoryManaged || false,
      variations: product.variation ? [product.variation] : [],

      // Include staff data if service-based
      ...(product.productType === 'ServiceBased' && {
        staffs: product.selectedStaff?.map(uid => ({ uid })) || []
      })
    }
    setSelectedProduct(productData)
    setEditDialogOpen(true)
  }

  const handleRemove = async (id: string, posUid?: string, orderItemUid?: string) => {
    if (!posUid || !orderItemUid) {
      dispatch(removeFromCart(id))
      toast.success('Item removed from cart', { style: { zIndex: 999999 } })
      return
    }

    setDeleteLoader(id)
    try {
      const deleteUrl = `${endpoints.pos.posOrder.removeItem}${posUid}/items/${orderItemUid}`
      await axios.delete(deleteUrl)
      dispatch(removeFromCart(id))
      toast.success('Item removed from order!', { style: { zIndex: 999999 } })
    } catch (error: any) {
      console.error('Error deleting item:', error)
      toast.error(error?.response?.data?.message || 'Failed to delete item', { 
        style: { zIndex: 999999 } 
      })
      dispatch(removeFromCart(id))
    } finally {
      setDeleteLoader(null)
    }
  }

  const handleClearAll = () => {
    if (products.length === 0) return
    products.forEach(item => {
      dispatch(removeFromCart(item.id))
    })
  }

  const totalItems = products.reduce((sum, item) => sum + item.quantity, 0)

  return (
    <Fragment>
      {products.length > 0 ? (
        <Box>
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              borderRadius: 1,
              mt: 4
            }}
          >
            <Typography variant='h6' sx={{ mt: 4, mb: 2 }}>
              Order Details ({totalItems} items)
            </Typography>
            <Button variant='outlined' size='small' color='error' onClick={handleClearAll}>
              Clear All
            </Button>
          </Box>
          <TableContainer component={Paper} sx={{ overflowX: 'auto' }}>
            <Table size='small' sx={{ minWidth: 500 }}>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', width: '20%' }}>
                    Item
                  </TableCell>
                  <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'center', width: '5%' }}>
                    QTY
                  </TableCell>
                  <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right', width: '20%' }}>
                    Price
                  </TableCell>
                  <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'right', width: '5%' }}>
                    Total
                  </TableCell>
                  <TableCell sx={{ fontWeight: 'bold', bgcolor: 'grey.100', textAlign: 'center', width: '5%' }}>
                    Actions
                  </TableCell>
                </TableRow>
              </TableHead>

              <TableBody>
                <AnimatePresence>
                  {products.map((product) => {
                    const hideEdit = shouldHideEdit(product)

                    // Only show "Out of Stock" for inventory managed products with stock 0
                    const showOutOfStock = product.productType === 'ReadyToSell' && 
                                          product.isInventoryManaged === true &&
                                          product.stockQty === 0
                    
                    // Use price (which should be finalAmount) for display
                    const unitPrice = product.price || product.mrp || 0
                    const totalCost = unitPrice * product.quantity
                    
                    return (
                      <MotionTableRow
                        key={product.id}
                        layout
                        initial={{ opacity: 0, y: -10 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{
                          opacity: 0,
                          x: -100,
                          scale: 0.95,
                          transition: { duration: 0.3 }
                        }}
                        sx={{
                          backgroundColor: deleteLoader === product.id ? 'rgba(255,0,0,0.04)' : 'transparent',
                          transition: 'background-color 0.3s ease',
                          '&:hover': {
                            backgroundColor: 'action.hover'
                          }
                        }}
                      >
                        {/* Item Column */}
                        <TableCell>
                          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
                            <Typography variant='body2' fontWeight={600}>
                              {product.name}
                            </Typography>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, flexWrap: 'wrap' }}>
                              {product.productType && (
                                <Chip 
                                  label={product.productType} 
                                  size="small" 
                                  color={product.productType === 'ServiceBased' ? 'secondary' : 'primary'}
                                  sx={{ height: 20, fontSize: '0.625rem' }}
                                />
                              )}
                              {product.variation?.attributes && product.variation.attributes.length > 0 && (
                                <Typography variant='caption' color='text.secondary'>
                                  {product.variation.attributes.map((attr: any) => 
                                    `${attr.attributeName}: ${attr.value}`
                                  ).join(' | ')}
                                </Typography>
                              )}
                            </Box>
                            {product.productType === 'ServiceBased' && product.selectedStaff && product.selectedStaff.length > 0 && (
                              <Typography variant='caption' color='secondary'>
                                Staff: {product.selectedStaff.length} selected
                              </Typography>
                            )}
                            {showOutOfStock && (
                              <Typography variant='caption' color='error' fontWeight='bold'>
                                Out of Stock
                              </Typography>
                            )}
                          </Box>
                        </TableCell>

                        {/* QTY Column */}
                        <TableCell sx={{ textAlign: 'center', verticalAlign: 'middle' }}>
                          <Typography variant='body2' fontWeight={600}>
                            {product.quantity}
                          </Typography>
                        </TableCell>

                        {/* Unit Price Column */}
                        <TableCell sx={{ textAlign: 'right', verticalAlign: 'middle' }}>
                          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                            <Typography variant='body2' fontWeight={700} color="primary.main">
                              ${unitPrice.toFixed(2)}
                            </Typography>
                            {product.mrp && product.taxAmount !== undefined && product.taxAmount > 0 && (
                              <Tooltip title={`MRP: $${product.mrp.toFixed(2)} + Tax: $${product.taxAmount.toFixed(2)}`}>
                                <Typography variant='caption' color='text.secondary' sx={{ fontSize: '0.65rem' }}>
                                  MRP: ${product.mrp.toFixed(2)} + Tax: ${product.taxAmount.toFixed(2)}
                                </Typography>
                              </Tooltip>
                            )}
                          </Box>
                        </TableCell>

                        {/* Total Cost Column */}
                        <TableCell sx={{ textAlign: 'right', verticalAlign: 'middle' }}>
                          <Typography variant='body2' fontWeight={700}>
                            ${totalCost.toFixed(2)}
                          </Typography>
                        </TableCell>

                        {/* Actions Column */}
                        <TableCell sx={{ textAlign: 'center', verticalAlign: 'middle' }}>
                          <Box sx={{ display: 'flex', justifyContent: 'center', gap: 0.5 }}>
                            <IconButton
                              aria-label='delete'
                              color='error'
                              size='small'
                              onClick={() => handleRemove(product.id, product.posUid, product.orderItemUid)}
                              disabled={deleteLoader === product.id}
                              sx={{ 
                                '&:hover': { 
                                  backgroundColor: 'error.light',
                                  color: 'error.dark'
                                }
                              }}
                            >
                              {deleteLoader === product.id ? (
                                <CircularProgress size={18} />
                              ) : (
                                <Icon icon='tabler:trash' fontSize={18} />
                              )}
                            </IconButton>
                            {!hideEdit && (
                              <IconButton
                                aria-label='edit'
                                color='primary'
                                size='small'
                                onClick={() => handleEditClick(product)}
                                sx={{ 
                                  '&:hover': { 
                                    backgroundColor: 'primary.light',
                                    color: 'primary.dark'
                                  }
                                }}
                              >
                                <Icon icon='tabler:edit' fontSize={18} />
                              </IconButton>
                            )}
                          </Box>
                        </TableCell>
                      </MotionTableRow>
                    )
                  })}
                </AnimatePresence>
              </TableBody>
            </Table>
          </TableContainer>
        </Box>
      ) : (
        <Typography variant='body2' sx={{ mb: 2, textAlign: 'center', mt: 4, py: 4 }}>
          🛒 No items in cart. Add products to get started.
        </Typography>
      )}

      {/* Edit Dialog */}
      {selectedProduct && (
        <ProductDialog
          open={editDialogOpen}
          onClose={() => {
            setEditDialogOpen(false)
            setSelectedProduct(null)
            setSelectedCartItem(null)
          }}
          product={selectedProduct}
          editItem={selectedCartItem}
          isEdit={true}
        />
      )}
    </Fragment>
  )
}

export default OrderListTable