// // import React, { Fragment } from 'react'

// // // ** MUI Imports
// // import { Button, Grid } from '@mui/material'

// // // ** Custom Components
// // import ProductInformation from '../../../views/components/product/ProductInformation'

// // // ** React Hook Form Imports
// // import { useForm } from 'react-hook-form'

// // import VariantForm from 'src/views/components/product/VariationListForm'

// // //**  ✅ Types
// // export interface LabelValue {
// //   label: string
// //   value: string
// // }

// // export type VariantNameType<T extends string> = T extends 'Color' | 'Size' | 'Style' ? LabelValue[] : string[]

// // export interface Variant {
// //   key: string
// //   name: string
// //   sku: string
// //   buyingPrice: number
// //   sellingPrice: number
// //   discountPrice: number
// //   quantity: number
// //   alertQuantity: number
// //   weight: string
// //   gtin: string
// //   variantNames: {
// //     [key: string]: string
// //   }
// // }

// // export interface ProductFormData {
// //   productName: string
// //   slug: string
// //   sku: string
// //   sellingType: string
// //   category: string
// //   subCategory: string
// //   brand: string
// //   unit: string
// //   barcodeSymbology: string
// //   itemCode: string
// //   description: string
// //   variants: Variant[]
// // }

// // const CreateProduct = () => {
// //   const {
// //     control,
// //     handleSubmit,
// //     setValue,
// //     watch,
// //     formState: { errors }
// //   } = useForm<ProductFormData>({
// //     defaultValues: {
// //       productName: '',
// //       slug: '',
// //       sku: '',
// //       sellingType: '',
// //       category: '',
// //       subCategory: '',
// //       brand: '',
// //       unit: '',
// //       barcodeSymbology: '',
// //       itemCode: '',
// //       description: '',
// //       variants: []
// //     }
// //   })

// //   const onSubmit = (data: ProductFormData) => {
// //     console.log('✅ Final Product Data:', data)
// //   }
// //   return (
// //     <Fragment>
// //       <form onSubmit={handleSubmit(onSubmit)}>
// //         <Grid container spacing={3}>
// //           <Grid item xs={12}>
// //             <ProductInformation control={control} setValue={setValue} errors={errors} watch={watch} />
// //           </Grid>

// //           <Grid item xs={12}>
// //             <VariantForm control={control} watch={watch} />
// //           </Grid>
// //           <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
// //             <Button type='submit' variant='contained' sx={{ mr: 1 }}>
// //               Create
// //             </Button>

// //             <Button variant='outlined' color='secondary'>
// //               Cancel
// //             </Button>
// //           </Grid>
// //         </Grid>
// //       </form>
// //       {/* <MultiVariation openVariationModal={openVariationModal} handleToggle={handleToggle} setValue={setValue} /> */}
// //     </Fragment>
// //   )
// // }

// // CreateProduct.acl = {
// //   action: 'read',
// //   subject: 'user-management'
// // }

// // export default CreateProduct



// // new page /////////////////////////
// import React, { useState, useEffect, Fragment } from 'react'
// import { useRouter } from 'next/router'

// // ** MUI
// import {
//   Box,
//   Button,
//   Card,
//   Typography,
//   Stepper,
//   Step,
//   StepLabel,
//   Grid,
//   TextField,
//   FormControl,
//   InputLabel,
//   Select,
//   MenuItem,
//   Chip,
//   IconButton,
//   Divider,
//   FormHelperText,
//   CircularProgress,
//   Alert,
//   Paper,
//   FormControlLabel,
//   Switch,
//   InputAdornment,
//   Drawer,
//   Autocomplete,
//   RadioGroup,
//   Radio,
//   FormLabel,
//   Skeleton,
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   Dialog,
//   DialogTitle,
//   DialogContent,
//   DialogActions
// } from '@mui/material'

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

// // ** React Hook Form
// import { useForm, Controller, useFieldArray } from 'react-hook-form'

// // ** TanStack Query
// import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'

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

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

// // ** Countries data
// import { countries } from 'src/@fake-db/autocomplete'

// // ============================================================
// //  Types
// // ============================================================

// interface StaffMember {
//   firstName: string
//   lastName: string
//   email: string
//   phoneNumber: string
//   countryCode: string
//   dialCodeCountry: string
// }

// interface VariationAttributeValue {
//   attributeName: string
//   value: string
// }

// interface Variation {
//   id?: string
//   uid?: string
//   size: string
//   mrp: string
//   stockQty?: number
//   noOfItems: string
//   unit: string
//   calculatedAmount: number
//   finalAmount: number
//   image?: File | null
//   imagePreview?: string
//   attributeValues?: VariationAttributeValue[]
// }

// interface SpecificationItem {
//   id: string
//   name: string
//   value: string
// }

// interface ProductFormValues {
//   productName: string
//   productType: 'ServiceBased' | 'ReadyToSell' | 'Subscription' | 'RawMaterials'
//   categoryUid: string
//   vendorUid: string
//   taxCharges: 'Inclusive' | 'Exclusive'
//   taxes: string
//   description: string
//   staffMembers?: StaffMember[]
//   variations?: Variation[]
//   trackStock?: boolean
// }

// interface Category {
//   uid: string
//   name: string
//   description?: string
//   parentUid?: { uid: string; name?: string } | null
//   attributeKeys: Array<{ attributeName: string; isRequired: boolean }>
// }

// interface Vendor {
//   uid: string
//   vendorName: string
// }

// interface Tax {
//   uid: string
//   taxName: string
//   taxType: string
//   taxValue: number
// }

// interface Attribute {
//   attributeName: string
//   isRequired: boolean
// }

// interface CategoryPayload {
//   name: string
//   description?: string
//   parentUid?: { uid: string } | null
//   attributeKeys: Attribute[]
// }

// // ============================================================
// //  Error helper
// // ============================================================

// const getErrorMessage = (err: unknown, fallback: string): string => {
//   const e = err as {
//     response?: {
//       data?: {
//         detail?: string
//         properties?: { description?: string }
//         content?: string
//         message?: string
//         title?: string
//       }
//     }
//     message?: string
//   }
//   const d = e?.response?.data
//   return (
//     d?.detail ||
//     d?.properties?.description ||
//     d?.content ||
//     d?.message ||
//     d?.title ||
//     (err as Error)?.message ||
//     fallback
//   )
// }

// // ============================================================
// //  Helper: get selected tax details
// // ============================================================

// const getSelectedTaxDetails = (selectedTaxUid: string | undefined, allTaxes: Tax[]): Tax | null => {
//   if (!selectedTaxUid) return null
//   return allTaxes.find(t => t.uid === selectedTaxUid) || null
// }

// // ============================================================
// //  Helper: calculate tax amount
// // ============================================================

// const calculateTaxAmount = (mrp: string, tax: Tax | null): number => {
//   const mrpValue = parseFloat(mrp) || 0
//   if (!tax) return 0
  
//   if (tax.taxType === 'percentage') {
//     return (mrpValue * tax.taxValue) / 100
//   } else {
//     return tax.taxValue
//   }
// }

// // ============================================================
// //  Helpers: validations
// // ============================================================

// const validateUnit = (value: string): boolean => {
//   return /^[a-zA-Z]+$/.test(value)
// }

// const validateAttributeValue = (value: string, isRequired: boolean): boolean => {
//   if (!value && !isRequired) return true
//   if (!value && isRequired) return false
//   return /^[a-zA-Z0-9\s]+$/.test(value)
// }

// const validateDescription = (value: string): boolean => {
//   if (!value) return true
//   return /^[a-zA-Z0-9\s.,-]*$/.test(value)
// }

// // ============================================================
// //  API functions
// // ============================================================

// const fetchCategories = async () => {
//   const { data } = await axios.get(endpoints.pos.categoryapi?.categories)
//   return data
// }

// const fetchVendors = async () => {
//   const { data } = await axios.get(endpoints.pos.vendorapi?.vendors)
//   return data
// }

// const fetchTaxes = async () => {
//   const { data } = await axios.get(endpoints.pos.taxesapi?.taxes)
//   return data
// }

// const fetchProductByUid = async (uid: string) => {
//   const { data } = await axios.get(`${endpoints.pos.product}${uid}`)
//   return data
// }

// const createProduct = async (payload: any) => {
//   const formData = new FormData()
  
//   formData.append('name', payload.productName)
//   if (payload.description) formData.append('description', payload.description)
//   formData.append('productType', payload.productType)
//   formData.append('taxChargesType', payload.taxCharges || 'Exclusive')
//   formData.append('isInventoryManaged', String(payload.trackStock || false))
  
//   if (payload.vendorUid) {
//     formData.append('vendorUid.uid', payload.vendorUid)
//   }
  
//   if (payload.taxes) {
//     formData.append('taxUid.uid', payload.taxes)
//   }
  
//   if (payload.categoryUid) {
//     formData.append('categoryUid.uid', payload.categoryUid)
//   }
  
//   if (payload.staffMembers && payload.staffMembers.length > 0) {
//     payload.staffMembers.forEach((staff: any, index: number) => {
//       formData.append(`staffs[${index}].firstName`, staff.firstName || '')
//       formData.append(`staffs[${index}].lastName`, staff.lastName || '')
//       formData.append(`staffs[${index}].emailId`, staff.email || '')
//       formData.append(`staffs[${index}].phoneNumber`, staff.phoneNumber || '')
//       formData.append(`staffs[${index}].countryCode`, staff.dialCodeCountry || 'US')
//       formData.append(`staffs[${index}].dialCountryCode`, staff.countryCode || '+1')
//     })
//   }
  
//   if (payload.variations && payload.variations.length > 0) {
//     payload.variations.forEach((variation: any, index: number) => {
//       formData.append(`variations[${index}].mrp`, String(variation.mrp || 0))
//       if (variation.stockQty !== undefined) {
//         formData.append(`variations[${index}].stockQty`, String(variation.stockQty || 0))
//       }
//       formData.append(`variations[${index}].quantity`, String(variation.noOfItems || 1))
//       formData.append(`variations[${index}].unit`, variation.unit || 'pcs')
//       formData.append(`variations[${index}].calAmount`, String(variation.calculatedAmount || 0))
//       formData.append(`variations[${index}].finalAmount`, String(variation.finalAmount || 0))
      
//       if (variation.attributeValues && variation.attributeValues.length > 0) {
//         variation.attributeValues.forEach((attr: any, attrIndex: number) => {
//           if (attr.value && attr.value.trim()) {
//             formData.append(`variations[${index}].attributes[${attrIndex}].attributeName`, attr.attributeName)
//             formData.append(`variations[${index}].attributes[${attrIndex}].value`, attr.value)
//           }
//         })
//       }
//     })
//   }
  
//   if (payload.specifications && payload.specifications.length > 0) {
//     payload.specifications.forEach((spec: any, index: number) => {
//       formData.append(`specifications[${index}].specKey`, spec.name)
//       formData.append(`specifications[${index}].specValue`, spec.value)
//     })
//   }
  
//   const { data } = await axios.post(endpoints.pos.product, formData, {
//     headers: { 'Content-Type': 'multipart/form-data' }
//   })
//   return data
// }

// const updateProduct = async (uid: string, payload: any) => {
//   // For update, send as JSON with correct structure
//   const updatePayload = {
//     name: payload.productName,
//     description: payload.description || '',
//     productType: payload.productType,
//     taxChargesType: payload.taxCharges || 'Exclusive',
//     isInventoryManaged: payload.trackStock || false,
//     categoryUid: { uid: payload.categoryUid },
//     vendorUid: { uid: payload.vendorUid },
//     taxUid: payload.taxes ? { uid: payload.taxes } : undefined,
//     staffs: payload.staffMembers?.map((staff: any) => ({
//       firstName: staff.firstName,
//       lastName: staff.lastName,
//       emailId: staff.email,
//       phoneNumber: staff.phoneNumber,
//       countryCode: staff.dialCodeCountry || 'US',
//       dialCountryCode: staff.countryCode || '+1'
//     })) || []
//   }

//   const { data } = await axios.put(`${endpoints.pos.product}${uid}`, updatePayload)
//   return data
// }

// const updateProductVariations = async (uid: string, payload: any) => {
//   const formData = new FormData()
//   formData.append('isInventoryManaged', String(payload.trackStock || false))
  
//   if (payload.variations && payload.variations.length > 0) {
//     payload.variations.forEach((variation: any, index: number) => {
//       if (variation.uid) {
//         formData.append(`variations[${index}].uid`, variation.uid)
//       }
//       formData.append(`variations[${index}].mrp`, String(variation.mrp || 0))
//       if (variation.stockQty !== undefined) {
//         formData.append(`variations[${index}].stockQty`, String(variation.stockQty || 0))
//       }
//       formData.append(`variations[${index}].quantity`, String(variation.noOfItems || 1))
//       formData.append(`variations[${index}].unit`, variation.unit || 'pcs')
//       formData.append(`variations[${index}].calAmount`, String(variation.calculatedAmount || 0))
//       formData.append(`variations[${index}].finalAmount`, String(variation.finalAmount || 0))
      
//       if (variation.attributeValues && variation.attributeValues.length > 0) {
//         variation.attributeValues.forEach((attr: any, attrIndex: number) => {
//           if (attr.value && attr.value.trim()) {
//             formData.append(`variations[${index}].attributes[${attrIndex}].attributeName`, attr.attributeName)
//             formData.append(`variations[${index}].attributes[${attrIndex}].value`, attr.value)
//           }
//         })
//       }
//     })
//   }
  
//   const { data } = await axios.put(`${endpoints.pos.productVariations}${uid}`, formData, {
//     headers: { 'Content-Type': 'multipart/form-data' }
//   })
//   return data
// }

// const updateProductSpecifications = async (uid: string, specifications: any[]) => {
//   const { data } = await axios.put(`${endpoints.pos.productSpecifications}${uid}`, specifications)
//   return data
// }

// const createCategory = async (payload: CategoryPayload) => {
//   const formData = new FormData()
//   formData.append('name', payload.name)
//   if (payload.description) formData.append('description', payload.description)
//   if (payload.parentUid?.uid) formData.append('parentUid.uid', payload.parentUid.uid)

//   payload.attributeKeys.forEach((attr, index) => {
//     formData.append(`attributeKeys[${index}].attributeName`, attr.attributeName)
//     formData.append(`attributeKeys[${index}].isRequired`, String(attr.isRequired))
//   })

//   const { data } = await axios.post(endpoints.pos.categoryapi?.category, formData, {
//     headers: { 'Content-Type': 'multipart/form-data' }
//   })
//   return data
// }

// const createVendor = async (payload: any) => {
//   const { data } = await axios.post(endpoints.pos.vendorapi?.vendors || '/vendor', payload)
//   return data
// }

// const createTax = async (payload: any) => {
//   const { data } = await axios.post(endpoints.pos.taxesapi?.taxes || '/productTax', payload)
//   return data
// }

// // ============================================================
// //  Add Category Drawer Component
// // ============================================================

// interface AddCategoryDrawerProps {
//   open: boolean
//   onClose: () => void
//   onSuccess: () => void
//   parentCategories: Category[]
// }

// const AddCategoryDrawer = ({ open, onClose, onSuccess, parentCategories = [] }: AddCategoryDrawerProps) => {
//   const [loading, setLoading] = useState(false)

//   const {
//     control,
//     handleSubmit,
//     reset,
//     formState: { errors },
//   } = useForm<CategoryPayload>({
//     defaultValues: {
//       name: '',
//       description: '',
//       parentUid: null,
//       attributeKeys: [],
//     }
//   })

//   const { fields, append, remove } = useFieldArray({
//     control,
//     name: 'attributeKeys'
//   })

