// // src/views/components/product/VariationDetails.tsx

// import React, { useEffect, useState } from 'react'
// import {
//   Grid,
//   TextField,
//   Button,
//   Typography,
//   Box,
//   Paper,
//   Switch,
//   FormControlLabel,
//   Divider,
//   CircularProgress
// } from '@mui/material'
// import { Controller, useFieldArray, Control, useWatch } from 'react-hook-form'
// import Icon from 'src/@core/components/icon'
// import { ProductFormValues, Category, Attribute } from './types'
// import { validateUnit, validateAttributeValue, getFullImageUrl } from './hooks'
// import toast from 'react-hot-toast'
// import axios from 'src/configs/axios'

// interface VariationDetailsProps {
//   control: Control<ProductFormValues>
//   errors: any
//   productType: string
//   trackStock: boolean
//   categoryAttributes: Attribute[]
//   selectedCategory: Category | undefined
//   isSubmitting: boolean
//   onRecalcVariation: (index: number, mrpValue: string) => void
//   onImageChange: (index: number, file: File | null) => void
// }

// const VariationDetails = ({
//   setVariationMRP,
//   control,
//   errors,
//   productType,
//   trackStock,
//   categoryAttributes,
//   selectedCategory,
//   isSubmitting,
//   onRecalcVariation,
//   onImageChange
// }: VariationDetailsProps) => {
//   const { fields: variationFields, append: appendVariation, remove: removeVariation } = useFieldArray({
//     control,
//     name: 'variations'
//   })

//   const [viewImageLoading, setViewImageLoading] = useState<{ [key: number]: boolean }>({})

//   // Watch variations to get image previews
//   const variations = useWatch({
//     control,
//     name: 'variations'
//   }) || []


// useEffect(()=>{
//   if (variations) {
//     setVariationMRP(variations?.[0]?.mrp);
//   }
// },[variations])

//   const handleViewImage = async (imagePath: string, index: number) => {
//     if (!imagePath) {
//       toast.error('No image to view')
//       return
//     }

//     setViewImageLoading(prev => ({ ...prev, [index]: true }))

//     try {
//       let imageUrl = ''

//       // If it's already a blob URL or data URL, use it directly
//       if (imagePath.startsWith('blob:') || imagePath.startsWith('data:')) {
//         imageUrl = imagePath
//         // Open directly
//         window.open(imageUrl, '_blank')
//         setViewImageLoading(prev => ({ ...prev, [index]: false }))
//         return
//       }

//       // Get full URL
//       const fullUrl = getFullImageUrl(imagePath)
      
//       // Fetch the image as blob with authentication
//       const response = await axios.get(fullUrl, {
//         responseType: 'blob',
//         headers: {
//           'Accept': 'image/*'
//         }
//       })

//       // Create blob URL
//       const blob = response.data
//       imageUrl = URL.createObjectURL(blob)

