import { ArrowLeftOutlined, FormOutlined, ReloadOutlined, UploadOutlined } from '@ant-design/icons';
import {
  Button,
  Grid,
  InputLabel,
  Stack,
  TextField,
  Autocomplete,
  Box,
  InputAdornment,
  FormHelperText,
  IconButton,
  Dialog,
  DialogTitle,
  DialogActions,
  DialogContent,
  CircularProgress,
  useMediaQuery,
  Tooltip,
  Avatar,
  Typography
} from '@mui/material';
import axios from 'axios';
import MainCard from 'components/MainCard';
import React, { useState } from 'react';
import { useFormik } from 'formik';
import * as yup from 'yup';
// import { useNavigate } from 'react-router';
import { handleFileChange } from 'components/third-party/s3img';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { getproductsubcategories, getProductUnits, getproductvariants, productCreate } from './api';
import { enqueueSnackbar } from 'notistack';
import uploadImage from '../../assets/images/uploadImage.png';
import AddIcon from '@mui/icons-material/Add';
import { useTheme } from '@emotion/react';
import OpenToast from 'components/third-party/OpenToast';
import TitleCard from 'components/TitleCard';
import { getLoginUser } from 'supportFuctions/getLoginUser';

const validationSchema = yup.object({
  // applocationid: yup.number().required('Please select location '),
  // tenantid: yup.number().required('Please select Tenant '),
  // categoryid: yup.number().required('Please select a  category '),
  subcategoryid: yup
    .number()
    // .typeError("Subcategory must be a number")
    // .nullable()
    .required('Please select subcategory'),
  // .test("not-null", "Please select subcategory", (value) => {
  //   return value !== null && value !== undefined;
  // })
  variants: yup.number(),
  productname: yup.string().required('Product Name is required'),
  productdesc: yup.string().required('Product Description is required'),
  productunit: yup.string().required('Product Unit is required'),
  // unitvalue: yup.string().required(" Unit Value is required"),
  unitvalue: yup
    .number()
    .typeError('Unit Value must be a number') // in case user enters letters
    .required('Unit Value is required')
    .moreThan(0, 'Value must be greater than 0'),
  productcost: yup
    .number()
    .typeError('Product Costmust be a number') // in case user enters letters
    .required(' Product Cost is required')
    .moreThan(0, 'Value must be greater than 0'),
  taxamount: yup.number().required(' Tax Amount is required'),
  taxpercent: yup.number().required(' Tax Percent is required'),
  producttax: yup.number().required(' Product Tax is required'),
  quantity: yup.number().required(' Minimun quantity is required'),
  // productstock: yup
  //   .number()
  //   .typeError('Product Stock be a number') // in case user enters letters
  //   .required(' Product Stock is required')
  //   .moreThan(0, 'Value must be greater than 0'),
  productstatus: yup.string().required('Product Status  is required'),
  productimage: yup.string().required('Product Image  is required')
  // productimage: yup
  //   .mixed()
  //   .required("Image is required")
  //   // .test("fileSize", "File too large", (value) => {
  //   //   return value && value.size <= 1024 * 1024; // <= 1 MB
  //   // })
  //   .test("fileType", "Unsupported file type", (value) => {
  //     return (
  //       value && ["image/jpeg", "image/png", "image/webp"].includes(value.type)
  //     );
  //   }),
});

/* ============================================= || opentoast || ============================================= */

const opentoast = (message, variant, duration) => {
  enqueueSnackbar(message, {
    variant: variant,
    anchorOrigin: { vertical: 'top', horizontal: 'right' },
    autoHideDuration: duration
  });
};