//   const onSubmit = async (data: CategoryPayload) => {
//     setLoading(true)
//     try {
//       await createCategory(data)
//       toast.success('Category created successfully')
//       onSuccess()
//       onClose()
//       reset({
//         name: '',
//         description: '',
//         parentUid: null,
//         attributeKeys: [],
//       })
//     } catch (error) {
//       toast.error(getErrorMessage(error, 'Failed to create category'))
//     } finally {
//       setLoading(false)
//     }
//   }

//   const addVariation = () => {
//     append({ attributeName: '', isRequired: false })
//   }

//   return (
//     <Drawer anchor='right' open={open} onClose={onClose}>
//       <Box sx={{ width: 500, p: 4, maxHeight: '100vh', overflow: 'auto' }}>
//         <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
//           <Typography variant='h6'>Add New Category</Typography>
//           <IconButton onClick={onClose}>
//             <Icon icon='tabler:x' />
//           </IconButton>
//         </Box>
//         <Divider sx={{ mb: 3 }} />

//         <Box component='form' onSubmit={handleSubmit(onSubmit)} noValidate>
//           <FormControl fullWidth sx={{ mb: 3 }}>
//             <InputLabel id='parent-category-label'>Parent Category</InputLabel>
//             <Controller
//               name='parentUid'
//               control={control}
//               render={({ field }) => (
//                 <Select
//                   {...field}
//                   labelId='parent-category-label'
//                   label='Parent Category'
//                   disabled={loading}
//                   value={field.value?.uid || ''}
//                   onChange={(e) => {
//                     const selected = parentCategories.find(p => p.uid === e.target.value)
//                     field.onChange(selected ? { uid: selected.uid } : null)
//                   }}
//                 >
//                   <MenuItem value=''>None</MenuItem>
//                   {parentCategories.map((category) => (
//                     <MenuItem key={category.uid} value={category.uid}>
//                       {category.name}
//                     </MenuItem>
//                   ))}
//                 </Select>
//               )}
//             />
//           </FormControl>

//           <Controller
//             name='name'
//             control={control}
//             rules={{
//               required: 'Category name is required',
//               minLength: { value: 2, message: 'Minimum 2 characters' },
//             }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Category Name *'
//                 placeholder='e.g. Women Cloths'
//                 error={!!errors.name}
//                 helperText={errors.name?.message}
//                 disabled={loading}
//                 sx={{ mb: 3 }}
//               />
//             )}
//           />

//           <Controller
//             name='description'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 multiline
//                 rows={3}
//                 label='Description (optional)'
//                 placeholder='Enter description about the category...'
//                 error={!!errors.description}
//                 helperText={errors.description?.message}
//                 disabled={loading}
//                 sx={{ mb: 3 }}
//               />
//             )}
//           />

//           <Box sx={{ mt: 2, mb: 3 }}>
//             <Typography variant='subtitle1' fontWeight={600} sx={{ mb: 2 }}>
//               Variations
//             </Typography>

//             <TableContainer component={Paper} variant='outlined'>
//               <Table>
//                 <TableHead>
//                   <TableRow>
//                     <TableCell><Typography fontWeight={600}>Variation Name</Typography></TableCell>
//                     <TableCell align='center'><Typography fontWeight={600}>Required</Typography></TableCell>
//                     <TableCell align='center'><Typography fontWeight={600}>Action</Typography></TableCell>
//                   </TableRow>
//                 </TableHead>
//                 <TableBody>
//                   {fields.length === 0 ? (
//                     <TableRow>
//                       <TableCell colSpan={3} align='center' sx={{ py: 3 }}>
//                         <Typography variant='body2' color='text.secondary'>
//                           No variations added. Click "Add New" to add variations.
//                         </Typography>
//                       </TableCell>
//                     </TableRow>
//                   ) : (
//                     fields.map((field, index) => (
//                       <TableRow key={field.id}>
//                         <TableCell>
//                           <Controller
//                             name={`attributeKeys.${index}.attributeName`}
//                             control={control}
//                             rules={{
//                               required: 'Variation name is required',
//                               minLength: { value: 2, message: 'Minimum 2 characters' },
//                             }}
//                             render={({ field: fieldProps, fieldState: { error } }) => (
//                               <TextField
//                                 {...fieldProps}
//                                 fullWidth
//                                 size='small'
//                                 placeholder='e.g. Color, Size'
//                                 error={!!error}
//                                 helperText={error?.message}
//                                 disabled={loading}
//                               />
//                             )}
//                           />
//                         </TableCell>
//                         <TableCell align='center'>
//                           <Controller
//                             name={`attributeKeys.${index}.isRequired`}
//                             control={control}
//                             render={({ field: fieldProps }) => (
//                               <FormControlLabel
//                                 control={
//                                   <Switch
//                                     {...fieldProps}
//                                     checked={fieldProps.value}
//                                     onChange={(e) => fieldProps.onChange(e.target.checked)}
//                                     disabled={loading}
//                                     color='primary'
//                                   />
//                                 }
//                                 label={fieldProps.value ? 'Yes' : 'No'}
//                                 sx={{ m: 0 }}
//                               />
//                             )}
//                           />
//                         </TableCell>
//                         <TableCell align='center'>
//                           <IconButton
//                             size='small'
//                             color='error'
//                             onClick={() => remove(index)}
//                             disabled={loading || fields.length === 1}
//                           >
//                             <Icon icon='tabler:trash' fontSize={18} />
//                           </IconButton>
//                         </TableCell>
//                       </TableRow>
//                     ))
//                   )}
//                 </TableBody>
//               </Table>
//             </TableContainer>

//             <Button
//               variant='outlined'
//               startIcon={<Icon icon='tabler:plus' />}
//               onClick={addVariation}
//               disabled={loading}
//               sx={{ mt: 2 }}
//             >
//               Add New
//             </Button>
//           </Box>

//           <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 3 }}>
//             <Button variant='outlined' onClick={onClose} disabled={loading}>
//               Cancel
//             </Button>
//             <Button type='submit' variant='contained' disabled={loading}>
//               {loading ? <CircularProgress size={24} /> : 'Create Category'}
//             </Button>
//           </Box>
//         </Box>
//       </Box>
//     </Drawer>
//   )
// }

// // ============================================================
// //  Add Vendor Drawer Component
// // ============================================================

// interface AddVendorDrawerProps {
//   open: boolean
//   onClose: () => void
//   onSuccess: () => void
// }

// const AddVendorDrawer = ({ open, onClose, onSuccess }: AddVendorDrawerProps) => {
//   const [loading, setLoading] = useState(false)
//   const [formData, setFormData] = useState({
//     vendorName: '',
//     companyName: '',
//     address: '',
//     email: '',
//     phoneNumber: '',
//     countryCode: '+1',
//     dialCodeCountry: 'US',
//     vendorType: ''
//   })

//   const getSelectedCountry = () => {
//     return countries.find(c => c.code === formData.dialCodeCountry) || null
//   }

//   const handleSubmit = async () => {
//     if (!formData.vendorName.trim() || !formData.companyName.trim()) {
//       toast.error('Vendor name and company name are required')
//       return
//     }
//     setLoading(true)
//     try {
//       const payload = {
//         vendorName: formData.vendorName,
//         companyName: formData.companyName,
//         address: formData.address,
//         emailId: formData.email,
//         phoneNumber: formData.phoneNumber,
//         countryCode: formData.countryCode,
//         dialCodeCountry: formData.dialCodeCountry,
//         vendorType: formData.vendorType
//       }
//       await createVendor(payload)
//       toast.success('Vendor created successfully')
//       onSuccess()
//       onClose()
//       setFormData({
//         vendorName: '',
//         companyName: '',
//         address: '',
//         email: '',
//         phoneNumber: '',
//         countryCode: '+1',
//         dialCodeCountry: 'US',
//         vendorType: ''
//       })
//     } catch (error) {
//       toast.error(getErrorMessage(error, 'Failed to create vendor'))
//     } finally {
//       setLoading(false)
//     }
//   }

//   return (
//     <Drawer anchor='right' open={open} onClose={onClose}>
//       <Box sx={{ width: 400, p: 4 }}>
//         <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
//           <Typography variant='h6'>Add New Vendor</Typography>
//           <IconButton onClick={onClose}>
//             <Icon icon='tabler:x' />
//           </IconButton>
//         </Box>
//         <Divider sx={{ mb: 3 }} />

//         <TextField
//           fullWidth
//           label='Vendor Name *'
//           value={formData.vendorName}
//           onChange={(e) => setFormData({ ...formData, vendorName: e.target.value })}
//           sx={{ mb: 3 }}
//         />

//         <TextField
//           fullWidth
//           label='Company Name *'
//           value={formData.companyName}
//           onChange={(e) => setFormData({ ...formData, companyName: e.target.value })}
//           sx={{ mb: 3 }}
//         />

//         <TextField
//           fullWidth
//           label='Email'
//           value={formData.email}
//           onChange={(e) => setFormData({ ...formData, email: e.target.value })}
//           sx={{ mb: 3 }}
//         />

//         <Box sx={{ display: 'flex', gap: 2, mb: 3 }}>
//           <Autocomplete
//             sx={{ width: '40%' }}
//             options={countries}
//             autoHighlight
//             getOptionLabel={(opt) => `${opt.code} +${opt.phone}`}
//             value={getSelectedCountry()}
//             onChange={(_, newValue) => {
//               if (newValue) {
//                 setFormData({
//                   ...formData,
//                   dialCodeCountry: newValue.code,
//                   countryCode: `+${newValue.phone}`
//                 })
//               }
//             }}
//             renderOption={(props, option) => (
//               <Box component='li' sx={{ display: 'flex', alignItems: 'center', gap: 1 }} {...props}>
//                 <img
//                   loading='lazy'
//                   width='20'
//                   src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
//                   srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
//                   alt=''
//                 />
//                 <span>{option.label}</span>
//               </Box>
//             )}
//             renderInput={params => (
//               <TextField
//                 {...params}
//                 label='Country'
//                 inputProps={{ ...params.inputProps, autoComplete: 'new-password' }}
//               />
//             )}
//           />
//           <TextField
//             fullWidth
//             label='Phone Number'
//             value={formData.phoneNumber}
//             onChange={(e) => setFormData({ ...formData, phoneNumber: e.target.value })}
//           />
//         </Box>

//         <TextField
//           fullWidth
//           label='Address'
//           multiline
//           rows={2}
//           value={formData.address}
//           onChange={(e) => setFormData({ ...formData, address: e.target.value })}
//           sx={{ mb: 3 }}
//         />

//         <TextField
//           fullWidth
//           label='Vendor Type'
//           value={formData.vendorType}
//           onChange={(e) => setFormData({ ...formData, vendorType: e.target.value })}
//           sx={{ mb: 3 }}
//         />

//         <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
//           <Button variant='outlined' onClick={onClose} disabled={loading}>
//             Cancel
//           </Button>
//           <Button variant='contained' onClick={handleSubmit} disabled={loading}>
//             {loading ? <CircularProgress size={24} /> : 'Create Vendor'}
//           </Button>
//         </Box>
//       </Box>
//     </Drawer>
//   )
// }

// // ============================================================
// //  Add Tax Drawer Component
// // ============================================================

// interface AddTaxDrawerProps {
//   open: boolean
//   onClose: () => void
//   onSuccess: () => void
// }

// const AddTaxDrawer = ({ open, onClose, onSuccess }: AddTaxDrawerProps) => {
//   const [loading, setLoading] = useState(false)
//   const [taxType, setTaxType] = useState('flat')
//   const [formData, setFormData] = useState({
//     taxName: '',
//     taxValue: 0
//   })

//   const handleSubmit = async () => {
//     if (!formData.taxName.trim() || formData.taxValue <= 0) {
//       toast.error('Tax name and value are required')
//       return
//     }
//     setLoading(true)
//     try {
//       const payload = {
//         taxName: formData.taxName,
//         taxType: taxType,
//         taxValue: formData.taxValue
//       }
//       await createTax(payload)
//       toast.success('Tax created successfully')
//       onSuccess()
//       onClose()
//       setFormData({ taxName: '', taxValue: 0 })
//       setTaxType('flat')
//     } catch (error) {
//       toast.error(getErrorMessage(error, 'Failed to create tax'))
//     } finally {
//       setLoading(false)
//     }
//   }

//   return (
//     <Drawer anchor='right' open={open} onClose={onClose}>
//       <Box sx={{ width: 400, p: 4 }}>
//         <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
//           <Typography variant='h6'>Add New Tax</Typography>
//           <IconButton onClick={onClose}>
//             <Icon icon='tabler:x' />
//           </IconButton>
//         </Box>
//         <Divider sx={{ mb: 3 }} />

//         <TextField
//           fullWidth
//           label='Tax Name *'
//           value={formData.taxName}
//           onChange={(e) => setFormData({ ...formData, taxName: e.target.value })}
//           sx={{ mb: 3 }}
//         />

//         <FormControl component="fieldset" sx={{ mb: 3 }}>
//           <FormLabel component="legend">Tax Type</FormLabel>
//           <RadioGroup
//             row
//             value={taxType}
//             onChange={(e) => setTaxType(e.target.value)}
//           >
//             <FormControlLabel value="flat" control={<Radio />} label="Flat" />
//             <FormControlLabel value="percentage" control={<Radio />} label="Percentage" />
//           </RadioGroup>
//         </FormControl>

//         <TextField
//           fullWidth
//           label='Tax Value *'
//           type='number'
//           value={formData.taxValue}
//           onChange={(e) => setFormData({ ...formData, taxValue: parseFloat(e.target.value) || 0 })}
//           InputProps={{
//             endAdornment: taxType === 'percentage' ? '%' : undefined,
//           }}
//           sx={{ mb: 3 }}
//         />

//         <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
//           <Button variant='outlined' onClick={onClose} disabled={loading}>
//             Cancel
//           </Button>
//           <Button variant='contained' onClick={handleSubmit} disabled={loading}>
//             {loading ? <CircularProgress size={24} /> : 'Create Tax'}
//           </Button>
//         </Box>
//       </Box>
//     </Drawer>
//   )
// }

// // ============================================================
// //  Main Component
// // ============================================================

// const CreateProduct = () => {
//   const router = useRouter()
//   const { uid } = router.query

//   const [activeStep, setActiveStep] = useState(0)
//   const [showCategoryDrawer, setShowCategoryDrawer] = useState(false)
//   const [showVendorDrawer, setShowVendorDrawer] = useState(false)
//   const [showTaxDrawer, setShowTaxDrawer] = useState(false)

//   const [specifications, setSpecifications] = useState<SpecificationItem[]>([])
//   const [specName, setSpecName] = useState('')
//   const [specValue, setSpecValue] = useState('')
//   const [editingSpecId, setEditingSpecId] = useState<string | null>(null)

//   const queryClient = useQueryClient()

//   const { data: categoriesData, refetch: refetchCategories } = useQuery({
//     queryKey: ['categories'],
//     queryFn: fetchCategories,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: parentCategoriesData, refetch: refetchParentCategories } = useQuery({
//     queryKey: ['parentCategories'],
//     queryFn: fetchCategories,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: vendorsData, refetch: refetchVendors } = useQuery({
//     queryKey: ['vendors'],
//     queryFn: fetchVendors,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: taxesData, refetch: refetchTaxes } = useQuery({
//     queryKey: ['taxes'],
//     queryFn: fetchTaxes,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: productData, isLoading: isLoadingProduct } = useQuery({
//     queryKey: ['product', uid],
//     queryFn: () => fetchProductByUid(uid as string),
//     enabled: !!uid,
//     staleTime: 0,
//   })

//   const categories: Category[] = categoriesData?.content?.result || []
//   const vendors: Vendor[] = vendorsData?.content?.result || []
//   const taxes: Tax[] = taxesData?.content?.result || []
//   const parentCategories: Category[] = parentCategoriesData?.content?.result || []