//       // Open the image in a new window/tab
//       const newWindow = window.open('', '_blank')
//       if (newWindow) {
//         newWindow.document.write(`
//           <!DOCTYPE html>
//           <html>
//             <head>
//               <title>Product Image</title>
//               <style>
//                 * { margin: 0; padding: 0; box-sizing: border-box; }
//                 body {
//                   display: flex;
//                   justify-content: center;
//                   align-items: center;
//                   min-height: 100vh;
//                   background-color: #f5f5f5;
//                   font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
//                 }
//                 .container {
//                   display: flex;
//                   flex-direction: column;
//                   align-items: center;
//                   justify-content: center;
//                   width: 100%;
//                   height: 100vh;
//                   padding: 20px;
//                 }
//                 .image-wrapper {
//                   background: white;
//                   border-radius: 12px;
//                   box-shadow: 0 4px 24px rgba(0,0,0,0.12);
//                   padding: 20px;
//                   max-width: 90%;
//                   max-height: 85vh;
//                   display: flex;
//                   justify-content: center;
//                   align-items: center;
//                 }
//                 img {
//                   max-width: 100%;
//                   max-height: 75vh;
//                   object-fit: contain;
//                   border-radius: 4px;
//                 }
//                 .close-btn {
//                   position: fixed;
//                   top: 20px;
//                   right: 20px;
//                   padding: 10px 24px;
//                   background-color: #fff;
//                   border: 1px solid #e0e0e0;
//                   border-radius: 8px;
//                   cursor: pointer;
//                   font-size: 14px;
//                   font-weight: 500;
//                   box-shadow: 0 2px 8px rgba(0,0,0,0.08);
//                   transition: all 0.2s ease;
//                   z-index: 1000;
//                   color: #333;
//                 }
//                 .close-btn:hover {
//                   background-color: #f5f5f5;
//                   box-shadow: 0 4px 12px rgba(0,0,0,0.12);
//                 }
//                 .loading {
//                   text-align: center;
//                   color: #666;
//                   font-size: 16px;
//                   padding: 40px;
//                 }
//                 .error {
//                   text-align: center;
//                   color: #d32f2f;
//                   font-size: 16px;
//                   padding: 40px;
//                   display: none;
//                 }
//                 .spinner {
//                   display: inline-block;
//                   width: 40px;
//                   height: 40px;
//                   border: 4px solid #f3f3f3;
//                   border-top: 4px solid #1976d2;
//                   border-radius: 50%;
//                   animation: spin 1s linear infinite;
//                   margin-bottom: 16px;
//                 }
//                 @keyframes spin {
//                   0% { transform: rotate(0deg); }
//                   100% { transform: rotate(360deg); }
//                 }
//               </style>
//             </head>
//             <body>
//               <button class="close-btn" onclick="window.close()">✕ Close</button>
//               <div class="container">
//                 <div class="image-wrapper">
//                   <img 
//                     src="${imageUrl}" 
//                     alt="Product Image"
//                     onerror="this.style.display='none'; document.querySelector('.error').style.display='block'; document.querySelector('.loading').style.display='none'"
//                     onload="document.querySelector('.loading').style.display='none'"
//                     style="display: block;"
//                   />
//                   <div class="loading" id="loading">
//                     <div class="spinner"></div>
//                     <div>Loading image...</div>
//                   </div>
//                   <div class="error" id="error">
//                     <div style="font-size: 48px; margin-bottom: 16px;">🖼️</div>
//                     <div>Failed to load image.</div>
//                     <div style="font-size: 14px; margin-top: 8px; color: #999;">Please try again or check the image URL.</div>
//                   </div>
//                 </div>
//               </div>
//               <script>
//                 // Clean up blob URL when window is closed
//                 window.addEventListener('beforeunload', function() {
//                   URL.revokeObjectURL('${imageUrl}')
//                 })
//               </script>
//             </body>
//           </html>
//         `)
//         newWindow.document.close()
//         setViewImageLoading(prev => ({ ...prev, [index]: false }))
//       } else {
//         // If popup is blocked, open in new tab
//         window.open(imageUrl, '_blank')
//         setViewImageLoading(prev => ({ ...prev, [index]: false }))
//       }
//     } catch (error) {
//       console.error('Error viewing image:', error)
//       toast.error('Failed to load image. Please try again.')
//       setViewImageLoading(prev => ({ ...prev, [index]: false }))
//     }
//   }

//   return (
//     <Grid container spacing={4}>
//       <Grid item xs={12}>
//         <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
//           <Typography variant='subtitle1' fontWeight={600}>
//             Add Product Variations
//           </Typography>
//         </Box>

//         {productType !== 'ServiceBased' && (
//           <Box sx={{ mb: 3 }}>
//             <Controller
//               name='trackStock'
//               control={control}
//               render={({ field }) => (
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       {...field}
//                       checked={field.value}
//                       onChange={(e) => field.onChange(e.target.checked)}
//                       color='primary'
//                     />
//                   }
//                   label='Track Stock'
//                 />
//               )}
//             />
//           </Box>
//         )}

//         {variationFields.map((field, index) => {
//           // Get the current variation data from watched values
//           const currentVariation = variations[index] || {}
//           const imagePreview = currentVariation.imagePreview || ''
//           const isLoading = viewImageLoading[index] || false

//           return (
//             <Paper key={field.id} sx={{ p: 3, mb: 3, position: 'relative', overflow: 'visible' }}>
//               <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
//                 <Typography variant='subtitle2' fontWeight={600}>
//                   Variation {index + 1}
//                 </Typography>
//                 {index > 0 && (
//                   <Button
//                     size='small'
//                     color='error'
//                     variant='outlined'
//                     startIcon={<Icon icon='tabler:trash' />}
//                     onClick={() => removeVariation(index)}
//                   >
//                     Remove Variation
//                   </Button>
//                 )}
//               </Box>