const Addproducts = ({ setAddDialog }) => {
  const theme = useTheme();
  const userdata = getLoginUser();
  const [groupDialog, setGroupDialog] = useState(false);
  const [imgloading, setImgLoading] = useState(false);
  // const isMobile = useMediaQuery(theme.breakpoints.down('custom500'));
  // const navigate = useNavigate();
  const useCreateProduct = () => {
    const queryClient = useQueryClient();
    return useMutation({
      mutationFn: productCreate,
      onSuccess: (data) => {
        console.log('✅ Product created:', data);
        queryClient.invalidateQueries({ queryKey: ['productlist'] });
           opentoast('Product created Succesfully', 'success', 2000);
        // navigate('../products');
          setAddDialog(false);
      },
      onError: (error) => {
        console.error('❌ Product creation failed:', error);
        opentoast(error.message, 'error', 2000);
      }
    });
  };

  const { mutate: createProduct } = useCreateProduct();

  const handleCreate = (values) => {
    createProduct(values); // values = formik.values
  };
  const formik = useFormik({
    initialValues: {
      applocationid: userdata?.applocationid,
      tenantid: userdata?.tenantid,
      categoryid: userdata?.categoryid,
      // locationid: userdata?.locationid,
      subcategoryid: 0,
      variants: 0, // variantid
      variantname: '',
      productname: '',
      productdesc: '',
      productunit: '',
      unitvalue: null,
      productcost: null,
      taxamount: null,
      taxpercent: 0,
      producttax: 0,
      productstock: 0,
      othercost: 0.0,
      approve: 0,
      productstatus: 'InActive',
      productimage: null,
      quantity: null
    },
    validationSchema,
    onSubmit: handleCreate
  });

  const [variantbody, setvariantBody] = useState({
    subcategoryid: formik?.values?.subcategoryid || 0,
    categoryid: userdata?.categoryid,
    tenantid: userdata?.tenantid,
    variantname: '',
    status: 'Active',
    varianytype: 'variant'
  });

  const { data: SubCat } = useQuery({
    queryKey: ['getsubcategory'],
    queryFn: getproductsubcategories
  });

  // const { data: productVariants = [], refetch: getproductvariantsRefetch } = useQuery({
  //   queryKey: ['productvariants', formik.values.subcategoryid],
  //   queryFn: ({ queryKey }) => {
  //     const [, subcategoryid] = queryKey;
  //     return subcategoryid ? getproductvariants(subcategoryid) : Promise.resolve([]); // return empty array if null
  //   },
  //   enabled: !!formik.values.subcategoryid // prevent call when subcategoryid is null or 0
  // });

  // const { data: productVariants = [], refetch: getproductvariantsRefetch } = useQuery({
  //   queryKey: ['productvariants', formik.values.subcategoryid],
  //   queryFn: () => getproductvariants(formik.values.subcategoryid)
  // });

  const { data: productVariants = [], refetch: getproductvariantsRefetch } = useQuery({
    queryKey: ['productvariants', formik.values.subcategoryid],
    queryFn: getproductvariants
  });

  const { data: unitOptions } = useQuery({
    queryKey: ['productunits'],
    queryFn: getProductUnits
  });

  const createproductvariant = async () => {
    for (const [key, value] of Object.entries(variantbody)) {
      if (!value) {
        opentoast(`Enter ${key}`, 'warning', 2000);
        return; // 🔥 this will stop execution if a field is missing
      }
    }
    try {
      const response = await axios.post(`${process.env.REACT_APP_URL}/products/createproductvariant`, variantbody);
      if (response.data.status) {
        getproductvariantsRefetch();
        opentoast(`Variant Added Successfully`, 'success', 2000);
        setGroupDialog(false);
      }
      console.log('createproductvariant', response.data);
    } catch (err) {
      console.error('API error:', err);
      opentoast('Failed to add variant', 'error', 2000);
    }
  };

  return (
    <Stack>
      <form onSubmit={formik.handleSubmit} noValidate>
        <TitleCard
          title={'Add Product'}
          sx={{ top: 0, backgroundColor: 'secondary.lighter', px: 1, mb: 2 }}
          starticon={
            <Tooltip title={'Back to products'}>
              <IconButton
                variant="contained"
                color="secondary"
                sx={{ backgroundColor: 'secondary.lighter', border: '1px solid', borderColor: 'secondary.light' }}
                onClick={() => {
                  setAddDialog(false);
                }}
              >
                <ArrowLeftOutlined style={{ fontSize: 20 }} />
              </IconButton>
            </Tooltip>
          }
          secondary={
            useMediaQuery(theme.breakpoints.down('custom500')) ? (
              <Stack
                gap={3}
                sx={{
                  display: 'flex',
                  justifyContent: 'left',
                  alignItems: 'center',
                  flexDirection: 'row',
                  flexWrap: 'nowrap'
                }}
              >
                <Tooltip title="Reset the form">
                  <IconButton
                    sx={{
                      backgroundColor: 'primary.main',
                      color: 'white',
                      '&:hover': {
                        backgroundColor: 'primary.main'
                      }
                    }}
                    onClick={() => {
                      formik.resetForm();
                    }}
                  >
                    <ReloadOutlined />
                  </IconButton>
                </Tooltip>
                <Tooltip title="Create New Product">
                  <IconButton
                    type="submit"
                    sx={{
                      backgroundColor: 'primary.main',
                      color: 'white',
                      '&:hover': {
                        backgroundColor: 'primary.main'
                      }
                    }}
                  >
                    <FormOutlined />
                  </IconButton>
                </Tooltip>
              </Stack>
            ) : (
              <Stack
                gap={3}
                sx={{
                  display: 'flex',
                  justifyContent: 'left',
                  alignItems: 'center',
                  flexDirection: 'row',
                  flexWrap: 'wrap'
                }}
              >
                <Button
                  variant="outlined"
                  color="info"
                  onClick={() => {
                    formik.resetForm();
                  }}
                >
                  Reset
                </Button>
                <Button type="submit" variant="contained" sx={{ textTransform: 'none' }}>
                  Create
                </Button>
              </Stack>
            )
          }
        />

        <Grid container spacing={2} sx={{}}>
          <Grid item xs={12} sm={6} sx={{}}>
            <MainCard sx={{ height: '100%', backgroundColor: 'bg.lighter' }}>
              <Grid container spacing={1} direction="column">
                {SubCat?.length > 0 && (
                  <Grid item xs={12}>
                    <InputLabel sx={{ mb: 1 }}>Sub Category</InputLabel>
                    <Autocomplete
                      disablePortal
                      id="combo-box-category"
                      options={SubCat || []}
                      getOptionLabel={(option) => option?.subcatname || ''}
                      onChange={(event, value) => {
                        console.log('SubCat', value);
                        formik.setFieldValue('subcategoryid', +value?.subcatid || 0);
                        setvariantBody((prev) => ({
                          ...prev,
                          subcategoryid: +value?.subcatid
                        }));
                      }}
                      renderOption={(props, option) => (
                        <Box {...props} sx={{ display: 'flex', alignItems: 'center', gap: 1, width: '100%' }}>
                          <Avatar
                            src={option.image || uploadImage}
                            alt={option.subcatname}
                            variant="square"
                            sx={{ width: 24, height: 24 }}
                          />
                          <Typography variant="body1">{option.subcatname}</Typography>
                        </Box>
                      )}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          placeholder={'Select Sub Category'}
                          error={formik.touched.subcategoryid && Boolean(formik.errors.subcategoryid)}
                          helperText={formik.touched.subcategoryid && formik.errors.subcategoryid}
                        />
                      )}
                    />
                  </Grid>
                )}
                <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>Product Name</InputLabel>
                  <TextField
                    name="productname"
                    placeholder="Enter Product name"
                    fullWidth
                    value={formik.values.productname}
                    onChange={formik.handleChange}
                    error={formik.touched.productname && Boolean(formik.errors.productname)}
                    helperText={formik.touched.productname && formik.errors.productname}
                  />
                </Grid>
                <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>Product Description</InputLabel>
                  <TextField
                    name="productdesc"
                    placeholder="Enter product description"
                    fullWidth
                    multiline
                    rows={3}
                    value={formik.values.productdesc}
                    onChange={formik.handleChange}
                    error={formik.touched.productdesc && Boolean(formik.errors.productdesc)}
                    helperText={formik.touched.productdesc && formik.errors.productdesc}
                  />
                </Grid>
                <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>Product Unit</InputLabel>

                  <Autocomplete
                    disablePortal
                    id="combo-box-category"
                    options={unitOptions || []}
                    value={unitOptions?.find((option) => option.typename === formik.values.productunit) || null}
                    getOptionLabel={(option) => option?.typename || ''}
                    onChange={(event, value) => {
                      formik.setFieldValue('productunit', value?.typename || null);
                    }}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        placeholder={'Select Product Unit'}
                        error={formik.touched.productunit && Boolean(formik.errors.productunit)}
                        helperText={formik.touched.productunit && formik.errors.productunit}
                      />
                    )}
                  />
                </Grid>
                <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>Unit Value (Base Quantity)</InputLabel>
                  <TextField
                    name="unitvalue"
                    placeholder="Enter Unit Value"
                    type="number"
                    fullWidth
                    value={formik.values.unitvalue ?? ''}
                    onChange={(e) => formik.setFieldValue('unitvalue', e.target.value.toString())}
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position="end">{formik.values.productunit ? `(${formik.values.productunit})` : ''}</InputAdornment>
                      )
                    }}
                    error={formik.touched.unitvalue && Boolean(formik.errors.unitvalue)}
                    helperText={formik.touched.unitvalue && formik.errors.unitvalue}
                  />
                </Grid>
                <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>Product Cost</InputLabel>
                  <TextField
                    name="productcost"
                    type="number"
                    placeholder="Enter Product Cost"
                    fullWidth
                    value={formik.values.productcost ?? ''}
                    InputProps={{
                      endAdornment: <InputAdornment position="end">(₹)</InputAdornment>
                    }}
                    onChange={(e) => {
                      const value = e.target.value;
                      formik.setFieldValue('productcost', +value || '');
                      // ⬇️ Trigger tax calculation
                      const cost = parseFloat(value);
                      const percent = parseFloat(formik.values.taxpercent) || 0;
                      if (!isNaN(cost)) {
                        const taxAmount = (cost * percent) / 100;
                        formik.setFieldValue('taxamount', +taxAmount);
                      } else {
                        formik.setFieldValue('taxamount', 0);
                      }
                    }}
                    error={formik.touched.productcost && Boolean(formik.errors.productcost)}
                    helperText={formik.touched.productcost && formik.errors.productcost}
                  />
                </Grid>
              </Grid>
            </MainCard>
          </Grid>
          <Grid item xs={12} sm={6}>
            <MainCard sx={{ height: '100%', backgroundColor: 'bg.lighter' }}>
              <Grid container direction="column" spacing={2} sx={{ height: '100%' }}>
                <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>{`Minimun  Stock /  Quantity ( ${formik.values.productunit} )`}</InputLabel>
                  <TextField
                    name="minquandity"
                    type="number"
                    placeholder="Enter Minimun  Stock"
                    fullWidth
                    value={formik.values.quantity ?? ''}
                    InputProps={{
                      endAdornment: <InputAdornment position="end">({formik.values.productunit} )</InputAdornment>
                    }}
                    onChange={(e) => {
                      const value = e.target.value;
                      formik.setFieldValue('quantity', +value || '');
                    }}
                    error={formik.touched.quantity && Boolean(formik.errors.quantity)}
                    helperText={formik.touched.quantity && formik.errors.quantity}
                  />
                </Grid>
                <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>Tax Percent</InputLabel>
                  <TextField
                    name="taxpercent"
                    type="number"
                    placeholder="Enter Tax Percent"
                    fullWidth
                    value={formik.values.taxpercent}
                    InputProps={{
                      endAdornment: <InputAdornment position="end">(%)</InputAdornment>
                    }}
                    onFocus={() => {
                      if (formik.values.taxpercent === 0) {
                        formik.setFieldValue('taxpercent', '');
                      }
                    }}
                    onBlur={(e) => {
                      if (e.target.value === '') {
                        formik.setFieldValue('taxpercent', 0); // Reset to 0 if left empty
                      }
                    }}
                    onChange={(e) => {
                      const value = e.target.value;
                      const percent = parseFloat(value);
                      formik.setFieldValue('taxpercent', isNaN(percent) ? '' : percent);

                      const cost = parseFloat(formik.values.productcost) || 0;
                      const taxAmount = (cost * (percent || 0)) / 100;
                      formik.setFieldValue('taxamount', taxAmount);
                    }}
                    error={formik.touched.taxpercent && Boolean(formik.errors.taxpercent)}
                    helperText={formik.touched.taxpercent && formik.errors.taxpercent}
                  />
                </Grid>
                <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>Tax Amount</InputLabel>
                  <TextField
                    name="taxamount"
                    placeholder="Calculated Tax Amount"
                    fullWidth
                    value={formik.values.taxamount ?? ''}
                    InputProps={{
                      readOnly: true,
                      endAdornment: <InputAdornment position="end">(%)</InputAdornment>
                    }}
                    error={formik.touched.taxamount && Boolean(formik.errors.taxamount)}
                    helperText={formik.touched.taxamount && formik.errors.taxamount}
                  />
                </Grid>
                {/* <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>Product Stock</InputLabel>
                  <TextField
                    name="productstock"
                    type="number"
                    placeholder="Enter Product Stock"
                    fullWidth
                    value={formik.values.productstock || ''}
                    onChange={formik.handleChange}
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position="end">{formik.values.productunit ? `(${formik.values.productunit})` : ''}</InputAdornment>
                      ),
                      inputProps: { inputMode: 'numeric', pattern: '[0-9]*' },
                      sx: {
                        '& input[type=number]': {
                          MozAppearance: 'textfield'
                        },
                        '& input[type=number]::-webkit-outer-spin-button': {
                          WebkitAppearance: 'none',
                          margin: 0
                        },
                        '& input[type=number]::-webkit-inner-spin-button': {
                          WebkitAppearance: 'none',
                          margin: 0
                        }
                      }
                    }}
                    error={formik.touched.productstock && Boolean(formik.errors.productstock)}
                    helperText={formik.touched.productstock && formik.errors.productstock}
                  />
                </Grid> */}
                {/* <Grid item xs={12}> */}
                {/* <InputLabel sx={{ mb: 1 }}>Status</InputLabel> */}
                {/* <Autocomplete
                    fullWidth
                    name="productstatus"
                    options={statuss}
                    getOptionLabel={(option) => option.label || ''}
                    value={statuss.find((option) => option.value === formik.values.productstatus) || null}
                    onChange={(_, selectedOption) => {
                      formik.setFieldValue('productstatus', selectedOption?.value || '');
                    }}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        placeholder="Select Product Status"
                        error={formik.touched.productstatus && Boolean(formik.errors.productstatus)}
                        helperText={formik.touched.productstatus && formik.errors.productstatus}
                      />
                    )}
                  /> */}
                {/* <TextField
                    fullWidth
                    placeholder="Select Product Status"
                    value={formik.values.productstatus == 'available' ? 'Available' : 'OutofStcok'}
                    error={formik.touched.productstatus && Boolean(formik.errors.productstatus)}
                    helperText={formik.touched.productstatus && formik.errors.productstatus}
                  /> */}
                {/* </Grid> */}
                <Grid item xs={12}>
                  <InputLabel sx={{ mb: 1 }}>Product Image</InputLabel>
                  <Stack
                    direction="row"
                    spacing={2}
                    alignItems="center"
                    flexWrap="wrap" // ✅ allows wrapping on small screens
                    gap={3}
                    sx={{ mt: 1 }}
                  >
                    <Button
                      component="label"
                      variant="outlined"
                      color="secondary"
                      startIcon={<UploadOutlined />}
                      sx={{ mt: 1, textTransform: 'none' }}
                    >
                      Click to Upload
                      <input
                        name="productimage"
                        type="file"
                        hidden
                        accept="image/png, image/jpeg"
                        onChange={async (event) => {
                          setImgLoading(true);
                          try {
                            const s3url = await handleFileChange(event);
                            if (s3url && typeof s3url === 'string' && s3url.startsWith('http')) {
                              formik.setFieldValue('productimage', s3url);
                            } else {
                              console.error('Upload failed or invalid file.');
                            }
                          } catch (error) {
                            console.error('File upload error:', error);
                          } finally {
                            setImgLoading(false);
                          }
                        }}
                      />
                    </Button>

                    {imgloading && (
                      <Box mt={2}>
                        <CircularProgress />
                      </Box>
                    )}

                    {formik.values.productimage && (
                      <Box mt={2}>
                        <img
                          src={formik.values.productimage || uploadImage} // ✅ S3 URL
                          alt="Uploaded preview"
                          style={{ maxWidth: '100px', borderRadius: 4 }}
                        />
                      </Box>
                    )}
                    {formik.touched.productimage && formik.errors.productimage && (
                      <FormHelperText error sx={{ ml: 1 }}>
                        {formik.errors.productimage}
                      </FormHelperText>
                    )}
                  </Stack>
                </Grid>
                <Grid item xs={12} sx={{ mt: '7px' }}>
                  <InputLabel sx={{ mb: 1 }}>Product Variants (Optional)</InputLabel>
                  <Autocomplete
                    disablePortal
                    id="combo-box-category"
                    options={formik.values.subcategoryid ? productVariants ?? [] : []}
                    getOptionLabel={(option) => option?.variantname || ''}
                    onChange={(event, value) => {
                      console.log('productVariants', value);
                      formik.setFieldValue('variants', +value?.variantid || 0);
                      formik.setFieldValue('variantname', value?.variantname);
                    }}
                    noOptionsText={
                      <Typography color={'error'}>
                        {!formik.values.subcategoryid ? 'Select Subcategory to view variants' : 'No variants available'}{' '}
                      </Typography>
                    }
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        placeholder={'Select Group'}
                        error={formik.touched.variants && Boolean(formik.errors.variants)}
                        helperText="*Select a variant with the same category as the product. If no variant exists, create one first."
                        onFocus={() => {
                          if (!formik.values.subcategoryid) {
                            OpenToast('Select Sub Category to Select the  Variants', 'warning', 2500);
                          }
                        }}
                        InputProps={{
                          ...params.InputProps,
                          endAdornment: (
                            <Stack sx={{ backgroundColor: '' }}>
                              {params.InputProps.endAdornment}
                              <Tooltip title="Create New variant" placement="top">
                                <IconButton
                                  disabled={!formik.values.subcategoryid}
                                  onClick={() => {
                                    setGroupDialog(true);
                                  }}
                                >
                                  <AddIcon style={{}} />
                                  {params.InputProps.startAdornment}
                                </IconButton>
                              </Tooltip>
                            </Stack>
                          )
                        }}
                      />
                    )}
                  />
                </Grid>
              </Grid>
            </MainCard>
          </Grid>
        </Grid>
      </form>
      <Dialog open={groupDialog} fullWidth maxWidth="sm">
        <DialogTitle>Add Variant</DialogTitle>
        <DialogContent dividers>
          <Grid container spacing={2}>
            {/* <Grid item xs={12} sm={6}>
              <InputLabel sx={{ mb: 1 }}>Sub Category</InputLabel>
              <Autocomplete
                disablePortal
                id="combo-box-category"
                options={SubCat || []}
                getOptionLabel={(option) => option?.subcatname || ''}
                onChange={(event, value) => {
                  setvariantBody({ ...variantbody, subcategoryid: value.subcatid });
                }}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    placeholder="Select Sub Category"
                    fullWidth
                    helperText="* Select same category as product you need to add"
                  />
                )}
              />
            </Grid> */}

            <Grid item xs={12} sm={12}>
              <InputLabel sx={{ mb: 1 }}>Variant Name</InputLabel>
              <TextField
                name="variantname"
                placeholder="Enter Variant Name"
                fullWidth
                onChange={(e) => {
                  setvariantBody({ ...variantbody, variantname: e.target.value });
                }}
              />
            </Grid>
          </Grid>
        </DialogContent>

        <DialogActions sx={{ px: 3, py: 2 }}>
          <Button
            variant="outlined"
            color="secondary"
            onClick={() => {
              setGroupDialog(false);
              setvariantBody({ ...variantbody, subcategoryid: 0, variantname: '' });
            }}
          >
            Cancel
          </Button>
          <Button variant="contained" color="primary" onClick={createproductvariant}>
            Create
          </Button>
        </DialogActions>
      </Dialog>
    </Stack>
  );
};

export default Addproducts;