//   const {
//     control,
//     handleSubmit,
//     watch,
//     setValue,
//     getValues,
//     reset,
//     trigger,
//     formState: { errors }
//   } = useForm<ProductFormValues>({
//     defaultValues: {
//       productName: '',
//       productType: 'ReadyToSell',
//       categoryUid: '',
//       vendorUid: '',
//       taxCharges: 'Exclusive',
//       taxes: '',
//       description: '',
//       staffMembers: [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }],
//       variations: [{
//         size: '',
//         mrp: '',
//         stockQty: 0,
//         noOfItems: '1',
//         unit: 'pcs',
//         calculatedAmount: 0,
//         finalAmount: 0,
//         image: null,
//         imagePreview: '',
//         attributeValues: []
//       }],
//       trackStock: false
//     }
//   })

//   const { fields: staffFields, append: appendStaff, remove: removeStaff } = useFieldArray({
//     control,
//     name: 'staffMembers'
//   })

//   const { fields: variationFields, append: appendVariation, remove: removeVariation } = useFieldArray({
//     control,
//     name: 'variations'
//   })

//   const productType = watch('productType')
//   const trackStock = watch('trackStock')
//   const categoryUid = watch('categoryUid')
//   const selectedTax = watch('taxes')

//   const selectedCategory: Category | undefined = categories.find(c => c.uid === categoryUid)
//   const categoryAttributes: Attribute[] = selectedCategory?.attributeKeys || []
//   const selectedTaxDetails = getSelectedTaxDetails(selectedTax, taxes)

//   const recalcAllVariations = () => {
//     const currentVariations = getValues('variations') || []
//     currentVariations.forEach((v, index) => {
//       const mrp = v.mrp || '0'
//       const calculated = calculateTaxAmount(mrp, selectedTaxDetails)
//       const mrpValue = parseFloat(mrp) || 0
//       const final = mrpValue + calculated
//       setValue(`variations.${index}.calculatedAmount`, calculated)
//       setValue(`variations.${index}.finalAmount`, final)
//     })
//   }

//   useEffect(() => {
//     recalcAllVariations()
//     // eslint-disable-next-line react-hooks/exhaustive-deps
//   }, [selectedTax, selectedTaxDetails])

//   useEffect(() => {
//     const currentVariations = getValues('variations') || []
//     currentVariations.forEach((_, index) => {
//       const newAttrValues = categoryAttributes.map(attr => ({
//         attributeName: attr.attributeName,
//         value: ''
//       }))
//       setValue(`variations.${index}.attributeValues`, newAttrValues)
//     })
//     // eslint-disable-next-line react-hooks/exhaustive-deps
//   }, [categoryUid])

//   // Populate form when editing
//   useEffect(() => {
//     if (uid && productData) {
//       const product = productData?.content?.result || productData?.content
//       if (product) {
//         console.log('Product data:', product)
        
//         // Map product data to form values
//         reset({
//           productName: product.name || '',
//           productType: product.productType || 'ReadyToSell',
//           categoryUid: product.categoryUid?.uid || product.category?.uid || '',
//           vendorUid: product.vendorUid?.uid || product.vendor?.uid || '',
//           taxCharges: product.taxChargesType || 'Exclusive',
//           taxes: product.taxUid?.uid || '',
//           description: product.description || '',
//           staffMembers: product.staffs && product.staffs.length > 0 
//             ? product.staffs.map((staff: any) => ({
//                 firstName: staff.firstName || '',
//                 lastName: staff.lastName || '',
//                 email: staff.emailId || '',
//                 phoneNumber: staff.phoneNumber || '',
//                 countryCode: staff.dialCountryCode || '+1',
//                 dialCodeCountry: staff.countryCode || 'US'
//               }))
//             : [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }],
//           variations: product.variations && product.variations.length > 0
//             ? product.variations.map((v: any) => ({
//                 uid: v.uid || '',
//                 size: '',
//                 mrp: String(v.mrp || 0),
//                 stockQty: v.stockQty || 0,
//                 noOfItems: String(v.quantity || 1),
//                 unit: v.unit || 'pcs',
//                 calculatedAmount: v.calAmount || 0,
//                 finalAmount: v.finalAmount || 0,
//                 image: null,
//                 imagePreview: '',
//                 attributeValues: v.attributes && v.attributes.length > 0
//                   ? v.attributes.map((attr: any) => ({
//                       attributeName: attr.attributeName || '',
//                       value: attr.value || ''
//                     }))
//                   : []
//               }))
//             : [{
//                 size: '',
//                 mrp: '',
//                 stockQty: 0,
//                 noOfItems: '1',
//                 unit: 'pcs',
//                 calculatedAmount: 0,
//                 finalAmount: 0,
//                 image: null,
//                 imagePreview: '',
//                 attributeValues: []
//               }],
//           trackStock: product.isInventoryManaged || false
//         })
        
//         // Set specifications
//         if (product.specifications && Array.isArray(product.specifications) && product.specifications.length > 0) {
//           setSpecifications(
//             product.specifications.map((s: any, i: number) => ({
//               id: s.id || `spec-${i}-${Date.now()}`,
//               name: s.specKey || s.name || '',
//               value: s.specValue || s.value || ''
//             }))
//           )
//         }
//       }
//     }
//   }, [uid, productData, reset])

//   const createMutation = useMutation({
//     mutationFn: createProduct,
//     onSuccess: (res) => {
//       toast.success(res?.content || 'Product created successfully')
//       router.push('/products')
//     },
//     onError: (err) => {
//       const errorMsg = getErrorMessage(err, 'Failed to create product')
//       toast.error(errorMsg)
//     }
//   })

//   const updateMutation = useMutation({
//     mutationFn: ({ uid, payload }: { uid: string; payload: any }) =>
//       updateProduct(uid, payload),
//     onSuccess: (res) => {
//       toast.success(res?.content || 'Product updated successfully')
//       router.push('/products')
//     },
//     onError: (err) => {
//       const errorMsg = getErrorMessage(err, 'Failed to update product')
//       toast.error(errorMsg)
//     }
//   })

//   const updateVariationsMutation = useMutation({
//     mutationFn: ({ uid, payload }: { uid: string; payload: any }) =>
//       updateProductVariations(uid, payload),
//     onSuccess: () => {
//       toast.success('Variations updated successfully')
//     },
//     onError: (err) => {
//       const errorMsg = getErrorMessage(err, 'Failed to update variations')
//       toast.error(errorMsg)
//     }
//   })

//   const updateSpecificationsMutation = useMutation({
//     mutationFn: ({ uid, specs }: { uid: string; specs: any[] }) =>
//       updateProductSpecifications(uid, specs),
//     onSuccess: () => {
//       toast.success('Specifications updated successfully')
//     },
//     onError: (err) => {
//       const errorMsg = getErrorMessage(err, 'Failed to update specifications')
//       toast.error(errorMsg)
//     }
//   })

//   const stepFieldsMap: Record<number, string[]> = {
//     0: ['productName', 'productType', 'categoryUid', 'vendorUid'],
//     1: ['variations'],
//     2: []
//   }

//   const handleNext = async () => {
//     const fieldsToValidate = stepFieldsMap[activeStep] as any
//     const isValid = await trigger(fieldsToValidate)
//     if (!isValid) {
//       toast.error('Please fill all required fields correctly')
//       return
//     }
//     setActiveStep((prev) => Math.min(prev + 1, 2))
//   }

//   const handleBack = () => {
//     setActiveStep((prev) => Math.max(prev - 1, 0))
//   }

//   const handleReset = () => {
//     reset({
//       productName: '',
//       productType: 'ReadyToSell',
//       categoryUid: '',
//       vendorUid: '',
//       taxCharges: 'Exclusive',
//       taxes: '',
//       description: '',
//       staffMembers: [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }],
//       variations: [{
//         size: '',
//         mrp: '',
//         stockQty: 0,
//         noOfItems: '1',
//         unit: 'pcs',
//         calculatedAmount: 0,
//         finalAmount: 0,
//         image: null,
//         imagePreview: '',
//         attributeValues: []
//       }],
//       trackStock: false
//     })
//     setSpecifications([])
//     setSpecName('')
//     setSpecValue('')
//     setEditingSpecId(null)
//     setActiveStep(0)
//   }

//   const onSubmit = async (data: ProductFormValues) => {
//     const variationsPayload = (data.variations || []).map(v => {
//       const { image, imagePreview, ...rest } = v
//       return { 
//         ...rest, 
//         image,
//         mrp: parseFloat(v.mrp) || 0,
//         noOfItems: parseInt(v.noOfItems) || 0
//       }
//     })

//     const payload = {
//       ...data,
//       variations: variationsPayload,
//       specifications: specifications.map(s => ({ name: s.name, value: s.value }))
//     }
    
//     if (uid) {
//       // Update product - basic details only
//       // Variations and specifications are updated separately
//       try {
//         await updateMutation.mutateAsync({ uid: uid as string, payload })
//         toast.success('Product updated successfully')
//         router.push('/products')
//       } catch (error) {
//         console.error('Update error:', error)
//       }
//     } else {
//       createMutation.mutate(payload)
//     }
//   }

//   const isSubmitting = createMutation.isPending || updateMutation.isPending || 
//                        updateVariationsMutation.isPending || updateSpecificationsMutation.isPending

//   const handleAddSpecification = () => {
//     if (!specName.trim() || !specValue.trim()) {
//       toast.error('Specification name and value are required')
//       return
//     }

//     if (editingSpecId) {
//       setSpecifications(prev =>
//         prev.map(s => (s.id === editingSpecId ? { ...s, name: specName.trim(), value: specValue.trim() } : s))
//       )
//       setEditingSpecId(null)
//     } else {
//       setSpecifications(prev => [
//         ...prev,
//         { id: `spec-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, name: specName.trim(), value: specValue.trim() }
//       ])
//     }
//     setSpecName('')
//     setSpecValue('')
//   }

//   const handleEditSpecification = (spec: SpecificationItem) => {
//     setEditingSpecId(spec.id)
//     setSpecName(spec.name)
//     setSpecValue(spec.value)
//   }

//   const handleRemoveSpecification = (id: string) => {
//     setSpecifications(prev => prev.filter(s => s.id !== id))
//     if (editingSpecId === id) {
//       setEditingSpecId(null)
//       setSpecName('')
//       setSpecValue('')
//     }
//   }

//   const recalcVariationAmount = (index: number, mrpValue: string) => {
//     const calculated = calculateTaxAmount(mrpValue, selectedTaxDetails)
//     const mrpNum = parseFloat(mrpValue) || 0
//     const final = mrpNum + calculated
//     setValue(`variations.${index}.calculatedAmount`, calculated)
//     setValue(`variations.${index}.finalAmount`, final)
//   }

//   const handleVariationImageChange = (index: number, file: File | null) => {
//     setValue(`variations.${index}.image`, file)
//     if (file) {
//       const reader = new FileReader()
//       reader.onload = () => {
//         setValue(`variations.${index}.imagePreview`, reader.result as string)
//       }
//       reader.readAsDataURL(file)
//     } else {
//       setValue(`variations.${index}.imagePreview`, '')
//     }
//   }

//   const steps = ['Product Details', 'Variation Details', 'Specification Details']

//   const renderStepContent = (step: number) => {
//     switch (step) {
//       case 0:
//         return renderProductDetails()
//       case 1:
//         return renderVariationDetails()
//       case 2:
//         return renderSpecificationDetails()
//       default:
//         return null
//     }
//   }

//   const renderProductDetails = () => (
//     <Grid container spacing={4}>
//       <Grid item xs={12}>
//         <Typography variant='subtitle1' fontWeight={600} sx={{ mb: 2 }}>
//           Add New Products details
//         </Typography>
//       </Grid>

//       <Grid item xs={12} md={6}>
//         <Controller
//           name='productName'
//           control={control}
//           rules={{ required: 'Product name is required' }}
//           render={({ field }) => (
//             <TextField
//               {...field}
//               fullWidth
//               label='Product Name *'
//               placeholder='Product Name'
//               error={!!errors.productName}
//               helperText={errors.productName?.message}
//               disabled={isSubmitting}
//             />
//           )}
//         />
//       </Grid>

//       <Grid item xs={12} md={6}>
//         <Controller
//           name='productType'
//           control={control}
//           rules={{ required: 'Product type is required' }}
//           render={({ field }) => (
//             <FormControl fullWidth error={!!errors.productType}>
//               <InputLabel>Product Type *</InputLabel>
//               <Select {...field} label='Product Type *' disabled={isSubmitting}>
//                 <MenuItem value='ServiceBased'>Service Based</MenuItem>
//                 <MenuItem value='ReadyToSell'>Ready To Sell</MenuItem>
//                 <MenuItem value='Subscription'>Subscription</MenuItem>
//                 <MenuItem value='RawMaterials'>Raw Materials</MenuItem>
//               </Select>
//               {errors.productType && <FormHelperText>{errors.productType.message}</FormHelperText>}
//             </FormControl>
//           )}
//         />
//       </Grid>

//       <Grid item xs={12} md={6}>
//         <Controller
//           name='categoryUid'
//           control={control}
//           rules={{ required: 'Category is required' }}
//           render={({ field }) => (
//             <FormControl fullWidth error={!!errors.categoryUid}>
//               <InputLabel>Category *</InputLabel>
//               <Select
//                 {...field}
//                 label='Category *'
//                 disabled={isSubmitting}
//                 value={field.value || ''}
//               >
//                 {categories.map((cat) => (
//                   <MenuItem key={cat.uid} value={cat.uid}>{cat.name}</MenuItem>
//                 ))}
//               </Select>
//               {errors.categoryUid && <FormHelperText>{errors.categoryUid.message}</FormHelperText>}
//             </FormControl>
//           )}
//         />
//         <Button
//           size='small'
//           startIcon={<Icon icon='tabler:plus' />}
//           onClick={() => setShowCategoryDrawer(true)}
//           sx={{ mt: 1 }}
//         >
//           Add New Category
//         </Button>
//       </Grid>

//       <Grid item xs={12} md={6}>
//         <Controller
//           name='vendorUid'
//           control={control}
//           rules={{ required: 'Vendor is required' }}
//           render={({ field }) => (
//             <FormControl fullWidth error={!!errors.vendorUid}>
//               <InputLabel>Vendor *</InputLabel>
//               <Select
//                 {...field}
//                 label='Vendor *'
//                 disabled={isSubmitting}
//                 value={field.value || ''}
//               >
//                 {vendors.map((vendor) => (
//                   <MenuItem key={vendor.uid} value={vendor.uid}>{vendor.vendorName}</MenuItem>
//                 ))}
//               </Select>
//               {errors.vendorUid && <FormHelperText>{errors.vendorUid.message}</FormHelperText>}
//             </FormControl>
//           )}
//         />
//         <Button
//           size='small'
//           startIcon={<Icon icon='tabler:plus' />}
//           onClick={() => setShowVendorDrawer(true)}
//           sx={{ mt: 1 }}
//         >
//           Add New Vendor
//         </Button>
//       </Grid>

//       <Grid item xs={12} md={6}>
//         <Controller
//           name='taxCharges'
//           control={control}
//           render={({ field }) => (
//             <FormControl fullWidth>
//               <InputLabel>Tax Charges</InputLabel>
//               <Select {...field} label='Tax Charges' value='Exclusive' disabled>
//                 <MenuItem value='Exclusive'>Exclusive</MenuItem>
//                 <MenuItem value='Inclusive'>Inclusive</MenuItem>
//               </Select>
//               <FormHelperText>Tax charges are fixed to Exclusive</FormHelperText>
//             </FormControl>
//           )}
//         />
//       </Grid>

