import { Fragment, useState, useRef, useEffect } from 'react';

// material-ui
import {
  // styled,
  useTheme
} from '@mui/material/styles';
import {
  Box,
  Grid,
  Card,
  CardMedia,
  CardContent,
  Typography,
  IconButton,
  Stack,
  Switch,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  InputLabel,
  TextField,
  Autocomplete,
  TableContainer,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
  TablePagination,
  Avatar,
  Divider
} from '@mui/material';
import { useFormik } from 'formik';
import * as yup from 'yup';
import {
  // getproductcategories,
  getproductsubcategories,
  getProductUnits,
  getallproducts,
  productsDelete,
  productsUpdate,
  getallinfiniteproducts
} from './api';

import { enqueueSnackbar } from 'notistack';

// project import

import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

import { CloseOutlined, DeleteFilled, EditOutlined, UploadOutlined } from '@ant-design/icons';
import MainCard from 'components/MainCard';
import CircularLoader from 'components/third-party/CircularLoader';
import { useCallback } from 'react';
import { handleFileChange } from 'components/third-party/s3img';
import ProductEmpty from './ProductEmpty';
const statuss = [
  { value: 'available', label: 'Available' },
  { value: 'outofstock', label: 'Out of Stock' }
];

const validationSchema = yup.object({
  applocationid: yup.number().required('Please select location '),
  categoryid: yup.number().required('Please select a  category '),
  subcategoryid: yup
    .number()
    .nullable()
    .test('required', 'Please select subcategory', (value) => {
      return value !== null && value !== undefined; // The .test() explicitly accepts 0, and only fails if the value is null or undefined.
    }),
  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
    .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'),
  // productstock: yup    {product.productname}
  //   .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'),

  approve: yup.number().required('  is required'),
  productstatus: yup.string().required('Product Status  is required'),
  productimage: yup.string().required('Product Image  is required')
});

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

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