//               <Box sx={{ mb: 3 }}>
//                 <Typography variant='body2' fontWeight={500} sx={{ mb: 1 }}>
//                   Upload Image
//                 </Typography>
//                 <Box
//                   sx={{
//                     border: '2px dashed',
//                     borderColor: imagePreview ? 'primary.main' : 'divider',
//                     borderRadius: 2,
//                     p: imagePreview ? 2 : 4,
//                     textAlign: 'center',
//                     cursor: 'pointer',
//                     '&:hover': { borderColor: 'primary.main' },
//                     position: 'relative',
//                     backgroundColor: imagePreview ? 'action.hover' : 'transparent'
//                   }}
//                 >
//                   <input
//                     type='file'
//                     accept='image/*'
//                     onChange={(e) => {
//                       const file = e.target.files?.[0] || null
//                       onImageChange(index, file)
//                     }}
//                     style={{ display: 'none' }}
//                     id={`image-upload-${index}`}
//                   />
//                   <label htmlFor={`image-upload-${index}`} style={{ cursor: 'pointer', display: 'block' }}>
//                     {imagePreview ? (
//                       <Box sx={{ position: 'relative' }}>
//                         <Box
//                           component='img'
//                           src={imagePreview.startsWith('blob:') || imagePreview.startsWith('data:') ? imagePreview : getFullImageUrl(imagePreview)}
//                           alt={`Variation ${index + 1}`}
//                           sx={{ 
//                             maxHeight: 120, 
//                             borderRadius: 1,
//                             display: 'block',
//                             margin: '0 auto'
//                           }}
//                           onError={(e) => {
//                             console.error('Image load error:', imagePreview)
//                             e.currentTarget.style.display = 'none'
//                           }}
//                         />
//                         <Box sx={{ mt: 1, display: 'flex', gap: 1, justifyContent: 'center' }}>
//                           <Button
//                             size='small'
//                             variant='outlined'
//                             disabled={isLoading}
//                             onClick={(e) => {
//                               e.preventDefault()
//                               handleViewImage(imagePreview, index)
//                             }}
//                             startIcon={isLoading ? <CircularProgress size={16} /> : undefined}
//                           >
//                             {isLoading ? 'Loading...' : 'View'}
//                           </Button>
//                           <Button
//                             size='small'
//                             variant='outlined'
//                             color='error'
//                             onClick={(e) => {
//                               e.preventDefault()
//                               onImageChange(index, null)
//                             }}
//                           >
//                             Remove
//                           </Button>
//                         </Box>
//                       </Box>
//                     ) : (
//                       <>
//                         <Icon icon='tabler:cloud-upload' style={{ fontSize: 40, color: '#9E9E9E' }} />
//                         <Typography variant='body2' color='text.secondary'>
//                           Click to upload image
//                         </Typography>
//                         <Typography variant='caption' color='text.secondary'>
//                           (JPG, PNG, GIF)
//                         </Typography>
//                       </>
//                     )}
//                   </label>
//                 </Box>
//               </Box>

//               <Grid container spacing={3}>
//                 <Grid item xs={12} md={4}>
//                   <Controller
//                     name={`variations.${index}.mrp`}
//                     control={control}
//                     rules={{ required: 'MRP is required' }}
//                     render={({ field }) => (
//                       <TextField
//                         {...field}
//                         fullWidth
//                         label='MRP *'
//                         placeholder='Enter MRP'
//                         size='small'
//                         error={!!errors.variations?.[index]?.mrp}
//                         helperText={errors.variations?.[index]?.mrp?.message}
//                         disabled={isSubmitting}
//                         onChange={(e) => {
//                           const val = e.target.value
//                           field.onChange(val)
//                           onRecalcVariation(index, val)
//                         }}
//                       />
//                     )}
//                   />
//                 </Grid>

//                 {productType !== 'ServiceBased' && trackStock && (
//                   <Grid item xs={12} md={4}>
//                     <Controller
//                       name={`variations.${index}.stockQty`}
//                       control={control}
//                       rules={{ required: 'Stock QTY is required' }}
//                       render={({ field }) => (
//                         <TextField
//                           {...field}
//                           fullWidth
//                           label='Stock QTY *'
//                           placeholder='Enter Stock QTY'
//                           type='text'
//                           size='small'
//                           error={!!errors.variations?.[index]?.stockQty}
//                           helperText={errors.variations?.[index]?.stockQty?.message}
//                           disabled={isSubmitting}
//                         />
//                       )}
//                     />
//                   </Grid>
//                 )}

//                 <Grid item xs={12} md={4}>
//                   <Controller
//                     name={`variations.${index}.noOfItems`}
//                     control={control}
//                     rules={{ required: 'Number of items is required' }}
//                     render={({ field }) => (
//                       <TextField
//                         {...field}
//                         fullWidth
//                         label='No. of Items *'
//                         placeholder='Enter No. of Items'
//                         size='small'
//                         error={!!errors.variations?.[index]?.noOfItems}
//                         helperText={errors.variations?.[index]?.noOfItems?.message}
//                         disabled={isSubmitting}
//                       />
//                     )}
//                   />
//                 </Grid>