//       <Grid item xs={12} md={6}>
//         <Controller
//           name='taxes'
//           control={control}
//           render={({ field }) => (
//             <FormControl fullWidth>
//               <InputLabel>Tax</InputLabel>
//               <Select
//                 {...field}
//                 label='Tax'
//                 disabled={isSubmitting}
//                 value={field.value || ''}
//               >
//                 <MenuItem value=''>None</MenuItem>
//                 {taxes.map((tax) => {
//                   let displayValue = ''
//                   if (tax.taxType === 'percentage') {
//                     displayValue = `${tax.taxValue}%`
//                   } else {
//                     displayValue = `${tax.taxValue}$`
//                   }
//                   return (
//                     <MenuItem key={tax.uid} value={tax.uid}>
//                       {tax.taxName} - {displayValue}
//                     </MenuItem>
//                   )
//                 })}
//               </Select>
//             </FormControl>
//           )}
//         />
//         <Button
//           size='small'
//           startIcon={<Icon icon='tabler:plus' />}
//           onClick={() => setShowTaxDrawer(true)}
//           sx={{ mt: 1 }}
//         >
//           Add New Tax
//         </Button>
//       </Grid>

//       <Grid item xs={12}>
//         <Controller
//           name='description'
//           control={control}
//           rules={{
//             maxLength: { value: 500, message: 'Maximum 500 characters' },
//             validate: (value) => {
//               if (value && !validateDescription(value)) {
//                 return 'Description can only contain letters, numbers, spaces, and special characters .,-'
//               }
//               return true
//             }
//           }}
//           render={({ field }) => (
//             <TextField
//               {...field}
//               fullWidth
//               multiline
//               rows={4}
//               label='Description optional (max 500 characters)'
//               placeholder='Description'
//               error={!!errors.description}
//               helperText={errors.description?.message || `${field.value?.length || 0}/500`}
//               disabled={isSubmitting}
//             />
//           )}
//         />
//       </Grid>

//       {productType === 'ServiceBased' && (
//         <Grid item xs={12}>
//           <Box sx={{ mt: 2 }}>
//             <Typography variant='subtitle1' fontWeight={600} sx={{ mb: 2 }}>
//               Staff Members
//             </Typography>
//             {staffFields.map((field, index) => (
//               <Paper key={field.id} sx={{ p: 3, mb: 2, position: 'relative', overflow: 'visible' }}>
//                 {staffFields.length > 1 && (
//                   <IconButton
//                     size='small'
//                     color='error'
//                     onClick={() => removeStaff(index)}
//                     sx={{
//                       position: 'absolute',
//                       top: -10,
//                       right: -10,
//                       zIndex: 1,
//                       bgcolor: 'background.paper',
//                       border: '1px solid',
//                       borderColor: 'divider',
//                       '&:hover': { bgcolor: 'error.light' }
//                     }}
//                   >
//                     <Icon icon='tabler:x' fontSize={16} />
//                   </IconButton>
//                 )}
//                 <Grid container spacing={3}>
//                   <Grid item xs={12} md={6}>
//                     <Controller
//                       name={`staffMembers.${index}.firstName`}
//                       control={control}
//                       rules={{ required: 'First name is required' }}
//                       render={({ field }) => (
//                         <TextField
//                           {...field}
//                           fullWidth
//                           label='First Name *'
//                           size='small'
//                           error={!!errors.staffMembers?.[index]?.firstName}
//                           helperText={errors.staffMembers?.[index]?.firstName?.message}
//                           disabled={isSubmitting}
//                         />
//                       )}
//                     />
//                   </Grid>
//                   <Grid item xs={12} md={6}>
//                     <Controller
//                       name={`staffMembers.${index}.lastName`}
//                       control={control}
//                       rules={{ required: 'Last name is required' }}
//                       render={({ field }) => (
//                         <TextField
//                           {...field}
//                           fullWidth
//                           label='Last Name *'
//                           size='small'
//                           error={!!errors.staffMembers?.[index]?.lastName}
//                           helperText={errors.staffMembers?.[index]?.lastName?.message}
//                           disabled={isSubmitting}
//                         />
//                       )}
//                     />
//                   </Grid>
//                   <Grid item xs={12} md={6}>
//                     <Controller
//                       name={`staffMembers.${index}.email`}
//                       control={control}
//                       rules={{
//                         required: 'Email is required',
//                         pattern: {
//                           value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
//                           message: 'Invalid email address'
//                         }
//                       }}
//                       render={({ field }) => (
//                         <TextField
//                           {...field}
//                           fullWidth
//                           label='Email ID *'
//                           size='small'
//                           error={!!errors.staffMembers?.[index]?.email}
//                           helperText={errors.staffMembers?.[index]?.email?.message}
//                           disabled={isSubmitting}
//                         />
//                       )}
//                     />
//                   </Grid>
//                   <Grid item xs={12} md={6}>
//                     <Controller
//                       name={`staffMembers.${index}.phoneNumber`}
//                       control={control}
//                       rules={{ required: 'Phone number is required' }}
//                       render={({ field: phoneField }) => (
//                         <Controller
//                           name={`staffMembers.${index}.dialCodeCountry`}
//                           control={control}
//                           render={({ field: countryField }) => (
//                             <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
//                               <Autocomplete
//                                 sx={{ width: '200px' }}
//                                 options={countries}
//                                 autoHighlight
//                                 getOptionLabel={(option) => `${option.code} +${option.phone}`}
//                                 value={countries.find(c => c.code === countryField.value) || null}
//                                 onChange={(_, newValue) => {
//                                   if (newValue) {
//                                     countryField.onChange(newValue.code)
//                                     setValue(`staffMembers.${index}.countryCode`, `+${newValue.phone}`)
//                                   }
//                                 }}
//                                 renderOption={(props, option) => (
//                                   <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
//                                     <img
//                                       loading="lazy"
//                                       width="20"
//                                       src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
//                                       srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
//                                       alt=""
//                                       style={{ marginRight: '8px' }}
//                                     />
//                                     {option.label} ({option.code}) +{option.phone}
//                                   </Box>
//                                 )}
//                                 renderInput={(params) => (
//                                   <TextField
//                                     {...params}
//                                     label="Country Code"
//                                     size='small'
//                                     error={!!errors.staffMembers?.[index]?.dialCodeCountry}
//                                     helperText={errors.staffMembers?.[index]?.dialCodeCountry?.message}
//                                     disabled={isSubmitting}
//                                     inputProps={{
//                                       ...params.inputProps,
//                                       autoComplete: 'new-password',
//                                     }}
//                                   />
//                                 )}
//                               />
//                               <TextField
//                                 {...phoneField}
//                                 fullWidth
//                                 label='Phone Number *'
//                                 placeholder='555 000 0000'
//                                 size='small'
//                                 error={!!errors.staffMembers?.[index]?.phoneNumber}
//                                 helperText={errors.staffMembers?.[index]?.phoneNumber?.message}
//                                 disabled={isSubmitting}
//                               />
//                             </Box>
//                           )}
//                         />
//                       )}
//                     />
//                   </Grid>
//                 </Grid>
//               </Paper>
//             ))}
//             <Button
//               variant='outlined'
//               startIcon={<Icon icon='tabler:plus' />}
//               onClick={() => appendStaff({ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' })}
//               disabled={isSubmitting}
//             >
//               Add Staff Member
//             </Button>
//           </Box>
//         </Grid>
//       )}
//     </Grid>
//   )

//   const renderVariationDetails = () => (
//     <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) => {
//           const imagePreview = watch(`variations.${index}.imagePreview`)

//           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: 'divider',
//                     borderRadius: 2,
//                     p: imagePreview ? 2 : 4,
//                     textAlign: 'center',
//                     cursor: 'pointer',
//                     '&:hover': { borderColor: 'primary.main' }
//                   }}
//                 >
//                   <input
//                     type='file'
//                     accept='image/*'
//                     onChange={(e) => {
//                       const file = e.target.files?.[0] || null
//                       handleVariationImageChange(index, file)
//                     }}
//                     style={{ display: 'none' }}
//                     id={`image-upload-${index}`}
//                   />
//                   <label htmlFor={`image-upload-${index}`} style={{ cursor: 'pointer' }}>
//                     {imagePreview ? (
//                       <Box
//                         component='img'
//                         src={imagePreview}
//                         alt={`Variation ${index + 1}`}
//                         sx={{ maxHeight: 120, borderRadius: 1 }}
//                       />
//                     ) : (
//                       <>
//                         <Icon icon='tabler:cloud-upload' style={{ fontSize: 40, color: '#9E9E9E' }} />
//                         <Typography variant='body2' color='text.secondary'>
//                           Click or drag file to upload
//                         </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)
//                           recalcVariationAmount(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='number'
//                           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)
//                                 setValue(`variations.${index}.attributeValues.${attrIndex}.attributeName`, attr.attributeName)
//                               }}
//                             />
//                           )}
//                         />
//                       </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>
//   )

//   const renderSpecificationDetails = () => (
//     <Grid container spacing={4}>
//       <Grid item xs={12}>
//         <Typography variant='subtitle1' fontWeight={600} sx={{ mb: 3 }}>
//           Specifications
//         </Typography>

//         <Paper sx={{ p: 3 }}>
//           <Grid container spacing={3} alignItems='center'>
//             <Grid item xs={12} md={5}>
//               <TextField
//                 fullWidth
//                 label='Specification Name'
//                 placeholder='e.g. Material'
//                 size='small'
//                 value={specName}
//                 onChange={(e) => setSpecName(e.target.value)}
//               />
//             </Grid>
//             <Grid item xs={12} md={5}>
//               <TextField
//                 fullWidth
//                 label='Value'
//                 placeholder='e.g. Cotton'
//                 size='small'
//                 value={specValue}
//                 onChange={(e) => setSpecValue(e.target.value)}
//               />
//             </Grid>
//             <Grid item xs={12} md={2}>
//               <Button variant='contained' fullWidth onClick={handleAddSpecification}>
//                 {editingSpecId ? 'Update' : 'Add'}
//               </Button>
//             </Grid>
//           </Grid>
//         </Paper>

//         {specifications.length > 0 && (
//           <Box sx={{ mt: 3 }}>
//             <TableContainer component={Paper} variant='outlined'>
//               <Table>
//                 <TableHead>
//                   <TableRow>
//                     <TableCell><Typography fontWeight={600}>Specification Name</Typography></TableCell>
//                     <TableCell><Typography fontWeight={600}>Value</Typography></TableCell>
//                     <TableCell align='center'><Typography fontWeight={600}>Action</Typography></TableCell>
//                   </TableRow>
//                 </TableHead>
//                 <TableBody>
//                   {specifications.map((spec) => (
//                     <TableRow key={spec.id}>
//                       <TableCell>{spec.name}</TableCell>
//                       <TableCell>{spec.value}</TableCell>
//                       <TableCell align='center'>
//                         <IconButton size='small' color='primary' onClick={() => handleEditSpecification(spec)}>
//                           <Icon icon='tabler:edit' fontSize={18} />
//                         </IconButton>
//                         <IconButton size='small' color='error' onClick={() => handleRemoveSpecification(spec.id)}>
//                           <Icon icon='tabler:trash' fontSize={18} />
//                         </IconButton>
//                       </TableCell>
//                     </TableRow>
//                   ))}
//                 </TableBody>
//               </Table>
//             </TableContainer>
//           </Box>
//         )}
//       </Grid>
//     </Grid>
//   )

//   if (uid && isLoadingProduct) {
//     return (
//       <Fragment>
//         <Box sx={{ p: 6 }}>
//           <Skeleton variant='rectangular' height={200} sx={{ mb: 3 }} />
//           <Skeleton variant='rectangular' height={400} />
//         </Box>
//       </Fragment>
//     )
//   }

//   return (
//     <Fragment>
//       <Box mb={4}>
//         <Typography variant='h5' fontWeight={600}>
//           {uid ? 'Edit Product' : 'Add New Product'}
//         </Typography>
//         <Typography variant='body2' color='text.secondary'>
//           Enter your product details below
//         </Typography>
//       </Box>

//       <Card sx={{ p: 4 }}>
//         <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
//           {steps.map((label) => (
//             <Step key={label}>
//               <StepLabel>{label}</StepLabel>
//             </Step>
//           ))}
//         </Stepper>

//         <form onSubmit={handleSubmit(onSubmit)}>
//           {renderStepContent(activeStep)}

//           <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4, pt: 3, borderTop: '1px solid', borderColor: 'divider' }}>
//             <Box sx={{ display: 'flex', gap: 2 }}>
//               <Button
//                 variant='outlined'
//                 color='secondary'
//                 onClick={handleBack}
//                 disabled={activeStep === 0 || isSubmitting}
//               >
//                 ← Previous
//               </Button>
//               {activeStep < steps.length - 1 && (
//                 <Button
//                   variant='contained'
//                   onClick={handleNext}
//                   disabled={isSubmitting}
//                 >
//                   Next →
//                 </Button>
//               )}
//             </Box>
//             <Box sx={{ display: 'flex', gap: 2 }}>
//               <Button
//                 variant='outlined'
//                 color='error'
//                 onClick={handleReset}
//                 disabled={isSubmitting}
//               >
//                 Reset
//               </Button>
//               {activeStep === steps.length - 1 && (
//                 <Button
//                   type='submit'
//                   variant='contained'
//                   disabled={isSubmitting}
//                   startIcon={isSubmitting ? <CircularProgress size={16} color='inherit' /> : undefined}
//                 >
//                   {isSubmitting ? 'Submitting...' : 'Submit'}
//                 </Button>
//               )}
//             </Box>
//           </Box>
//         </form>
//       </Card>

//       <AddCategoryDrawer
//         open={showCategoryDrawer}
//         onClose={() => setShowCategoryDrawer(false)}
//         onSuccess={() => {
//           refetchCategories()
//           refetchParentCategories()
//           queryClient.invalidateQueries({ queryKey: ['categories'] })
//           queryClient.invalidateQueries({ queryKey: ['parentCategories'] })
//         }}
//         parentCategories={parentCategories}
//       />

//       <AddVendorDrawer
//         open={showVendorDrawer}
//         onClose={() => setShowVendorDrawer(false)}
//         onSuccess={() => {
//           refetchVendors()
//           queryClient.invalidateQueries({ queryKey: ['vendors'] })
//         }}
//       />

//       <AddTaxDrawer
//         open={showTaxDrawer}
//         onClose={() => setShowTaxDrawer(false)}
//         onSuccess={() => {
//           refetchTaxes()
//           queryClient.invalidateQueries({ queryKey: ['taxes'] })
//         }}
//       />
//     </Fragment>
//   )
// }

// CreateProduct.acl = { action: 'read', subject: 'permission' }

// export default CreateProduct


// sorted code ///////////////////////////
// src/pages/products/create-product/index.tsx

// src/pages/products/create-product/index.tsx

// import React, { useState, useEffect, Fragment } from 'react'
// import { useRouter } from 'next/router'

// // ** MUI
// import {
//   Box,
//   Button,
//   Card,
//   Typography,
//   Stepper,
//   Step,
//   StepLabel,
//   CircularProgress,
//   Skeleton
// } from '@mui/material'

// // ** React Hook Form
// import { useForm } from 'react-hook-form'

// // ** TanStack Query
// import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'

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

// // ** Custom components
// import ProductDetails from 'src/views/components/product/ProductDetails'
// import VariationDetails from 'src/views/components/product/VariationDetails'
// import SpecificationDetails from 'src/views/components/product/SpecificationDetails'
// import AddCategoryDrawer from 'src/views/components/product/drawers/AddCategoryDrawer'
// import AddVendorDrawer from 'src/views/components/product/drawers/AddVendorDrawer'
// import AddTaxDrawer from 'src/views/components/product/drawers/AddTaxDrawer'