const ProductsView = ({ selectedCat, view, productCount, debouncedSearchword }) => {
  const theme = useTheme();
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editDialog, setEditDialog] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState({});
  const observerRef = useRef(null);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0); // reset to first page
  };

  const useDeleteProduct = () => {
    const queryClient = useQueryClient();

    return useMutation({
      mutationFn: productsDelete,
      onSuccess: () => {
        queryClient.invalidateQueries(['productlist']); // Refresh the list
        opentoast('Product Deleted Succesfully', 'success', 1000);
      },
      onError: (error) => {
        console.error('Delete failed:', error);
        opentoast(error.message, 'error', 1000);
      }
    });
  };
  const { mutate: deleteProduct, isLoading: deleteLoading } = useDeleteProduct();

  const handleDelete = (productid) => {
    deleteProduct({ productid });
  };

  const useUpdateProductStatus = () => {
    const queryClient = useQueryClient();
    return useMutation({
      mutationFn: productsUpdate,
      onSuccess: () => {
        queryClient.invalidateQueries(['productlist']); // // Refresh the list
        opentoast('Product Updated Succesfully', 'success', 1000);
      },
      onError: (error) => {
        console.error('Update failed:', error);
        opentoast(error.message, 'error', 1000);
      }
    });
  };

  const { mutate: updateProductStatus, isLoading: updateLoading } = useUpdateProductStatus();

  const handleStatusChange = (props) => {
    updateProductStatus(props);
    setEditDialog(false);
  };

  const formik = useFormik({
    initialValues: {},
    validationSchema,
    onSubmit: handleStatusChange
  });

  const { data: productList, isLoading: productlistloading } = useQuery({
    queryKey: ['productlist', selectedCat, page, rowsPerPage, debouncedSearchword],
    queryFn: () => getallproducts(selectedCat?.subcatid || 0, page, rowsPerPage, debouncedSearchword)
  });

  useEffect(() => {
    console.log('productList', productList);
  }, [productList]);

  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
    queryKey: ['infiniteproductList', selectedCat, rowsPerPage, debouncedSearchword],
    queryFn: ({ pageParam = 0 }) =>
      getallinfiniteproducts({
        pageParam,
        subcatid: selectedCat?.subcatid || 0,
        rowsPerPage,
        search: debouncedSearchword
      }),
    getNextPageParam: (lastPage, allPages) => (lastPage.length > 0 ? allPages.length : undefined)
  });

  const products = data?.pages.flat() || [];

  const lastProductRef = useCallback(
    (node) => {
      if (isFetchingNextPage) return;
      if (observerRef.current) observerRef.current.disconnect();
      observerRef.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasNextPage) {
          fetchNextPage();
        }
      });
      if (node) observerRef.current.observe(node);
    },
    [isFetchingNextPage, hasNextPage, fetchNextPage]
  );

  const { data: SubCat, isLoading: subcatloading } = useQuery({
    queryKey: ['productsubcategory'],
    queryFn: () => getproductsubcategories(selectedCat)
  });

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

  return (
    <Fragment>
      {(productlistloading || subcatloading || deleteLoading || updateLoading) && <CircularLoader />}

      {products?.length <= 0 ? (
        <ProductEmpty />
      ) : (
        <>
          {view === 'card' ? (
            <Stack sx={{ mt: 1 }}>
              <Grid container spacing={{ xs: 1, sm: 2, md: 3 }}>
                {products?.map((product, index) => {
                  const isLast = products.length === index + 1;
                  return (
                    <Grid
                      ref={isLast ? lastProductRef : null}
                      item
                      xs={12}
                      custom450={6}
                      custom650={4}
                      custom900={3}
                      custom1100={2.4}
                      key={index}
                      sx={{ height: 370 }}
                    >
                      <Card
                        elevation={0}
                        sx={{
                          height: '100%',
                          display: 'flex',
                          flexDirection: 'column',
                          border: `1px solid ${theme.palette.border.light}`,
                          overflow: 'hidden',
                          // cursor: 'pointer',
                          transition: 'all 0.3s ease'
                        }}
                      >
                        <CardMedia
                          component="img"
                          image={product.productimage}
                          alt={product.productname}
                          sx={{
                            minHeight: '200px',
                            maxHeight: '200px',
                            width: '100%',
                            objectFit: 'cover',
                            filter: product.approve === 0 ? 'grayscale(100%) brightness(0.8)' : 'none',
                            transition: 'filter 0.3s ease',
                            p: 2
                          }}
                        />
                        <Divider />
                        <CardContent>
                          <Stack spacing={1}>
                            <Typography
                              component="span"
                              sx={{
                                fontWeight: 600,
                                lineHeight: 1.2,
                                fontSize: { xs: 14, sm: 16, md: 18, lg: 20 },
                                whiteSpace: 'nowrap',
                                overflow: 'scroll'
                              }}
                            >
                              {product.productname}
                              <Typography component={'span'} variant="body2" color={'secondary'}>
                                {` ( ${product.productid} ) `}
                              </Typography>
                            </Typography>

                            <Typography component="span" sx={{ color: 'text.secondary', fontSize: 14 }}>
                              ₹{product.productcost} / {product.unitvalue}
                              {product.productunit}
                            </Typography>
                          </Stack>

                          <Stack
                            sx={{ width: '100%', mt: 2 }}
                            direction={'row'}
                            alignItems={'center'}
                            justifyContent={'space-between'}
                            spacing={3}
                          >
                            <Stack direction={'row'} alignItems={'center'} spacing={2}>
                              <IconButton
                                color="primary"
                                sx={{ backgroundColor: 'bg.light' }}
                                onClick={() => {
                                  setEditDialog(true);
                                  formik.resetForm({
                                    values: {
                                      ...formik.initialValues,
                                      ...product
                                    }
                                  });
                                }}
                              >
                                <EditOutlined />
                              </IconButton>
                              <IconButton
                                color="error"
                                sx={{ backgroundColor: 'bg.light' }}
                                onClick={() => {
                                  setSelectedProduct(product);
                                  setDialogOpen(true);
                                }}
                              >
                                <DeleteFilled />
                              </IconButton>
                            </Stack>
                            <Switch
                              checked={product.approve === 1}
                              onChange={() =>
                                handleStatusChange({
                                  productid: product.productid,
                                  approve: product.approve == 1 ? 0 : 1
                                })
                              }
                            />
                          </Stack>
                        </CardContent>
                      </Card>
                    </Grid>
                  );
                })}
                {isFetchingNextPage && <p>Loading more...</p>}
              </Grid>
            </Stack>
          ) : (
            <Box sx={{ border: `1px  solid ${theme.palette.bg.main}` }}>
              <TableContainer
                sx={{
                  borderBottom: `1px  solid ${theme.palette.bg.main}`
                }}
              >
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>S.No</TableCell>
                      <TableCell>Product Details</TableCell>
                      <TableCell>Categories</TableCell>
                      <TableCell>Rate</TableCell>
                      <TableCell>Stock</TableCell>
                      <TableCell>Status</TableCell>
                      <TableCell align="right">Actions</TableCell>
                    </TableRow>
                  </TableHead>

                  <TableBody>
                    {productList?.map((product, index) => (
                      <TableRow key={index}>
                        <TableCell> {page * rowsPerPage + index + 1} </TableCell>
                        <TableCell>
                          <Stack direction="row" spacing={1.5} alignItems="center">
                            <Avatar
                              variant="rounded"
                              alt={product?.productname}
                              color="secondary"
                              src={product?.productimage}
                              sx={{ filter: product.approve === 0 ? 'grayscale(100%) brightness(0.8)' : 'none' }}
                            />
                            <Stack spacing={0}>
                              <Typography>{product?.productname}</Typography>
                              <Typography variant="caption" color="textSecondary">
                                {product?.productdesc}
                              </Typography>
                            </Stack>
                          </Stack>
                        </TableCell>
                        <TableCell>
                          <Typography>{product?.Subcategoryname}</Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="body1">
                            ₹{product?.productcost}{' '}
                            <Typography
                              component="span"
                              variant="body2"
                              // color="text.secondary"
                            >
                              / {product?.unitvalue}
                              {product?.productunit}
                            </Typography>
                          </Typography>
                        </TableCell>
                        <TableCell> {`${product?.productstock}(${product?.productunit})`} </TableCell>
                        <TableCell>
                          {product?.productstatus ? product.productstatus.charAt(0).toUpperCase() + product.productstatus.slice(1) : ''}
                        </TableCell>{' '}
                        <TableCell align="right">
                          <Stack display={'flex'} flexDirection={'row'} justifyContent={'end'} spacing={1} alignItems="flex-end">
                            <Switch
                              size="small"
                              checked={product.approve === 1}
                              onChange={() =>
                                handleStatusChange({
                                  productid: product.productid,
                                  approve: product.approve === 1 ? 0 : 1
                                })
                              }
                            />
                            <Stack
                              spacing={1}
                              alignItems="flex-end"
                              sx={{
                                flexDirection: 'row',
                                display: 'flex'
                              }}
                            >
                              <IconButton
                                color="primary"
                                onClick={() => {
                                  console.log('editproduct', product);

                                  setEditDialog(true);
                                  formik.resetForm({
                                    values: {
                                      ...formik.initialValues,
                                      productid: product.productid,
                                      applocationid: product.applocationid,
                                      categoryid: product.categoryid,
                                      subcategoryid: product.subcategoryid,
                                      productname: product.productname,
                                      productdesc: product.productdesc,
                                      productunit: product.productunit,
                                      unitvalue: product.unitvalue,
                                      productcost: product.productcost,
                                      taxamount: product.taxamount,
                                      taxpercent: product.taxpercent,
                                      producttax: product.producttax,
                                      productstock: product.productstock,
                                      approve: product.productstock,
                                      productstatus: product.productstatus,
                                      productimage: product.productimage
                                    }
                                  });
                                }}
                              >
                                <EditOutlined />
                              </IconButton>
                              <IconButton
                                color="error"
                                onClick={() => {
                                  setSelectedProduct(product);
                                  setDialogOpen(true);
                                }}
                              >
                                <DeleteFilled />
                              </IconButton>
                            </Stack>
                          </Stack>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
              {productList && (
                <TablePagination
                  sx={{ position: 'sticky', bottom: 0, zIndex: 10, backgroundColor: 'border.lighter' }}
                  component="div"
                  count={productCount?.total || 0}
                  page={page}
                  onPageChange={handleChangePage}
                  rowsPerPage={rowsPerPage}
                  onRowsPerPageChange={handleChangeRowsPerPage}
                  rowsPerPageOptions={[5, 10, 25, 50]}
                  labelRowsPerPage="Rows per page"
                />
              )}
            </Box>
          )}
        </>
      )}
      {/* ========================= || Delete product Dialog ========================= || */}

      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle sx={{ backgroundColor: theme.palette.error.light }}>
          <Stack direction="row" justifyContent="space-between" alignItems="center">
            {/* Left side - Title with Icon */}
            <Stack direction="row" alignItems="center" spacing={1}>
              <DeleteFilled style={{ color: '#d32f2f' }} />
              <Typography variant="h4">Delete Product</Typography>
            </Stack>

            {/* Right side - Close Button */}
            <IconButton onClick={() => setDialogOpen(false)} size="small">
              <CloseOutlined />
            </IconButton>
          </Stack>
        </DialogTitle>

        {/* ✅ Only handle delete here */}
        <form
          onSubmit={(e) => {
            e.preventDefault();
            handleDelete(selectedProduct.productid);
            setDialogOpen(false);
          }}
        >
          <DialogContent>
            <Typography variant="h5" sx={{ mt: 1 }}>
              Are you sure you want to delete this product? This action cannot be undone.
            </Typography>
          </DialogContent>

          <DialogActions>
            <Button variant="outlined" onClick={() => setDialogOpen(false)}>
              Cancel
            </Button>

            {/* ✅ Remove onClick, keep type="submit" */}
            <Button type="submit" variant="contained" color="error" autoFocus>
              Delete
            </Button>
          </DialogActions>
        </form>
      </Dialog>

      {/* ========================= || edit product Dialog ========================= || */}
      <Dialog open={editDialog} fullWidth scroll="paper" maxWidth="xl">
        <DialogTitle sx={{ backgroundColor: theme.palette.primary.main, color: 'white' }}>
          <Stack direction="row" justifyContent="space-between" alignItems="center">
            {/* Left side - Title with Icon */}
            <Stack direction="row" alignItems="center" spacing={1}>
              <EditOutlined />
              <Typography variant="h4">Edit Product</Typography>
            </Stack>
            <IconButton sx={{ color: 'white' }} onClick={() => setEditDialog(false)}>
              <CloseOutlined />
            </IconButton>
          </Stack>
        </DialogTitle>

        <form onSubmit={formik.handleSubmit} noValidate>
          <DialogContent sx={{ overflow: 'scroll' }}>
            <MainCard
              sx={{ overflow: 'scroll' }}
              title={
                <Grid container spacing={3}>
                  {SubCat?.length > 0 && (
                    <Grid item xs={12} sm={12}>
                      <InputLabel sx={{ mb: 1 }}>Sub Category</InputLabel>
                      <Autocomplete
                        disablePortal
                        id="combo-box-category"
                        options={SubCat || []}
                        value={SubCat?.find((loc) => loc.subcatid === formik.values.subcategoryid) || null}
                        getOptionLabel={(option) => option?.subcatname || ''}
                        onChange={(event, value) => {
                          formik.setFieldValue('subcategoryid', +value?.subcatid || null);
                        }}
                        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>
              }
            >
              <Grid container spacing={2} sx={{}}>
                <Grid item xs={12} sm={4} sx={{}}>
                  <MainCard>
                    <Grid container spacing={1} direction="column">
                      <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</InputLabel>
                        <TextField
                          name="unitvalue"
                          placeholder="Enter Unit Value"
                          fullWidth
                          value={formik.values.unitvalue ?? ''}
                          onChange={formik.handleChange}
                          error={formik.touched.unitvalue && Boolean(formik.errors.unitvalue)}
                          helperText={formik.touched.unitvalue && formik.errors.unitvalue}
                        />
                      </Grid>
                    </Grid>
                  </MainCard>
                </Grid>
                <Grid item xs={12} sm={4} sx={{}}>
                  <MainCard>
                    <Grid container direction="column" spacing={2}>
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Product Cost</InputLabel>
                        <TextField
                          name="productcost"
                          type="number"
                          placeholder="Enter Unit Value"
                          fullWidth
                          value={formik.values.productcost ?? ''}
                          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 item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Tax Percent</InputLabel>
                        <TextField
                          name="taxpercent"
                          type="number"
                          placeholder="Enter Tax Percent"
                          fullWidth
                          value={formik.values.taxpercent ?? ''}
                          onChange={(e) => {
                            const value = e.target.value;
                            formik.setFieldValue('taxpercent', +value);

                            // ⬇️ Trigger tax calculation
                            const cost = parseFloat(formik.values.productcost) || 0;
                            const percent = parseFloat(value) || 0;
                            const taxAmount = (cost * percent) / 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
                          }}
                          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}
                          error={formik.touched.productstock && Boolean(formik.errors.productstock)}
                          helperText={formik.touched.productstock && formik.errors.productstock}
                        />
                      </Grid>
                    </Grid>
                  </MainCard>
                </Grid>
                <Grid item xs={12} sm={4} sx={{}}>
                  <MainCard>
                    <Grid container direction="column" spacing={2}>
                      <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}
                            />
                          )}
                        />
                      </Grid>

                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Product Image</InputLabel>

                        <Button
                          component="label"
                          variant="outlined"
                          color="secondary"
                          startIcon={<UploadOutlined />}
                          sx={{ mt: 1, textTransform: 'none' }}
                        >
                          Image Change
                          <input
                            name="productimage"
                            type="file"
                            hidden
                            accept="image/png, image/jpeg"
                            onChange={async (event) => {
                              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.');
                              }
                            }}
                          />
                        </Button>

                        {formik.touched.productimage && formik.errors.productimage && (
                          <Typography color="error" sx={{ mt: 1 }}>
                            {formik.errors.productimage}
                          </Typography>
                        )}

                        {formik.values.productimage && (
                          <Box mt={2}>
                            <img
                              src={formik.values.productimage} // ✅ S3 URL
                              alt="Uploaded preview"
                              style={{ width: '100px', borderRadius: 4 }}
                            />
                          </Box>
                        )}
                      </Grid>
                    </Grid>
                  </MainCard>
                </Grid>
              </Grid>
            </MainCard>
          </DialogContent>

          <DialogActions
            sx={{
              position: 'sticky', // ✅ Keep fixed at the bottom of scroll container
              bottom: 0,
              backgroundColor: 'background.paper',
              zIndex: 1
            }}
          >
            <Button
              variant="outlined"
              color="secondary"
              onClick={() => {
                setEditDialog(false);
              }}
            >
              Cancel
            </Button>
            <Button type="submit" variant="contained" sx={{ textTransform: 'none', mr: 4 }}>
              Edit Product
            </Button>
          </DialogActions>
        </form>
      </Dialog>
    </Fragment>
  );
};

export default ProductsView;