//                 <Grid item xs={12} md={4}>
//                   <Controller
//                     name={`variations.${index}.unit`}
//                     control={control}
//                     rules={{ 
//                       required: 'Unit is required',
//                       validate: (value) => validateUnit(value) || 'Unit should only contain alphabetic characters (A-Z, a-z)'
//                     }}
//                     render={({ field }) => (
//                       <TextField
//                         {...field}
//                         fullWidth
//                         label='Unit *'
//                         placeholder='Enter Unit (e.g. pcs, kg, g)'
//                         size='small'
//                         error={!!errors.variations?.[index]?.unit}
//                         helperText={errors.variations?.[index]?.unit?.message || 'Only alphabetic characters allowed'}
//                         disabled={isSubmitting}
//                       />
//                     )}
//                   />
//                 </Grid>

//                 <Grid item xs={12} md={4}>
//                   <Controller
//                     name={`variations.${index}.calculatedAmount`}
//                     control={control}
//                     render={({ field }) => (
//                       <TextField
//                         fullWidth
//                         label='Calculated Amount'
//                         value={field.value ?? 0}
//                         size='small'
//                         disabled
//                       />
//                     )}
//                   />
//                 </Grid>

//                 <Grid item xs={12} md={4}>
//                   <Controller
//                     name={`variations.${index}.finalAmount`}
//                     control={control}
//                     render={({ field }) => (
//                       <TextField
//                         fullWidth
//                         label='Final Amount'
//                         value={field.value ?? 0}
//                         size='small'
//                         disabled
//                       />
//                     )}
//                   />
//                 </Grid>
//               </Grid>

//               {categoryAttributes.length > 0 && (
//                 <Box sx={{ mt: 3 }}>
//                   <Divider sx={{ mb: 2 }} />
//                   <Typography variant='body2' fontWeight={600} sx={{ mb: 2 }}>
//                     {selectedCategory?.name} Variations
//                   </Typography>
//                   <Grid container spacing={3}>
//                     {categoryAttributes.map((attr, attrIndex) => (
//                       <Grid item xs={12} md={4} key={`${attr.attributeName}-${attrIndex}`}>
//                         <Controller
//                           name={`variations.${index}.attributeValues.${attrIndex}.value`}
//                           control={control}
//                           rules={{
//                             ...(attr.isRequired ? { required: `${attr.attributeName} is required` } : {}),
//                             validate: (value) => {
//                               if (value && !validateAttributeValue(value, attr.isRequired)) {
//                                 return 'Value should only contain alphanumeric characters and spaces'
//                               }
//                               return true
//                             }
//                           }}
//                           render={({ field }) => (
//                             <TextField
//                               {...field}
//                               fullWidth
//                               size='small'
//                               label={`${attr.attributeName}${attr.isRequired ? ' *' : ''}`}
//                               placeholder={`Enter ${attr.attributeName}`}
//                               disabled={isSubmitting}
//                               error={!!errors.variations?.[index]?.attributeValues?.[attrIndex]?.value}
//                               helperText={errors.variations?.[index]?.attributeValues?.[attrIndex]?.value?.message || 'Alphanumeric and spaces only'}
//                               onChange={(e) => {
//                                 field.onChange(e.target.value)
//                               }}
//                             />
//                           )}
//                         />
//                       </Grid>
//                     ))}
//                   </Grid>
//                 </Box>
//               )}
//             </Paper>
//           )
//         })}

//         <Button
//           variant='outlined'
//           startIcon={<Icon icon='tabler:plus' />}
//           onClick={() => appendVariation({
//             size: '',
//             mrp: '',
//             stockQty: 0,
//             noOfItems: '1',
//             unit: 'pcs',
//             calculatedAmount: 0,
//             finalAmount: 0,
//             image: null,
//             imagePreview: '',
//             attributeValues: categoryAttributes.map(a => ({ attributeName: a.attributeName, value: '' }))
//           })}
//           disabled={isSubmitting}
//         >
//           Add Variation
//         </Button>
//       </Grid>
//     </Grid>
//   )
// }

// export default VariationDetails


// sagar changes ////////////
import React, { useEffect, useState, useMemo } from 'react'
import {
  Grid,
  TextField,
  Button,
  Typography,
  Box,
  Paper,
  Switch,
  FormControlLabel,
  Divider,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  IconButton
} from '@mui/material'
import { Controller, useFieldArray, Control, useWatch } from 'react-hook-form'
import Icon from 'src/@core/components/icon'
import { ProductFormValues, Category, Attribute } from './types'
import { validateUnit, validateAttributeValue, getFullImageUrl } from './hooks'
import toast from 'react-hot-toast'
import axios from 'src/configs/axios'