// // ** Types and Hooks
// import {
//   ProductFormValues,
//   Category,
//   Vendor,
//   Tax
// } from 'src/views/components/product/types'
// import {
//   fetchCategories,
//   fetchVendors,
//   fetchTaxes,
//   fetchProductByUid,
//   createProduct,
//   updateProductBasicDetails,
//   updateProductVariations,
//   updateProductSpecifications,
//   getSelectedTaxDetails,
//   calculateTaxAmount,
//   getErrorMessage,
//   getFullImageUrl
// } from 'src/views/components/product/hooks'

// const CreateProduct = () => {
//   const router = useRouter()
//   const { uid } = router.query
// const [variationMRP,setVariationMRP]=useState(null);
//   const [activeStep, setActiveStep] = useState(0)
//   const [showCategoryDrawer, setShowCategoryDrawer] = useState(false)
//   const [showVendorDrawer, setShowVendorDrawer] = useState(false)
//   const [showTaxDrawer, setShowTaxDrawer] = useState(false)

//   const [specifications, setSpecifications] = useState<any[]>([])
//   const [specName, setSpecName] = useState('')
//   const [specValue, setSpecValue] = useState('')
//   const [editingSpecId, setEditingSpecId] = useState<string | null>(null)

//   const queryClient = useQueryClient()

//   const { data: categoriesData, refetch: refetchCategories } = useQuery({
//     queryKey: ['categories'],
//     queryFn: fetchCategories,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: parentCategoriesData, refetch: refetchParentCategories } = useQuery({
//     queryKey: ['parentCategories'],
//     queryFn: fetchCategories,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: vendorsData, refetch: refetchVendors } = useQuery({
//     queryKey: ['vendors'],
//     queryFn: fetchVendors,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: taxesData, refetch: refetchTaxes } = useQuery({
//     queryKey: ['taxes'],
//     queryFn: fetchTaxes,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: productData, isLoading: isLoadingProduct } = useQuery({
//     queryKey: ['product', uid],
//     queryFn: () => fetchProductByUid(uid as string),
//     enabled: !!uid,
//     staleTime: 0,
//   })


 
//   const categories: Category[] = categoriesData?.content?.result || []
//   const vendors: Vendor[] = vendorsData?.content?.result || []
//   const taxes: Tax[] = taxesData?.content?.result || []
//   const parentCategories: Category[] = parentCategoriesData?.content?.result || []

//   const {
//     control,
//     handleSubmit,
//     watch,
//     setValue,
//     getValues,
//     reset,
//     trigger,
//     formState: { errors }
//   } = useForm<ProductFormValues>({
//     defaultValues: {
//       productName: '',
//       productType: '',
//       categoryUid: '',
//       vendorUid: '',
//       taxCharges: 'Exclusive',
//       taxes: '',
//       description: '',
//       staffMembers: [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }],
//       variations: [{
//         size: '',
//         mrp: '',
//         stockQty: '',
//         noOfItems: '',
//         unit: '',
//         calculatedAmount: 0,
//         finalAmount: 0,
//         image: null,
//         imagePreview: '',
//         attributeValues: []
//       }],
//       trackStock: false
//     }
//   })

//   const productType = watch('productType')
//   const trackStock = watch('trackStock')
//   const categoryUid = watch('categoryUid')
//   const selectedTax = watch('taxes')

//   const selectedCategory: Category | undefined = categories.find(c => c.uid === categoryUid)
//   const categoryAttributes = selectedCategory?.attributeKeys || []
//   const selectedTaxDetails = getSelectedTaxDetails(selectedTax, taxes)

//   const recalcAllVariations = () => {
//     const currentVariations = getValues('variations') || []
//     currentVariations.forEach((v, index) => {
//       const mrp = v.mrp || '0'
//       const calculated = calculateTaxAmount(mrp, selectedTaxDetails)
//       const mrpValue = parseFloat(mrp) || 0
//       const final = mrpValue + calculated
//       setValue(`variations.${index}.calculatedAmount`, calculated)
//       setValue(`variations.${index}.finalAmount`, final)
//     })
//   }

//   useEffect(() => {
//     recalcAllVariations()
//     // eslint-disable-next-line react-hooks/exhaustive-deps
//   }, [selectedTax, selectedTaxDetails])

//   useEffect(() => {
//     const currentVariations = getValues('variations') || []
//     currentVariations.forEach((_, index) => {
//       const newAttrValues = categoryAttributes.map(attr => ({
//         attributeName: attr.attributeName,
//         value: ''
//       }))
//       setValue(`variations.${index}.attributeValues`, newAttrValues)
//     })
//     // eslint-disable-next-line react-hooks/exhaustive-deps
//   }, [categoryUid])

//   useEffect(() => {
//     if (uid && productData) {

          

//       const product = productData?.content?.result || productData?.content
//       if (product) {
       
//         // Map variations with image URLs
//         const variations = product.variations || []
//         const mappedVariations = variations.map((v: any) => {
//           let imagePreview = ''
//           if (v.variationImages && v.variationImages.length > 0) {
//             const imageUrl = v.variationImages[0].imageUrl || v.variationImages[0].url
//             if (imageUrl) {
//               imagePreview = getFullImageUrl(imageUrl)
//             }
//           }
//           return {
//             uid: v.uid || '',
//             size: '',
//             mrp: String(v.mrp || 0),
//             stockQty: v.stockQty || 0,
//             noOfItems: String(v.quantity || 1),
//             unit: v.unit || 'pcs',
//             calculatedAmount: v.calAmount || 0,
//             finalAmount: v.finalAmount || 0,
//             image: null,
//             imagePreview: imagePreview,
//             attributeValues: v.attributes && v.attributes.length > 0
//               ? v.attributes.map((attr: any) => ({
//                   attributeName: attr.attributeName || '',
//                   value: attr.value || ''
//                 }))
//               : []
//           }
//         })

//         // Map staff members with uid
//         const staffMembers = product.staffs && product.staffs.length > 0 
//           ? product.staffs.map((staff: any) => ({
//               uid: staff.uid || staff.staffUID || '',
//               firstName: staff.firstName || '',
//               lastName: staff.lastName || '',
//               email: staff.emailId || '',
//               phoneNumber: staff.phoneNumber || '',
//               countryCode: staff.dialCountryCode || '+1',
//               dialCodeCountry: staff.countryCode || 'US'
//             }))
//           : [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }]

//         reset({
//           productName: product.name || '',
//           productType: product.productType || 'ReadyToSell',
//           categoryUid: product.categoryUid?.uid || product.category?.uid || '',
//           vendorUid: product.vendorUid?.uid || product.vendor?.uid || '',
//           taxCharges: product.taxChargesType || 'Exclusive',
//           taxes: product.taxUid?.uid || '',
//           description: product.description || '',
//           staffMembers: staffMembers,
//           variations: mappedVariations.length > 0 ? mappedVariations : [{
//             size: '',
//             mrp: '',
//             stockQty: 0,
//             noOfItems: '1',
//             unit: 'pcs',
//             calculatedAmount: 0,
//             finalAmount: 0,
//             image: null,
//             imagePreview: '',
//             attributeValues: []
//           }],
//           trackStock: product.isInventoryManaged || false
//         })
        
//         if (product.specifications && Array.isArray(product.specifications) && product.specifications.length > 0) {
//           setSpecifications(
//             product.specifications.map((s: any, i: number) => ({
//               id: s.id || `spec-${i}-${Date.now()}`,
//               name: s.specKey || s.name || '',
//               value: s.specValue || s.value || ''
//             }))
//           )
//         }
//       }
//     }
   
    
//   }, [uid, productData, reset ,variationMRP])

//   const createMutation = useMutation({
//     mutationFn: createProduct,
//     onSuccess: (res) => {
//       toast.success(res?.content || 'Product created successfully')
//       router.push('/products')
//     },
//     onError: (err) => {
//       toast.error(getErrorMessage(err, 'Failed to create product'))
//     }
//   })

//   const updateBasicDetailsMutation = useMutation({
//     mutationFn: ({ uid, payload }: { uid: string; payload: any }) =>
//       updateProductBasicDetails(uid, payload),
//     onSuccess: () => {
//       toast.success('Product details updated successfully')
//     },
//     onError: (err) => {
//       toast.error(getErrorMessage(err, 'Failed to update product details'))
//     }
//   })

//   const updateVariationsMutation = useMutation({
//     mutationFn: ({ uid, payload }: { uid: string; payload: any }) =>
//       updateProductVariations(uid, payload),
//     onSuccess: () => {
//       toast.success('Variations updated successfully')
//     },
//     onError: (err) => {
//       toast.error(getErrorMessage(err, 'Failed to update variations'))
//     }
//   })

//   const updateSpecificationsMutation = useMutation({
//     mutationFn: ({ uid, specs }: { uid: string; specs: any[] }) =>
//       updateProductSpecifications(uid, specs),
//     onSuccess: () => {
//       toast.success('Specifications updated successfully')
//     },
//     onError: (err) => {
//       toast.error(getErrorMessage(err, 'Failed to update specifications'))
//     }
//   })

//   const stepFieldsMap: Record<number, string[]> = {
//     0: ['productName', 'productType', 'categoryUid', 'vendorUid'],
//     1: ['variations'],
//     2: []
//   }

//   const handleNext = async () => {
//     const fieldsToValidate = stepFieldsMap[activeStep] as any
//     const isValid = await trigger(fieldsToValidate)
//     if (!isValid) {
//       toast.error('Please fill all required fields correctly')
//       return
//     }

//     // If in edit mode, save current step data
//     if (uid) {
//       const data = getValues()
      
//       if (activeStep === 0) {
//         // Save Product Details
//         try {
//           await updateBasicDetailsMutation.mutateAsync({ 
//             uid: uid as string, 
//             payload: data 
//           })
//         } catch (error) {
//           return
//         }
//       } else if (activeStep === 1) {
//         // Save Variations
//         const variationsPayload = (data.variations || []).map(v => {
//           const { image, imagePreview, ...rest } = v
//           return { 
//             ...rest, 
//             image: image instanceof File ? image : null,
//             mrp: parseFloat(v.mrp) || 0,
//             noOfItems: parseInt(v.noOfItems) || 0
//           }
//         })
//         try {
//           await updateVariationsMutation.mutateAsync({ 
//             uid: uid as string, 
//             payload: { 
//               trackStock: data.trackStock, 
//               variations: variationsPayload 
//             } 
//           })
//           // Refresh product data to get updated image URLs
//           await queryClient.invalidateQueries({ queryKey: ['product', uid] })
//         } catch (error) {
//           return
//         }
//       }
//     }

//     setActiveStep((prev) => Math.min(prev + 1, 2))
//   }

//   const handleBack = () => {
//     setActiveStep((prev) => Math.max(prev - 1, 0))
//   }

//   const handleReset = () => {
//     reset({
//       productName: '',
//       productType: 'ReadyToSell',
//       categoryUid: '',
//       vendorUid: '',
//       taxCharges: 'Exclusive',
//       taxes: '',
//       description: '',
//       staffMembers: [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }],
//       variations: [{
//         size: '',
//         mrp: '',
//         stockQty: 0,
//         noOfItems: '1',
//         unit: 'pcs',
//         calculatedAmount: 0,
//         finalAmount: 0,
//         image: null,
//         imagePreview: '',
//         attributeValues: []
//       }],
//       trackStock: false
//     })
//     setSpecifications([])
//     setSpecName('')
//     setSpecValue('')
//     setEditingSpecId(null)
//     setActiveStep(0)
//   }

//   const onSubmit = async (data: ProductFormValues) => {
//     if (!uid) {
//       // Create mode - submit all at once
//       const variationsPayload = (data.variations || []).map(v => {
//         const { image, imagePreview, ...rest } = v
//         return { 
//           ...rest, 
//           image: image instanceof File ? image : null,
//           mrp: parseFloat(v.mrp) || 0,
//           noOfItems: parseInt(v.noOfItems) || 0
//         }
//       })

//       const payload = {
//         ...data,
//         variations: variationsPayload,
//         specifications: specifications.map(s => ({ name: s.name, value: s.value }))
//       }
//       createMutation.mutate(payload)
//     } else {
//       // Edit mode - save specifications only (last step)
//       try {
//         await updateSpecificationsMutation.mutateAsync({ 
//           uid: uid as string, 
//           specs: specifications.map(s => ({ 
//             specKey: s.name, 
//             specValue: s.value 
//           })) 
//         })
//         toast.success('Product updated successfully')
//         router.push('/products')
//       } catch (error) {
//         console.error('Update error:', error)
//       }
//     }
//   }

//   const isSubmitting = createMutation.isPending || 
//                        updateBasicDetailsMutation.isPending || 
//                        updateVariationsMutation.isPending || 
//                        updateSpecificationsMutation.isPending

//   const handleAddSpecification = () => {
//     if (!specName.trim() || !specValue.trim()) {
//       toast.error('Specification name and value are required')
//       return
//     }

//     if (editingSpecId) {
//       setSpecifications(prev =>
//         prev.map(s => (s.id === editingSpecId ? { ...s, name: specName.trim(), value: specValue.trim() } : s))
//       )
//       setEditingSpecId(null)
//     } else {
//       setSpecifications(prev => [
//         ...prev,
//         { id: `spec-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, name: specName.trim(), value: specValue.trim() }
//       ])
//     }
//     setSpecName('')
//     setSpecValue('')
//   }

//   const handleEditSpecification = (spec: any) => {
//     setEditingSpecId(spec.id)
//     setSpecName(spec.name)
//     setSpecValue(spec.value)
//   }

//   const handleRemoveSpecification = (id: string) => {
//     setSpecifications(prev => prev.filter(s => s.id !== id))
//     if (editingSpecId === id) {
//       setEditingSpecId(null)
//       setSpecName('')
//       setSpecValue('')
//     }
//   }

//   const recalcVariationAmount = (index: number, mrpValue: string) => {
//     const calculated = calculateTaxAmount(mrpValue, selectedTaxDetails)
//     const mrpNum = parseFloat(mrpValue) || 0
//     const final = mrpNum + calculated
//     setValue(`variations.${index}.calculatedAmount`, calculated)
//     setValue(`variations.${index}.finalAmount`, final)
//   }

//   const handleVariationImageChange = (index: number, file: File | null) => {
//     setValue(`variations.${index}.image`, file)
//     if (file) {
//       const reader = new FileReader()
//       reader.onload = () => {
//         setValue(`variations.${index}.imagePreview`, reader.result as string)
//       }
//       reader.readAsDataURL(file)
//     } else {
//       setValue(`variations.${index}.imagePreview`, '')
//     }
//   }

//   const steps = ['Product Details', 'Variation Details', 'Specification Details']

//   const renderStepContent = (step: number) => {
//     switch (step) {
//       case 0:
//         return (
//           <ProductDetails
//             control={control}
//             errors={errors}
//             categories={categories}
//             vendors={vendors}
//             taxes={taxes}
//             productType={productType}
//             isSubmitting={isSubmitting}
//             onAddCategory={() => setShowCategoryDrawer(true)}
//             onAddVendor={() => setShowVendorDrawer(true)}
//             onAddTax={() => setShowTaxDrawer(true)}
//           />
//         )
//       case 1:
//         return (
//           <VariationDetails
//           setVariationMRP={setVariationMRP}
//             control={control}
//             errors={errors}
//             productType={productType}
//             trackStock={trackStock}
//             categoryAttributes={categoryAttributes}
//             selectedCategory={selectedCategory}
//             isSubmitting={isSubmitting}
//             onRecalcVariation={recalcVariationAmount}
//             onImageChange={handleVariationImageChange}
//           />
//         )
//       case 2:
//         return (
//           <SpecificationDetails
//             specifications={specifications}
//             specName={specName}
//             specValue={specValue}
//             editingSpecId={editingSpecId}
//             onSpecNameChange={setSpecName}
//             onSpecValueChange={setSpecValue}
//             onAddSpecification={handleAddSpecification}
//             onEditSpecification={handleEditSpecification}
//             onRemoveSpecification={handleRemoveSpecification}
//             isSubmitting={isSubmitting}
//           />
//         )
//       default:
//         return null
//     }
//   }

//   if (uid && isLoadingProduct) {
//     return (
//       <Fragment>
//         <Box sx={{ p: 6 }}>
//           <Skeleton variant='rectangular' height={200} sx={{ mb: 3 }} />
//           <Skeleton variant='rectangular' height={400} />
//         </Box>
//       </Fragment>
//     )
//   }

//   return (
//     <Fragment>
//       <Box mb={4}>
//         <Typography variant='h5' fontWeight={600}>
//           {uid ? 'Edit Product' : 'Add New Product'}
//         </Typography>
//         <Typography variant='body2' color='text.secondary'>
//           Enter your product details below
//         </Typography>
//       </Box>

//       <Card sx={{ p: 4 }}>
//         <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
//           {steps.map((label) => (
//             <Step key={label}>
//               <StepLabel>{label}</StepLabel>
//             </Step>
//           ))}
//         </Stepper>

//         <form onSubmit={handleSubmit(onSubmit)}>
//           {renderStepContent(activeStep)}

//           <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4, pt: 3, borderTop: '1px solid', borderColor: 'divider' }}>
//             <Box sx={{ display: 'flex', gap: 2 }}>
//               <Button
//                 variant='outlined'
//                 color='secondary'
//                 onClick={handleBack}
//                 disabled={activeStep === 0 || isSubmitting}
//               >
//                 ← Previous
//               </Button>
//               {activeStep < steps.length - 1 && (
//                 <Button
//                   variant='contained'
//                   onClick={handleNext}
//                   disabled={isSubmitting}
//                 >
//                   Next →
//                 </Button>
//               )}
//             </Box>
//             <Box sx={{ display: 'flex', gap: 2 }}>
//               <Button
//                 variant='outlined'
//                 color='error'
//                 onClick={handleReset}
//                 disabled={isSubmitting}
//               >
//                 Reset
//               </Button>
//               {activeStep === steps.length - 1 && (
//                 <Button
//                   type='submit'
//                   variant='contained'
//                   disabled={isSubmitting}
//                   startIcon={isSubmitting ? <CircularProgress size={16} color='inherit' /> : undefined}
//                 >
//                   {isSubmitting ? 'Submitting...' : 'Submit'}
//                 </Button>
//               )}
//             </Box>
//           </Box>
//         </form>
//       </Card>

//       <AddCategoryDrawer
//         open={showCategoryDrawer}
//         onClose={() => setShowCategoryDrawer(false)}
//         onSuccess={() => {
//           refetchCategories()
//           refetchParentCategories()
//           queryClient.invalidateQueries({ queryKey: ['categories'] })
//           queryClient.invalidateQueries({ queryKey: ['parentCategories'] })
//         }}
//         parentCategories={parentCategories}
//       />

//       <AddVendorDrawer
//         open={showVendorDrawer}
//         onClose={() => setShowVendorDrawer(false)}
//         onSuccess={() => {
//           refetchVendors()
//           queryClient.invalidateQueries({ queryKey: ['vendors'] })
//         }}
//       />

//       <AddTaxDrawer
//         open={showTaxDrawer}
//         onClose={() => setShowTaxDrawer(false)}
//         onSuccess={() => {
//           refetchTaxes()
//           queryClient.invalidateQueries({ queryKey: ['taxes'] })
//         }}
//       />
//     </Fragment>
//   )
// }

// CreateProduct.acl = { action: 'read', subject: 'permission' }

// export default CreateProduct


// final changes ////////////////////////////////
// import React, { useState, useEffect, Fragment } from 'react'
// import { useRouter } from 'next/router'

// // ** MUI
// import {
//   Box,
//   Button,
//   Card,
//   Typography,
//   Stepper,
//   Step,
//   StepLabel,
//   CircularProgress,
//   Skeleton
// } from '@mui/material'

// // ** React Hook Form
// import { useForm } from 'react-hook-form'

// // ** TanStack Query
// import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'

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

// // ** Custom components
// import ProductDetails from 'src/views/components/product/ProductDetails'
// import VariationDetails from 'src/views/components/product/VariationDetails'
// import SpecificationDetails from 'src/views/components/product/SpecificationDetails'
// import AddCategoryDrawer from 'src/views/components/product/drawers/AddCategoryDrawer'
// import AddVendorDrawer from 'src/views/components/product/drawers/AddVendorDrawer'
// import AddTaxDrawer from 'src/views/components/product/drawers/AddTaxDrawer'

// // ** Types and Hooks
// import {
//   ProductFormValues,
//   Category,
//   Vendor,
//   Tax
// } from 'src/views/components/product/types'
// import {
//   fetchCategories,
//   fetchVendors,
//   fetchTaxes,
//   fetchProductByUid,
//   createProduct,
//   updateProductBasicDetails,
//   updateProductVariations,
//   updateProductSpecifications,
//   getSelectedTaxDetails,
//   calculateTaxAmount,
//   getErrorMessage,
//   getFullImageUrl
// } from 'src/views/components/product/hooks'

// const CreateProduct = () => {
//   const router = useRouter()
//   const { uid } = router.query
//   const [variationMRP, setVariationMRP] = useState(null)
//   const [activeStep, setActiveStep] = useState(0)
//   const [showCategoryDrawer, setShowCategoryDrawer] = useState(false)
//   const [showVendorDrawer, setShowVendorDrawer] = useState(false)
//   const [showTaxDrawer, setShowTaxDrawer] = useState(false)

//   const [specifications, setSpecifications] = useState<any[]>([])
//   const [specName, setSpecName] = useState('')
//   const [specValue, setSpecValue] = useState('')
//   const [editingSpecId, setEditingSpecId] = useState<string | null>(null)

//   const queryClient = useQueryClient()

//   const { data: categoriesData, refetch: refetchCategories } = useQuery({
//     queryKey: ['categories'],
//     queryFn: fetchCategories,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: parentCategoriesData, refetch: refetchParentCategories } = useQuery({
//     queryKey: ['parentCategories'],
//     queryFn: fetchCategories,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: vendorsData, refetch: refetchVendors } = useQuery({
//     queryKey: ['vendors'],
//     queryFn: fetchVendors,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { data: taxesData, refetch: refetchTaxes } = useQuery({
//     queryKey: ['taxes'],
//     queryFn: fetchTaxes,
//     staleTime: 5 * 60 * 1000,
//     refetchOnWindowFocus: false,
//   })

//   const { 
//     data: productData, 
//     isLoading: isLoadingProduct,
//     refetch: refetchProduct
//   } = useQuery({
//     queryKey: ['product', uid],
//     queryFn: () => fetchProductByUid(uid as string),
//     enabled: !!uid,
//     staleTime: 0,
//   })

//   const categories: Category[] = categoriesData?.content?.result || []
//   const vendors: Vendor[] = vendorsData?.content?.result || []
//   const taxes: Tax[] = taxesData?.content?.result || []
//   const parentCategories: Category[] = parentCategoriesData?.content?.result || []

//   const {
//     control,
//     handleSubmit,
//     watch,
//     setValue,
//     getValues,
//     reset,
//     trigger,
//     formState: { errors }
//   } = useForm<ProductFormValues>({
//     defaultValues: {
//       productName: '',
//       productType: '',
//       categoryUid: '',
//       vendorUid: '',
//       taxCharges: 'Exclusive',
//       taxes: '',
//       description: '',
//       staffMembers: [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }],
//       variations: [{
//         size: '',
//         mrp: '',
//         stockQty: '',
//         noOfItems: '',
//         unit: '',
//         calculatedAmount: 0,
//         finalAmount: 0,
//         image: null,
//         imagePreview: '',
//         attributeValues: []
//       }],
//       trackStock: false
//     }
//   })

//   const productType = watch('productType')
//   const trackStock = watch('trackStock')
//   const categoryUid = watch('categoryUid')
//   const selectedTax = watch('taxes')

//   const selectedCategory: Category | undefined = categories.find(c => c.uid === categoryUid)
//   const categoryAttributes = selectedCategory?.attributeKeys || []
//   const selectedTaxDetails = getSelectedTaxDetails(selectedTax, taxes)

//   const recalcAllVariations = () => {
//     const currentVariations = getValues('variations') || []
//     currentVariations.forEach((v, index) => {
//       const mrp = v.mrp || '0'
//       const calculated = calculateTaxAmount(mrp, selectedTaxDetails)
//       const mrpValue = parseFloat(mrp) || 0
//       const final = mrpValue + calculated
//       setValue(`variations.${index}.calculatedAmount`, calculated)
//       setValue(`variations.${index}.finalAmount`, final)
//     })
//   }

//   useEffect(() => {
//     recalcAllVariations()
//     // eslint-disable-next-line react-hooks/exhaustive-deps
//   }, [selectedTax, selectedTaxDetails])

//   useEffect(() => {
//     const currentVariations = getValues('variations') || []
//     currentVariations.forEach((_, index) => {
//       const newAttrValues = categoryAttributes.map(attr => ({
//         attributeName: attr.attributeName,
//         value: ''
//       }))
//       setValue(`variations.${index}.attributeValues`, newAttrValues)
//     })
//     // eslint-disable-next-line react-hooks/exhaustive-deps
//   }, [categoryUid])

//   // Function to populate form with product data
//   const populateFormWithProductData = (product: any) => {
//     if (!product) return

//     // Get variations and sort them by id (ascending) or createdAt
//     const variations = product.variations || []
//     // Sort variations by id (ascending) to maintain order
//     const sortedVariations = [...variations].sort((a, b) => {
//       // If both have id, sort by id
//       if (a.id && b.id) {
//         return a.id - b.id
//       }
//       // If no id, sort by createdAt
//       if (a.createdAt && b.createdAt) {
//         return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
//       }
//       return 0
//     })

//     const mappedVariations = sortedVariations.map((v: any) => {
//       let imagePreview = ''
//       if (v.variationImages && v.variationImages.length > 0) {
//         const imageUrl = v.variationImages[0].imageUrl || v.variationImages[0].url
//         if (imageUrl) {
//           imagePreview = getFullImageUrl(imageUrl)
//         }
//       }
//       return {
//         uid: v.uid || '',
//         size: '',
//         mrp: String(v.mrp || 0),
//         stockQty: v.stockQty !== undefined && v.stockQty !== null ? String(v.stockQty) : '',
//         noOfItems: v.quantity ? String(v.quantity) : '',
//         unit: v.unit || '',
//         calculatedAmount: v.calAmount || 0,
//         finalAmount: v.finalAmount || 0,
//         image: null,
//         imagePreview: imagePreview,
//         attributeValues: v.attributes && v.attributes.length > 0
//           ? v.attributes.map((attr: any) => ({
//               attributeName: attr.attributeName || '',
//               value: attr.value || ''
//             }))
//           : []
//       }
//     })

//     // Map staff members with uid
//     const staffMembers = product.staffs && product.staffs.length > 0 
//       ? product.staffs.map((staff: any) => ({
//           uid: staff.uid || staff.staffUID || '',
//           firstName: staff.firstName || '',
//           lastName: staff.lastName || '',
//           email: staff.emailId || '',
//           phoneNumber: staff.phoneNumber || '',
//           countryCode: staff.dialCountryCode || '+1',
//           dialCodeCountry: staff.countryCode || 'US'
//         }))
//       : [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }]

//     reset({
//       productName: product.name || '',
//       productType: product.productType || 'ReadyToSell',
//       categoryUid: product.categoryUid?.uid || product.category?.uid || '',
//       vendorUid: product.vendorUid?.uid || product.vendor?.uid || '',
//       taxCharges: product.taxChargesType || 'Exclusive',
//       taxes: product.taxUid?.uid || '',
//       description: product.description || '',
//       staffMembers: staffMembers,
//       variations: mappedVariations.length > 0 ? mappedVariations : [{
//         size: '',
//         mrp: '',
//         stockQty: '',
//         noOfItems: '',
//         unit: '',
//         calculatedAmount: 0,
//         finalAmount: 0,
//         image: null,
//         imagePreview: '',
//         attributeValues: []
//       }],
//       trackStock: product.isInventoryManaged || false
//     })
    
//     if (product.specifications && Array.isArray(product.specifications) && product.specifications.length > 0) {
//       setSpecifications(
//         product.specifications.map((s: any, i: number) => ({
//           id: s.id || `spec-${i}-${Date.now()}`,
//           name: s.specKey || s.name || '',
//           value: s.specValue || s.value || ''
//         }))
//       )
//     }
//   }

//   // Initial load of product data
//   useEffect(() => {
//     if (uid && productData) {
//       const product = productData?.content?.result || productData?.content
//       if (product) {
//         populateFormWithProductData(product)
//       }
//     }
//   }, [uid, productData])

//   const createMutation = useMutation({
//     mutationFn: createProduct,
//     onSuccess: (res) => {
//       toast.success(res?.content || 'Product created successfully', {
//         style: { zIndex: 999999 }
//       })
//       router.push('/products')
//     },
//     onError: (err) => {
//       toast.error(getErrorMessage(err, 'Failed to create product'), {
//         style: { zIndex: 999999 }
//       })
//     }
//   })

//   const updateBasicDetailsMutation = useMutation({
//     mutationFn: ({ uid, payload }: { uid: string; payload: any }) =>
//       updateProductBasicDetails(uid, payload),
//     onSuccess: async (_, variables) => {
//       toast.success('Product details updated successfully', {
//         style: { zIndex: 999999 }
//       })
      
//       // Refetch product data to get updated values
//       await refetchProduct()
      
//       // Update form with latest data
//       const updatedProduct = queryClient.getQueryData(['product', uid]) as any
//       if (updatedProduct) {
//         const product = updatedProduct?.content?.result || updatedProduct?.content
//         if (product) {
//           populateFormWithProductData(product)
//         }
//       }
//     },
//     onError: (err) => {
//       toast.error(getErrorMessage(err, 'Failed to update product details'), {
//         style: { zIndex: 999999 }
//       })
//     }
//   })

//   const updateVariationsMutation = useMutation({
//     mutationFn: ({ uid, payload }: { uid: string; payload: any }) =>
//       updateProductVariations(uid, payload),
//     onSuccess: async (_, variables) => {
//       toast.success('Variations updated successfully', {
//         style: { zIndex: 999999 }
//       })
      
//       // Refetch product data to get updated values
//       await refetchProduct()
      
//       // Update form with latest data
//       const updatedProduct = queryClient.getQueryData(['product', uid]) as any
//       if (updatedProduct) {
//         const product = updatedProduct?.content?.result || updatedProduct?.content
//         if (product) {
//           populateFormWithProductData(product)
//         }
//       }
//     },
//     onError: (err) => {
//       toast.error(getErrorMessage(err, 'Failed to update variations'), {
//         style: { zIndex: 999999 }
//       })
//     }
//   })

//   const updateSpecificationsMutation = useMutation({
//     mutationFn: ({ uid, specs }: { uid: string; specs: any[] }) =>
//       updateProductSpecifications(uid, specs),
//     onSuccess: () => {
//       toast.success('Specifications updated successfully', {
//         style: { zIndex: 999999 }
//       })
//     },
//     onError: (err) => {
//       toast.error(getErrorMessage(err, 'Failed to update specifications'), {
//         style: { zIndex: 999999 }
//       })
//     }
//   })

//   const stepFieldsMap: Record<number, string[]> = {
//     0: ['productName', 'productType', 'categoryUid', 'vendorUid'],
//     1: ['variations'],
//     2: []
//   }