interface VariationDetailsProps {
  control: Control<ProductFormValues>
  errors: any
  productType: string
  trackStock: boolean
  categoryAttributes: Attribute[]
  selectedCategory: Category | undefined
  isSubmitting: boolean
  isEditMode: boolean
  onRecalcVariation: (index: number, mrpValue: string) => void
  onImageChange: (index: number, file: File | null) => void
  setVariationMRP?: any
}

const VariationDetails = ({
  setVariationMRP,
  control,
  errors,
  productType,
  trackStock,
  categoryAttributes,
  selectedCategory,
  isSubmitting,
  isEditMode,
  onRecalcVariation,
  onImageChange
}: VariationDetailsProps) => {
  const { fields, append: appendVariation, remove: removeVariation, replace: replaceVariations } = useFieldArray({
    control,
    name: 'variations'
  })

  const [viewImageLoading, setViewImageLoading] = useState<{ [key: string]: boolean }>({})
  const [imageDialogOpen, setImageDialogOpen] = useState(false)
  const [selectedImage, setSelectedImage] = useState<string>('')
  const [imageLoadError, setImageLoadError] = useState(false)
  const [currentViewingIndex, setCurrentViewingIndex] = useState<string>('')

  // Watch variations to get image previews
  const watchedVariations = useWatch({
    control,
    name: 'variations'
  }) || []

  // Create a stable mapping of field id to variation data
  const variationsMap = useMemo(() => {
    const map = new Map()
    fields.forEach((field, index) => {
      map.set(field.id, watchedVariations[index] || {})
    })
    return map
  }, [fields, watchedVariations])

  // Get variation data by field id
  const getVariationByFieldId = (fieldId: string) => {
    return variationsMap.get(fieldId) || {}
  }

  // Check if product type is ServiceBased
  const isServiceBased = productType === 'ServiceBased'

  // Ensure only one variation for ServiceBased products
  useEffect(() => {
    if (isServiceBased && fields.length > 1) {
      // Keep only the first variation
      const firstVariation = fields[0]
      replaceVariations([firstVariation])
      toast.error('Only one service entry is allowed for Service-Based products', {
        style: { zIndex: 999999 }
      })
    }
  }, [isServiceBased, fields.length, replaceVariations])

  useEffect(() => {
    if (watchedVariations && watchedVariations.length > 0) {
      setVariationMRP(watchedVariations?.[0]?.mrp)
    }
  }, [watchedVariations, setVariationMRP])

  const handleViewImage = async (imagePath: string, fieldId: string) => {
    if (!imagePath) {
      toast.error('No image to view', {
        style: { zIndex: 999999 }
      })
      return
    }

    setCurrentViewingIndex(fieldId)
    setImageLoadError(false)
    setViewImageLoading(prev => ({ ...prev, [fieldId]: true }))

    try {
      // If it's already a blob URL or data URL, use it directly
      if (imagePath.startsWith('blob:') || imagePath.startsWith('data:')) {
        setSelectedImage(imagePath)
        setImageDialogOpen(true)
        setViewImageLoading(prev => ({ ...prev, [fieldId]: false }))
        return
      }

      // Get full URL
      const fullUrl = getFullImageUrl(imagePath)
      
      // Try to fetch the image to check if it's accessible
      try {
        const response = await axios.get(fullUrl, {
          responseType: 'blob',
          timeout: 10000
        })
        
        // Create blob URL from response
        const blob = response.data
        const blobUrl = URL.createObjectURL(blob)
        setSelectedImage(blobUrl)
        setImageDialogOpen(true)
      } catch (fetchError) {
        console.error('Error fetching image:', fetchError)

        // If fetch fails, try to use the URL directly
        setSelectedImage(fullUrl)
        setImageDialogOpen(true)
      }
    } catch (error) {
      console.error('Error viewing image:', error)
      toast.error('Failed to load image. Please try again.', {
        style: { zIndex: 999999 }
      })
    } finally {
      setViewImageLoading(prev => ({ ...prev, [fieldId]: false }))
      setCurrentViewingIndex('')
    }
  }

  const handleImageUpload = (index: number, file: File | null) => {
    // Check file size (5MB = 5 * 1024 * 1024 bytes)
    if (file && file.size > 5 * 1024 * 1024) {
      toast.error('Image size should be less than 5MB', {
        style: { zIndex: 999999 }
      })
      return
    }
    onImageChange(index, file)
  }

  const handleImageError = () => {
    setImageLoadError(true)
    toast.error('Failed to load image. The image might be corrupted or inaccessible.', {
      style: { zIndex: 999999 }
    })
  }

  const handleCloseDialog = () => {
    setImageDialogOpen(false)
    setSelectedImage('')
    setImageLoadError(false)
    setCurrentViewingIndex('')
  }

  // Get the section title based on product type
  const getSectionTitle = () => {
    return isServiceBased ? 'Service Details' : 'Add Product Variations'
  }

  // Get the card title based on product type and index
  const getCardTitle = (index: number) => {
    if (isServiceBased) {
      return 'Service Information'
    }
    return `Variation ${index + 1}`
  }

  // Handle append variation - always add at the end
  const handleAppendVariation = () => {
    appendVariation({
      size: '',
      mrp: '',
      stockQty: 0,
      noOfItems: '',
      unit: '',
      calculatedAmount: 0,
      finalAmount: 0,
      image: null,
      imagePreview: '',
      attributeValues: categoryAttributes.map(a => ({ attributeName: a.attributeName, value: '' }))
    })
  }

  // Render service-based or product variation content
  const renderContent = () => {
    // For ServiceBased, always show the first variation
    const fieldsToRender = isServiceBased 
      ? fields.slice(0, 1) 
      : fields

    return fieldsToRender.map((field, index) => {
      // Get variation data using the field id
      const variation = getVariationByFieldId(field.id)
      const imagePreview = variation.imagePreview || ''
      const fieldId = field.id
      const isLoading = viewImageLoading[fieldId] || false

      return (
        <Paper key={field.id} sx={{ p: 3, mb: 3, position: 'relative', overflow: 'visible' }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
            <Typography variant='subtitle2' fontWeight={600}>
              {getCardTitle(index)}
            </Typography>
            {/* Only show Remove button for non-ServiceBased products with more than 1 variation */}
            {!isServiceBased && fields.length > 1 && (
              <Button
                size='small'
                color='error'
                variant='outlined'
                startIcon={<Icon icon='tabler:trash' />}
                onClick={() => removeVariation(index)}
                disabled={isSubmitting}
              >
                Remove Variation
              </Button>
            )}
          </Box>

          <Box sx={{ mb: 3 }}>
            <Typography variant='body2' fontWeight={500} sx={{ mb: 1 }}>
              Upload Image (Max 5MB)
            </Typography>
            <Box
              sx={{
                border: '2px dashed',
                borderColor: imagePreview ? 'primary.main' : 'divider',
                borderRadius: 2,
                p: imagePreview ? 2 : 4,
                textAlign: 'center',
                cursor: 'pointer',
                '&:hover': { borderColor: 'primary.main' },
                position: 'relative',
                backgroundColor: imagePreview ? 'action.hover' : 'transparent'
              }}
            >
              <input
                type='file'
                accept='image/*'
                onChange={(e) => {
                  const file = e.target.files?.[0] || null
                  handleImageUpload(index, file)
                }}
                style={{ display: 'none' }}
                id={`image-upload-${field.id}`}
              />
              <label htmlFor={`image-upload-${field.id}`} style={{ cursor: 'pointer', display: 'block' }}>
                {imagePreview ? (
                  <Box sx={{ position: 'relative' }}>
                    <Box
                      component='img'
                      src={imagePreview}
                      alt={`Variation ${index + 1}`}
                      sx={{ 
                        maxHeight: 120, 
                        borderRadius: 1,
                        display: 'block',
                        margin: '0 auto',
                        objectFit: 'contain'
                      }}
                      onError={(e) => {
                        console.error('Image load error:', imagePreview)
                        e.currentTarget.style.display = 'none'
                      }}
                    />
                    <Box sx={{ mt: 1, display: 'flex', gap: 1, justifyContent: 'center' }}>
                      {/* Only show View button in edit mode */}
                      {isEditMode && (
                        <Button
                          size='small'
                          variant='outlined'
                          disabled={isLoading}
                          onClick={(e) => {
                            e.preventDefault()
                            handleViewImage(imagePreview, field.id)
                          }}
                          startIcon={isLoading ? <CircularProgress size={16} /> : undefined}
                        >
                          {isLoading ? 'Loading...' : 'View'}
                        </Button>
                      )}
                      <Button
                        size='small'
                        variant='outlined'
                        color='error'
                        onClick={(e) => {
                          e.preventDefault()
                          onImageChange(index, null)
                        }}
                        disabled={isSubmitting}
                      >
                        Remove
                      </Button>
                    </Box>
                  </Box>
                ) : (
                  <>
                    <Icon icon='tabler:cloud-upload' style={{ fontSize: 40, color: '#9E9E9E' }} />
                    <Typography variant='body2' color='text.secondary'>
                      Click to upload image
                    </Typography>
                    <Typography variant='caption' color='text.secondary'>
                      (JPG, PNG, GIF - Max 5MB)
                    </Typography>
                  </>
                )}
              </label>
            </Box>
          </Box>

          <Grid container spacing={3}>
            <Grid item xs={12} md={4}>
              <Controller
                name={`variations.${index}.mrp`}
                control={control}
                rules={{ required: isServiceBased ? 'Price is required' : 'MRP is required' }}
                render={({ field }) => (
                  <TextField
                    {...field}
                    fullWidth
                    label={isServiceBased ? 'Price *' : 'MRP *'}
                    placeholder={isServiceBased ? 'Enter Price' : 'Enter MRP'}
                    size='small'
                    error={!!errors.variations?.[index]?.mrp}
                    helperText={errors.variations?.[index]?.mrp?.message}
                    disabled={isSubmitting}
                    onChange={(e) => {
                      const val = e.target.value
                      field.onChange(val)
                      onRecalcVariation(index, val)
                    }}
                  />
                )}
              />
            </Grid>

            {!isServiceBased && trackStock && (
              <Grid item xs={12} md={4}>
                <Controller
                  name={`variations.${index}.stockQty`}
                  control={control}
                  rules={{ 
                    required: 'Stock QTY is required',
                    validate: (value) => {
                      if (value && isNaN(Number(value))) {
                        return 'Stock QTY must be a valid number'
                      }
                      if (value && Number(value) < 0) {
                        return 'Stock QTY must be greater than 0'
                      }
                      return true
                    }
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      label='Stock QTY *'
                      placeholder='Enter Stock QTY'
                      size='small'
                      error={!!errors.variations?.[index]?.stockQty}
                      helperText={errors.variations?.[index]?.stockQty?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>
            )}

            <Grid item xs={12} md={4}>
              <Controller
                name={`variations.${index}.noOfItems`}
                control={control}
                rules={{ 
                  required: isServiceBased ? 'Quantity is required' : 'Number of items is required',
                  validate: (value) => {
                    if (!value) return isServiceBased ? 'Quantity is required' : 'Number of items is required'
                    if (isNaN(Number(value))) return 'Must be a valid number'
                    if (Number(value) < 1) return 'Must be at least 1'
                    return true
                  }
                }}
                render={({ field }) => (
                  <TextField
                    {...field}
                    fullWidth
                    label={isServiceBased ? 'Quantity *' : 'No. of Items *'}
                    placeholder={isServiceBased ? 'Enter Quantity' : 'Enter No. of Items'}
                    size='small'
                    error={!!errors.variations?.[index]?.noOfItems}
                    helperText={errors.variations?.[index]?.noOfItems?.message}
                    disabled={isSubmitting}
                  />
                )}
              />
            </Grid>

            <Grid item xs={12} md={4}>
              <Controller
                name={`variations.${index}.unit`}
                control={control}
                rules={{ 
                  required: 'Unit is required',
                  validate: (value) => validateUnit(value) || 'Unit should only contain alphabetic characters (A-Z, a-z)'
                }}
                render={({ field }) => (
                  <TextField
                    {...field}
                    fullWidth
                    label='Unit *'
                    placeholder='Enter Unit (e.g. pcs, kg, g)'
                    size='small'
                    error={!!errors.variations?.[index]?.unit}
                    helperText={errors.variations?.[index]?.unit?.message || 'Only alphabetic characters allowed'}
                    disabled={isSubmitting}
                  />
                )}
              />
            </Grid>

            <Grid item xs={12} md={4}>
              <Controller
                name={`variations.${index}.calculatedAmount`}
                control={control}
                render={({ field }) => (
                  <TextField
                    fullWidth
                    label='Calculated Amount'
                    value={field.value ?? 0}
                    size='small'
                    disabled
                  />
                )}
              />
            </Grid>

            <Grid item xs={12} md={4}>
              <Controller
                name={`variations.${index}.finalAmount`}
                control={control}
                render={({ field }) => (
                  <TextField
                    fullWidth
                    label='Final Amount'
                    value={field.value ?? 0}
                    size='small'
                    disabled
                  />
                )}
              />
            </Grid>
          </Grid>

          {categoryAttributes.length > 0 && (
            <Box sx={{ mt: 3 }}>
              <Divider sx={{ mb: 2 }} />
              <Typography variant='body2' fontWeight={600} sx={{ mb: 2 }}>
                {selectedCategory?.name} {isServiceBased ? 'Details' : 'Variations'}
              </Typography>
              <Grid container spacing={3}>
                {categoryAttributes.map((attr, attrIndex) => (
                  <Grid item xs={12} md={4} key={`${attr.attributeName}-${attrIndex}`}>
                    <Controller
                      name={`variations.${index}.attributeValues.${attrIndex}.value`}
                      control={control}
                      rules={{
                        ...(attr.isRequired ? { required: `${attr.attributeName} is required` } : {}),
                        validate: (value) => {
                          if (value && !validateAttributeValue(value, attr.isRequired)) {
                            return 'Value should only contain alphanumeric characters and spaces'
                          }
                          return true
                        }
                      }}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          fullWidth
                          size='small'
                          label={`${attr.attributeName}${attr.isRequired ? ' *' : ''}`}
                          placeholder={`Enter ${attr.attributeName}`}
                          disabled={isSubmitting}
                          error={!!errors.variations?.[index]?.attributeValues?.[attrIndex]?.value}
                          helperText={errors.variations?.[index]?.attributeValues?.[attrIndex]?.value?.message || 'Alphanumeric and spaces only'}
                          onChange={(e) => {
                            field.onChange(e.target.value)
                          }}
                        />
                      )}
                    />
                  </Grid>
                ))}
              </Grid>
            </Box>
          )}
        </Paper>
      )
    })
  }

  return (
    <>
      <Grid container spacing={4}>
        <Grid item xs={12}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
            <Typography variant='subtitle1' fontWeight={600}>
              {getSectionTitle()}
            </Typography>
          </Box>

          {/* Track Stock - Only for non-ServiceBased products */}
          {!isServiceBased && (
            <Box sx={{ mb: 3 }}>
              <Controller
                name='trackStock'
                control={control}
                render={({ field }) => (
                  <FormControlLabel
                    control={
                      <Switch
                        {...field}
                        checked={field.value}
                        onChange={(e) => field.onChange(e.target.checked)}
                        color='primary'
                      />
                    }
                    label='Track Stock'
                  />
                )}
              />
            </Box>
          )}

          {renderContent()}

          {/* Add Variation Button - Only for non-ServiceBased products */}
          {!isServiceBased && (
            <Button
              variant='outlined'
              startIcon={<Icon icon='tabler:plus' />}
              onClick={handleAppendVariation}
              disabled={isSubmitting}
            >
              Add Variation
            </Button>
          )}
        </Grid>
      </Grid>

      {/* Image View Dialog */}
      <Dialog
        open={imageDialogOpen}
        onClose={handleCloseDialog}
        maxWidth='md'
        fullWidth
        PaperProps={{
          sx: {
            zIndex: 999999
          }
        }}
      >
        <DialogTitle sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Typography variant='h6'>Product Image</Typography>
          <IconButton onClick={handleCloseDialog}>
            <Icon icon='tabler:x' />
          </IconButton>
        </DialogTitle>
        <DialogContent sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 400, position: 'relative' }}>
          {viewImageLoading[currentViewingIndex] ? (
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
              <CircularProgress />
              <Typography variant='body2' color='text.secondary'>Loading image...</Typography>
            </Box>
          ) : imageLoadError ? (
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
              <Icon icon='tabler:photo-off' style={{ fontSize: 64, color: '#9E9E9E' }} />
              <Typography variant='body1' color='text.secondary'>Failed to load image</Typography>
              <Typography variant='body2' color='text.secondary'>The image might be corrupted or inaccessible</Typography>
              <Button 
                variant='outlined' 
                onClick={() => {
                  setImageLoadError(false)
                  if (selectedImage) {
                    // Retry loading
                    const img = new Image()
                    img.onload = () => setImageLoadError(false)
                    img.onerror = () => setImageLoadError(true)
                    img.src = selectedImage
                  }
                }}
              >
                Retry
              </Button>
            </Box>
          ) : selectedImage ? (
            <Box
              component='img'
              src={selectedImage}
              alt='Product'
              sx={{
                maxWidth: '100%',
                maxHeight: '70vh',
                objectFit: 'contain'
              }}
              onError={handleImageError}
              onLoad={() => {
                setImageLoadError(false)
                setViewImageLoading(prev => ({ ...prev, [currentViewingIndex]: false }))
              }}
            />
          ) : (
            <Typography variant='body2' color='text.secondary'>No image to display</Typography>
          )}
        </DialogContent>
      </Dialog>
    </>
  )
}

export default VariationDetails