//   const handleNext = async () => {
//     const fieldsToValidate = stepFieldsMap[activeStep] as any
//     const isValid = await trigger(fieldsToValidate)
//     if (!isValid) {
//       toast.error('Please fill all required fields correctly', {
//         style: { zIndex: 999999 }
//       })
//       return
//     }

//     // If in edit mode, save current step data
//     if (uid) {
//       const data = getValues()
      
//       if (activeStep === 0) {
//         // Save Product Details
//         try {
//           await updateBasicDetailsMutation.mutateAsync({ 
//             uid: uid as string, 
//             payload: data 
//           })
//         } catch (error) {
//           return
//         }
//       } else if (activeStep === 1) {
//         // Save Variations
//         const variationsPayload = (data.variations || []).map(v => {
//           const { image, imagePreview, ...rest } = v
//           return { 
//             ...rest, 
//             image: image instanceof File ? image : null,
//             mrp: parseFloat(v.mrp) || 0,
//             noOfItems: v.noOfItems ? parseInt(v.noOfItems) : 0
//           }
//         })
//         try {
//           await updateVariationsMutation.mutateAsync({ 
//             uid: uid as string, 
//             payload: { 
//               trackStock: data.trackStock, 
//               variations: variationsPayload 
//             } 
//           })
//         } catch (error) {
//           return
//         }
//       }
//     }

//     setActiveStep((prev) => Math.min(prev + 1, 2))
//   }

//   const handleBack = () => {
//     setActiveStep((prev) => Math.max(prev - 1, 0))
//   }

//   const handleReset = () => {
//     reset({
//       productName: '',
//       productType: 'ReadyToSell',
//       categoryUid: '',
//       vendorUid: '',
//       taxCharges: 'Exclusive',
//       taxes: '',
//       description: '',
//       staffMembers: [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }],
//       variations: [{
//         size: '',
//         mrp: '',
//         stockQty: '',
//         noOfItems: '',
//         unit: '',
//         calculatedAmount: 0,
//         finalAmount: 0,
//         image: null,
//         imagePreview: '',
//         attributeValues: []
//       }],
//       trackStock: false
//     })
//     setSpecifications([])
//     setSpecName('')
//     setSpecValue('')
//     setEditingSpecId(null)
//     setActiveStep(0)
//   }

//   const onSubmit = async (data: ProductFormValues) => {
//     if (!uid) {
//       // Create mode - submit all at once
//       const variationsPayload = (data.variations || []).map(v => {
//         const { image, imagePreview, ...rest } = v
//         return { 
//           ...rest, 
//           image: image instanceof File ? image : null,
//           mrp: parseFloat(v.mrp) || 0,
//           noOfItems: v.noOfItems ? parseInt(v.noOfItems) : 0
//         }
//       })

//       const payload = {
//         ...data,
//         variations: variationsPayload,
//         specifications: specifications.map(s => ({ name: s.name, value: s.value }))
//       }
//       createMutation.mutate(payload)
//     } else {
//       // Edit mode - save specifications only (last step)
//       try {
//         await updateSpecificationsMutation.mutateAsync({ 
//           uid: uid as string, 
//           specs: specifications.map(s => ({ 
//             specKey: s.name, 
//             specValue: s.value 
//           })) 
//         })
//         toast.success('Product updated successfully', {
//           style: { zIndex: 999999 }
//         })
//         router.push('/products')
//       } catch (error) {
//         console.error('Update error:', error)
//       }
//     }
//   }

//   const isSubmitting = createMutation.isPending || 
//                        updateBasicDetailsMutation.isPending || 
//                        updateVariationsMutation.isPending || 
//                        updateSpecificationsMutation.isPending

//   const handleAddSpecification = () => {
//     if (!specName.trim() || !specValue.trim()) {
//       toast.error('Specification name and value are required', {
//         style: { zIndex: 999999 }
//       })
//       return
//     }

//     if (editingSpecId) {
//       setSpecifications(prev =>
//         prev.map(s => (s.id === editingSpecId ? { ...s, name: specName.trim(), value: specValue.trim() } : s))
//       )
//       setEditingSpecId(null)
//     } else {
//       setSpecifications(prev => [
//         ...prev,
//         { id: `spec-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, name: specName.trim(), value: specValue.trim() }
//       ])
//     }
//     setSpecName('')
//     setSpecValue('')
//   }

//   const handleEditSpecification = (spec: any) => {
//     setEditingSpecId(spec.id)
//     setSpecName(spec.name)
//     setSpecValue(spec.value)
//   }

//   const handleRemoveSpecification = (id: string) => {
//     setSpecifications(prev => prev.filter(s => s.id !== id))
//     if (editingSpecId === id) {
//       setEditingSpecId(null)
//       setSpecName('')
//       setSpecValue('')
//     }
//   }

//   const recalcVariationAmount = (index: number, mrpValue: string) => {
//     const calculated = calculateTaxAmount(mrpValue, selectedTaxDetails)
//     const mrpNum = parseFloat(mrpValue) || 0
//     const final = mrpNum + calculated
//     setValue(`variations.${index}.calculatedAmount`, calculated)
//     setValue(`variations.${index}.finalAmount`, final)
//   }

//   const handleVariationImageChange = (index: number, file: File | null) => {
//     setValue(`variations.${index}.image`, file)
//     if (file) {
//       const reader = new FileReader()
//       reader.onload = () => {
//         setValue(`variations.${index}.imagePreview`, reader.result as string)
//       }
//       reader.readAsDataURL(file)
//     } else {
//       setValue(`variations.${index}.imagePreview`, '')
//     }
//   }

//   const steps = ['Product Details', 'Variation Details', 'Specification Details']

//   const renderStepContent = (step: number) => {
//     switch (step) {
//       case 0:
//         return (
//           <ProductDetails
//             control={control}
//             errors={errors}
//             categories={categories}
//             vendors={vendors}
//             taxes={taxes}
//             productType={productType}
//             isSubmitting={isSubmitting}
//             onAddCategory={() => setShowCategoryDrawer(true)}
//             onAddVendor={() => setShowVendorDrawer(true)}
//             onAddTax={() => setShowTaxDrawer(true)}
//           />
//         )
//       case 1:
//         return (
//           <VariationDetails
//             setVariationMRP={setVariationMRP}
//             control={control}
//             errors={errors}
//             productType={productType}
//             trackStock={trackStock}
//             categoryAttributes={categoryAttributes}
//             selectedCategory={selectedCategory}
//             isSubmitting={isSubmitting}
//             isEditMode={!!uid}
//             onRecalcVariation={recalcVariationAmount}
//             onImageChange={handleVariationImageChange}
//           />
//         )
//       case 2:
//         return (
//           <SpecificationDetails
//             specifications={specifications}
//             specName={specName}
//             specValue={specValue}
//             editingSpecId={editingSpecId}
//             onSpecNameChange={setSpecName}
//             onSpecValueChange={setSpecValue}
//             onAddSpecification={handleAddSpecification}
//             onEditSpecification={handleEditSpecification}
//             onRemoveSpecification={handleRemoveSpecification}
//             isSubmitting={isSubmitting}
//           />
//         )
//       default:
//         return null
//     }
//   }

//   if (uid && isLoadingProduct) {
//     return (
//       <Fragment>
//         <Box sx={{ p: 6 }}>
//           <Skeleton variant='rectangular' height={200} sx={{ mb: 3 }} />
//           <Skeleton variant='rectangular' height={400} />
//         </Box>
//       </Fragment>
//     )
//   }

//   return (
//     <Fragment>
//       <Box mb={4}>
//         <Typography variant='h5' fontWeight={600}>
//           {uid ? 'Edit Product' : 'Add New Product'}
//         </Typography>
//         <Typography variant='body2' color='text.secondary'>
//           Enter your product details below
//         </Typography>
//       </Box>

//       <Card sx={{ p: 4 }}>
//         <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
//           {steps.map((label) => (
//             <Step key={label}>
//               <StepLabel>{label}</StepLabel>
//             </Step>
//           ))}
//         </Stepper>

//         <form onSubmit={handleSubmit(onSubmit)}>
//           {renderStepContent(activeStep)}

//           <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4, pt: 3, borderTop: '1px solid', borderColor: 'divider' }}>
//             <Box sx={{ display: 'flex', gap: 2 }}>
//               <Button
//                 variant='outlined'
//                 color='secondary'
//                 onClick={handleBack}
//                 disabled={activeStep === 0 || isSubmitting}
//               >
//                 ← Previous
//               </Button>
//               {activeStep < steps.length - 1 && (
//                 <Button
//                   variant='contained'
//                   onClick={handleNext}
//                   disabled={isSubmitting}
//                 >
//                   Next →
//                 </Button>
//               )}
//             </Box>
//             <Box sx={{ display: 'flex', gap: 2 }}>
//               <Button
//                 variant='outlined'
//                 color='error'
//                 onClick={handleReset}
//                 disabled={isSubmitting}
//               >
//                 Reset
//               </Button>
//               {activeStep === steps.length - 1 && (
//                 <Button
//                   type='submit'
//                   variant='contained'
//                   disabled={isSubmitting}
//                   startIcon={isSubmitting ? <CircularProgress size={16} color='inherit' /> : undefined}
//                 >
//                   {isSubmitting ? 'Submitting...' : 'Submit'}
//                 </Button>
//               )}
//             </Box>
//           </Box>
//         </form>
//       </Card>

//       <AddCategoryDrawer
//         open={showCategoryDrawer}
//         onClose={() => setShowCategoryDrawer(false)}
//         onSuccess={() => {
//           refetchCategories()
//           refetchParentCategories()
//           queryClient.invalidateQueries({ queryKey: ['categories'] })
//           queryClient.invalidateQueries({ queryKey: ['parentCategories'] })
//         }}
//         parentCategories={parentCategories}
//       />

//       <AddVendorDrawer
//         open={showVendorDrawer}
//         onClose={() => setShowVendorDrawer(false)}
//         onSuccess={() => {
//           refetchVendors()
//           queryClient.invalidateQueries({ queryKey: ['vendors'] })
//         }}
//       />

//       <AddTaxDrawer
//         open={showTaxDrawer}
//         onClose={() => setShowTaxDrawer(false)}
//         onSuccess={() => {
//           refetchTaxes()
//           queryClient.invalidateQueries({ queryKey: ['taxes'] })
//         }}
//       />
//     </Fragment>
//   )
// }

// CreateProduct.acl = { action: 'read', subject: 'permission' }

// export default CreateProduct

// tyscript issue solved 
import React, { useState, useEffect, Fragment } from 'react'
import { useRouter } from 'next/router'

// ** MUI
import {
  Box,
  Button,
  Card,
  Typography,
  Stepper,
  Step,
  StepLabel,
  CircularProgress,
  Skeleton
} from '@mui/material'

// ** React Hook Form
import { useForm } from 'react-hook-form'

// ** TanStack Query
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'

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

// ** Custom components
import ProductDetails from 'src/views/components/product/ProductDetails'
import VariationDetails from 'src/views/components/product/VariationDetails'
import SpecificationDetails from 'src/views/components/product/SpecificationDetails'
import AddCategoryDrawer from 'src/views/components/product/drawers/AddCategoryDrawer'
import AddVendorDrawer from 'src/views/components/product/drawers/AddVendorDrawer'
import AddTaxDrawer from 'src/views/components/product/drawers/AddTaxDrawer'

// ** Types and Hooks
import {
  ProductFormValues,
  Category,
  Vendor,
  Tax
} from 'src/views/components/product/types'
import {
  fetchCategories,
  fetchVendors,
  fetchTaxes,
  fetchProductByUid,
  createProduct,
  updateProductBasicDetails,
  updateProductVariations,
  updateProductSpecifications,
  getSelectedTaxDetails,
  calculateTaxAmount,
  getErrorMessage,
  getFullImageUrl
} from 'src/views/components/product/hooks'

const CreateProduct = () => {
  const router = useRouter()
  const { uid } = router.query
  const [variationMRP, setVariationMRP] = useState(null)
  const [activeStep, setActiveStep] = useState(0)
  const [showCategoryDrawer, setShowCategoryDrawer] = useState(false)
  const [showVendorDrawer, setShowVendorDrawer] = useState(false)
  const [showTaxDrawer, setShowTaxDrawer] = useState(false)

  const [specifications, setSpecifications] = useState<any[]>([])
  const [specName, setSpecName] = useState('')
  const [specValue, setSpecValue] = useState('')
  const [editingSpecId, setEditingSpecId] = useState<string | null>(null)

  const queryClient = useQueryClient()

  const { data: categoriesData, refetch: refetchCategories } = useQuery({
    queryKey: ['categories'],
    queryFn: fetchCategories,
    staleTime: 5 * 60 * 1000,
    refetchOnWindowFocus: false,
  })

  const { data: parentCategoriesData, refetch: refetchParentCategories } = useQuery({
    queryKey: ['parentCategories'],
    queryFn: fetchCategories,
    staleTime: 5 * 60 * 1000,
    refetchOnWindowFocus: false,
  })

  const { data: vendorsData, refetch: refetchVendors } = useQuery({
    queryKey: ['vendors'],
    queryFn: fetchVendors,
    staleTime: 5 * 60 * 1000,
    refetchOnWindowFocus: false,
  })

  const { data: taxesData, refetch: refetchTaxes } = useQuery({
    queryKey: ['taxes'],
    queryFn: fetchTaxes,
    staleTime: 5 * 60 * 1000,
    refetchOnWindowFocus: false,
  })

  const { 
    data: productData, 
    isLoading: isLoadingProduct,
    refetch: refetchProduct
  } = useQuery({
    queryKey: ['product', uid],
    queryFn: () => fetchProductByUid(uid as string),
    enabled: !!uid,
    staleTime: 0,
  })

  const categories: Category[] = categoriesData?.content?.result || []
  const vendors: Vendor[] = vendorsData?.content?.result || []
  const taxes: Tax[] = taxesData?.content?.result || []
  const parentCategories: Category[] = parentCategoriesData?.content?.result || []

  const {
    control,
    handleSubmit,
    watch,
    setValue,
    getValues,
    reset,
    trigger,
    formState: { errors }
  } = useForm<ProductFormValues>({
    defaultValues: {
      productName: '',
      productType: 'ReadyToSell',
      categoryUid: '',
      vendorUid: '',
      taxCharges: 'Exclusive',
      taxes: '',
      description: '',
      staffMembers: [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }],
      variations: [{
        size: '',
        mrp: '',
        stockQty: 0,
        noOfItems: '',
        unit: '',
        calculatedAmount: 0,
        finalAmount: 0,
        image: null,
        imagePreview: '',
        attributeValues: []
      }],
      trackStock: false
    }
  })

  const productType = watch('productType')
  const trackStock = watch('trackStock') ?? false
  const categoryUid = watch('categoryUid')
  const selectedTax = watch('taxes')

  const selectedCategory: Category | undefined = categories.find(c => c.uid === categoryUid)
  const categoryAttributes = selectedCategory?.attributeKeys || []
  const selectedTaxDetails = getSelectedTaxDetails(selectedTax, taxes)

  const recalcAllVariations = () => {
    const currentVariations = getValues('variations') || []
    currentVariations.forEach((v, index) => {
      const mrp = v.mrp || '0'
      const calculated = calculateTaxAmount(mrp, selectedTaxDetails)
      const mrpValue = parseFloat(mrp) || 0
      const final = mrpValue + calculated
      setValue(`variations.${index}.calculatedAmount`, calculated)
      setValue(`variations.${index}.finalAmount`, final)
    })
  }

  useEffect(() => {
    recalcAllVariations()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedTax, selectedTaxDetails])

  useEffect(() => {
    const currentVariations = getValues('variations') || []
    currentVariations.forEach((_, index) => {
      const newAttrValues = categoryAttributes.map(attr => ({
        attributeName: attr.attributeName,
        value: ''
      }))
      setValue(`variations.${index}.attributeValues`, newAttrValues)
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [categoryUid])

  // Function to populate form with product data
  const populateFormWithProductData = (product: any) => {
    if (!product) return

    // Get variations and sort them by id (ascending) or createdAt
    const variations = product.variations || []

    // Sort variations by id (ascending) to maintain order
    const sortedVariations = [...variations].sort((a, b) => {
      // If both have id, sort by id
      if (a.id && b.id) {
        return a.id - b.id
      }

      // If no id, sort by createdAt
      if (a.createdAt && b.createdAt) {
        return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
      }
      return 0
    })

    const mappedVariations = sortedVariations.map((v: any) => {
      let imagePreview = ''
      if (v.variationImages && v.variationImages.length > 0) {
        const imageUrl = v.variationImages[0].imageUrl || v.variationImages[0].url
        if (imageUrl) {
          imagePreview = getFullImageUrl(imageUrl)
        }
      }
      return {
        uid: v.uid || '',
        size: '',
        mrp: String(v.mrp || 0),
        stockQty: v.stockQty !== undefined && v.stockQty !== null ? Number(v.stockQty) : 0,
        noOfItems: v.quantity ? String(v.quantity) : '',
        unit: v.unit || '',
        calculatedAmount: v.calAmount || 0,
        finalAmount: v.finalAmount || 0,
        image: null,
        imagePreview: imagePreview,
        attributeValues: v.attributes && v.attributes.length > 0
          ? v.attributes.map((attr: any) => ({
              attributeName: attr.attributeName || '',
              value: attr.value || ''
            }))
          : []
      }
    })

    // Map staff members with uid
    const staffMembers = product.staffs && product.staffs.length > 0 
      ? product.staffs.map((staff: any) => ({
          uid: staff.uid || staff.staffUID || '',
          firstName: staff.firstName || '',
          lastName: staff.lastName || '',
          email: staff.emailId || '',
          phoneNumber: staff.phoneNumber || '',
          countryCode: staff.dialCountryCode || '+1',
          dialCodeCountry: staff.countryCode || 'US'
        }))
      : [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }]

    reset({
      productName: product.name || '',
      productType: product.productType || 'ReadyToSell',
      categoryUid: product.categoryUid?.uid || product.category?.uid || '',
      vendorUid: product.vendorUid?.uid || product.vendor?.uid || '',
      taxCharges: product.taxChargesType || 'Exclusive',
      taxes: product.taxUid?.uid || '',
      description: product.description || '',
      staffMembers: staffMembers,
      variations: mappedVariations.length > 0 ? mappedVariations : [{
        size: '',
        mrp: '',
        stockQty: 0,
        noOfItems: '',
        unit: '',
        calculatedAmount: 0,
        finalAmount: 0,
        image: null,
        imagePreview: '',
        attributeValues: []
      }],
      trackStock: product.isInventoryManaged || false
    })
    
    if (product.specifications && Array.isArray(product.specifications) && product.specifications.length > 0) {
      setSpecifications(
        product.specifications.map((s: any, i: number) => ({
          id: s.id || `spec-${i}-${Date.now()}`,
          name: s.specKey || s.name || '',
          value: s.specValue || s.value || ''
        }))
      )
    }
  }

  // Initial load of product data
  useEffect(() => {
    if (uid && productData) {
      const product = productData?.content?.result || productData?.content
      if (product) {
        populateFormWithProductData(product)
      }
    }
  }, [uid, productData])

  const createMutation = useMutation({
    mutationFn: createProduct,
    onSuccess: (res) => {
      toast.success(res?.content || 'Product created successfully', {
        style: { zIndex: 999999 }
      })
      router.push('/products')
    },
    onError: (err) => {
      toast.error(getErrorMessage(err, 'Failed to create product'), {
        style: { zIndex: 999999 }
      })
    }
  })

  const updateBasicDetailsMutation = useMutation({
    mutationFn: ({ uid, payload }: { uid: string; payload: any }) =>
      updateProductBasicDetails(uid, payload),
    onSuccess: async (_, variables) => {
      toast.success('Product details updated successfully', {
        style: { zIndex: 999999 }
      })
      
      // Refetch product data to get updated values
      await refetchProduct()
      
      // Update form with latest data
      const updatedProduct = queryClient.getQueryData(['product', uid]) as any
      if (updatedProduct) {
        const product = updatedProduct?.content?.result || updatedProduct?.content
        if (product) {
          populateFormWithProductData(product)
        }
      }
    },
    onError: (err) => {
      toast.error(getErrorMessage(err, 'Failed to update product details'), {
        style: { zIndex: 999999 }
      })
    }
  })

  const updateVariationsMutation = useMutation({
    mutationFn: ({ uid, payload }: { uid: string; payload: any }) =>
      updateProductVariations(uid, payload),
    onSuccess: async (_, variables) => {
      toast.success('Variations updated successfully', {
        style: { zIndex: 999999 }
      })
      
      // Refetch product data to get updated values
      await refetchProduct()
      
      // Update form with latest data
      const updatedProduct = queryClient.getQueryData(['product', uid]) as any
      if (updatedProduct) {
        const product = updatedProduct?.content?.result || updatedProduct?.content
        if (product) {
          populateFormWithProductData(product)
        }
      }
    },
    onError: (err) => {
      toast.error(getErrorMessage(err, 'Failed to update variations'), {
        style: { zIndex: 999999 }
      })
    }
  })

  const updateSpecificationsMutation = useMutation({
    mutationFn: ({ uid, specs }: { uid: string; specs: any[] }) =>
      updateProductSpecifications(uid, specs),
    onSuccess: () => {
      toast.success('Specifications updated successfully', {
        style: { zIndex: 999999 }
      })
    },
    onError: (err) => {
      toast.error(getErrorMessage(err, 'Failed to update specifications'), {
        style: { zIndex: 999999 }
      })
    }
  })

  const stepFieldsMap: Record<number, string[]> = {
    0: ['productName', 'productType', 'categoryUid', 'vendorUid'],
    1: ['variations'],
    2: []
  }

  const handleNext = async () => {
    const fieldsToValidate = stepFieldsMap[activeStep] as any
    const isValid = await trigger(fieldsToValidate)
    if (!isValid) {
      toast.error('Please fill all required fields correctly', {
        style: { zIndex: 999999 }
      })
      return
    }

    // If in edit mode, save current step data
    if (uid) {
      const data = getValues()
      
      if (activeStep === 0) {
        // Save Product Details
        try {
          await updateBasicDetailsMutation.mutateAsync({ 
            uid: uid as string, 
            payload: data 
          })
        } catch (error) {
          return
        }
      } else if (activeStep === 1) {
        // Save Variations
        const variationsPayload = (data.variations || []).map(v => {
          const { image, imagePreview, ...rest } = v
          return { 
            ...rest, 
            image: image instanceof File ? image : null,
            mrp: parseFloat(v.mrp) || 0,
            stockQty: Number(v.stockQty) || 0,
            noOfItems: v.noOfItems ? parseInt(v.noOfItems) : 0
          }
        })
        try {
          await updateVariationsMutation.mutateAsync({ 
            uid: uid as string, 
            payload: { 
              trackStock: data.trackStock || false, 
              variations: variationsPayload 
            } 
          })
        } catch (error) {
          return
        }
      }
    }

    setActiveStep((prev) => Math.min(prev + 1, 2))
  }

  const handleBack = () => {
    setActiveStep((prev) => Math.max(prev - 1, 0))
  }

  const handleReset = () => {
    reset({
      productName: '',
      productType: 'ReadyToSell',
      categoryUid: '',
      vendorUid: '',
      taxCharges: 'Exclusive',
      taxes: '',
      description: '',
      staffMembers: [{ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' }],
      variations: [{
        size: '',
        mrp: '',
        stockQty: 0,
        noOfItems: '',
        unit: '',
        calculatedAmount: 0,
        finalAmount: 0,
        image: null,
        imagePreview: '',
        attributeValues: []
      }],
      trackStock: false
    })
    setSpecifications([])
    setSpecName('')
    setSpecValue('')
    setEditingSpecId(null)
    setActiveStep(0)
  }

  const onSubmit = async (data: ProductFormValues) => {
    if (!uid) {
      // Create mode - submit all at once
      const variationsPayload = (data.variations || []).map(v => {
        const { image, imagePreview, ...rest } = v
        return { 
          ...rest, 
          image: image instanceof File ? image : null,
          mrp: parseFloat(v.mrp) || 0,
          stockQty: Number(v.stockQty) || 0,
          noOfItems: v.noOfItems ? parseInt(v.noOfItems) : 0
        }
      })

      const payload = {
        ...data,
        variations: variationsPayload,
        specifications: specifications.map(s => ({ name: s.name, value: s.value }))
      }
      createMutation.mutate(payload)
    } else {
      // Edit mode - save specifications only (last step)
      try {
        await updateSpecificationsMutation.mutateAsync({ 
          uid: uid as string, 
          specs: specifications.map(s => ({ 
            specKey: s.name, 
            specValue: s.value 
          })) 
        })
        toast.success('Product updated successfully', {
          style: { zIndex: 999999 }
        })
        router.push('/products')
      } catch (error) {
        console.error('Update error:', error)
      }
    }
  }

  const isSubmitting = createMutation.isPending || 
                       updateBasicDetailsMutation.isPending || 
                       updateVariationsMutation.isPending || 
                       updateSpecificationsMutation.isPending

  const handleAddSpecification = () => {
    if (!specName.trim() || !specValue.trim()) {
      toast.error('Specification name and value are required', {
        style: { zIndex: 999999 }
      })
      return
    }

    if (editingSpecId) {
      setSpecifications(prev =>
        prev.map(s => (s.id === editingSpecId ? { ...s, name: specName.trim(), value: specValue.trim() } : s))
      )
      setEditingSpecId(null)
    } else {
      setSpecifications(prev => [
        ...prev,
        { id: `spec-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, name: specName.trim(), value: specValue.trim() }
      ])
    }
    setSpecName('')
    setSpecValue('')
  }

  const handleEditSpecification = (spec: any) => {
    setEditingSpecId(spec.id)
    setSpecName(spec.name)
    setSpecValue(spec.value)
  }

  const handleRemoveSpecification = (id: string) => {
    setSpecifications(prev => prev.filter(s => s.id !== id))
    if (editingSpecId === id) {
      setEditingSpecId(null)
      setSpecName('')
      setSpecValue('')
    }
  }

  const recalcVariationAmount = (index: number, mrpValue: string) => {
    const calculated = calculateTaxAmount(mrpValue, selectedTaxDetails)
    const mrpNum = parseFloat(mrpValue) || 0
    const final = mrpNum + calculated
    setValue(`variations.${index}.calculatedAmount`, calculated)
    setValue(`variations.${index}.finalAmount`, final)
  }

  const handleVariationImageChange = (index: number, file: File | null) => {
    setValue(`variations.${index}.image`, file)
    if (file) {
      const reader = new FileReader()
      reader.onload = () => {
        setValue(`variations.${index}.imagePreview`, reader.result as string)
      }
      reader.readAsDataURL(file)
    } else {
      setValue(`variations.${index}.imagePreview`, '')
    }
  }

  const steps = ['Product Details', 'Variation Details', 'Specification Details']

  const renderStepContent = (step: number) => {
    switch (step) {
      case 0:
        return (
          <ProductDetails
            control={control}
            errors={errors}
            categories={categories}
            vendors={vendors}
            taxes={taxes}
            productType={productType}
            isSubmitting={isSubmitting}
            onAddCategory={() => setShowCategoryDrawer(true)}
            onAddVendor={() => setShowVendorDrawer(true)}
            onAddTax={() => setShowTaxDrawer(true)}
          />
        )
      case 1:
        return (
          <VariationDetails
            setVariationMRP={setVariationMRP}
            control={control}
            errors={errors}
            productType={productType}
            trackStock={trackStock}
            categoryAttributes={categoryAttributes}
            selectedCategory={selectedCategory}
            isSubmitting={isSubmitting}
            isEditMode={!!uid}
            onRecalcVariation={recalcVariationAmount}
            onImageChange={handleVariationImageChange}
          />
        )
      case 2:
        return (
          <SpecificationDetails
            specifications={specifications}
            specName={specName}
            specValue={specValue}
            editingSpecId={editingSpecId}
            onSpecNameChange={setSpecName}
            onSpecValueChange={setSpecValue}
            onAddSpecification={handleAddSpecification}
            onEditSpecification={handleEditSpecification}
            onRemoveSpecification={handleRemoveSpecification}
            isSubmitting={isSubmitting}
          />
        )
      default:
        return null
    }
  }

  if (uid && isLoadingProduct) {
    return (
      <Fragment>
        <Box sx={{ p: 6 }}>
          <Skeleton variant='rectangular' height={200} sx={{ mb: 3 }} />
          <Skeleton variant='rectangular' height={400} />
        </Box>
      </Fragment>
    )
  }

  return (
    <Fragment>
      <Box mb={4}>
        <Typography variant='h5' fontWeight={600}>
          {uid ? 'Edit Product' : 'Add New Product'}
        </Typography>
        <Typography variant='body2' color='text.secondary'>
          Enter your product details below
        </Typography>
      </Box>

      <Card sx={{ p: 4 }}>
        <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
          {steps.map((label) => (
            <Step key={label}>
              <StepLabel>{label}</StepLabel>
            </Step>
          ))}
        </Stepper>

        <form onSubmit={handleSubmit(onSubmit)}>
          {renderStepContent(activeStep)}

          <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4, pt: 3, borderTop: '1px solid', borderColor: 'divider' }}>
            <Box sx={{ display: 'flex', gap: 2 }}>
              <Button
                variant='outlined'
                color='secondary'
                onClick={handleBack}
                disabled={activeStep === 0 || isSubmitting}
              >
                ← Previous
              </Button>
              {activeStep < steps.length - 1 && (
                <Button
                  variant='contained'
                  onClick={handleNext}
                  disabled={isSubmitting}
                >
                  Next →
                </Button>
              )}
            </Box>
            <Box sx={{ display: 'flex', gap: 2 }}>
              <Button
                variant='outlined'
                color='error'
                onClick={handleReset}
                disabled={isSubmitting}
              >
                Reset
              </Button>
              {activeStep === steps.length - 1 && (
                <Button
                  type='submit'
                  variant='contained'
                  disabled={isSubmitting}
                  startIcon={isSubmitting ? <CircularProgress size={16} color='inherit' /> : undefined}
                >
                  {isSubmitting ? 'Submitting...' : 'Submit'}
                </Button>
              )}
            </Box>
          </Box>
        </form>
      </Card>

      <AddCategoryDrawer
        open={showCategoryDrawer}
        onClose={() => setShowCategoryDrawer(false)}
        onSuccess={() => {
          refetchCategories()
          refetchParentCategories()
          queryClient.invalidateQueries({ queryKey: ['categories'] })
          queryClient.invalidateQueries({ queryKey: ['parentCategories'] })
        }}
        parentCategories={parentCategories}
      />

      <AddVendorDrawer
        open={showVendorDrawer}
        onClose={() => setShowVendorDrawer(false)}
        onSuccess={() => {
          refetchVendors()
          queryClient.invalidateQueries({ queryKey: ['vendors'] })
        }}
      />

      <AddTaxDrawer
        open={showTaxDrawer}
        onClose={() => setShowTaxDrawer(false)}
        onSuccess={() => {
          refetchTaxes()
          queryClient.invalidateQueries({ queryKey: ['taxes'] })
        }}
      />
    </Fragment>
  )
}

CreateProduct.acl = { action: 'read', subject: 'permission' }

export default CreateProduct