import React, { useRef, Fragment, useEffect, useState } from 'react';
import { useTheme } from '@mui/material/styles';
import {
  Typography,
  Chip,
  IconButton,
  Stack,
  Button,
  TextField,
  TableContainer,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
  Avatar,
  Box,
  Paper,
  Divider,
  useMediaQuery,
  Slide,
  FormControl,
  FormControlLabel,
  OutlinedInput,
  InputAdornment,
  Drawer,
  FormGroup,
  Checkbox,
  Skeleton,
  TablePagination
} from '@mui/material';
import { useFormik } from 'formik';
import * as yup from 'yup';
import {
  fetchAppLocations,
  getproductsubcategories,
  getProductUnits,
  productsDelete,
  productsUpdate,
  getcatalougeproducts
} from 'pages/nearle/api/api';
import { enqueueSnackbar } from 'notistack';
import FilterAltOutlinedIcon from '@mui/icons-material/FilterAltOutlined';
import { useDebounce } from 'use-debounce';
import { Add, DeleteOutlineOutlined, Remove } from '@mui/icons-material';
import ClearIcon from '@mui/icons-material/Clear';
import ProductEmpty from 'sections/apps/e-commerce/products/ProductEmpty';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { PlusCircleOutlined, SearchOutlined } from '@ant-design/icons';
import MainCard from 'components/MainCard';
import CircularLoader from 'components/nearle_components/CircularLoader';
import { useNavigate } from 'react-router';
import FloatingCart from 'components/cards/e-commerce/FloatingCart';
import OpenToast from 'components/nearle_components/OpenToast';
import axios from 'axios';
import { useSelector } from 'react-redux';

const ProductCardView = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const textFieldRef = useRef(null);
  const isMobile = useMediaQuery(theme.breakpoints.down('sm')); // true if screen < 600px
  const [search, setSearch] = useState('');
  const [debouncedSearchword] = useDebounce(search, 700); // ⏱️ Debounce for 500ms
  const [drawerOpen, setDrawerOpen] = useState(true);
  const [selectedSubCat, setSelectedSubCat] = useState('');
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  const [stockProducts, setStockProducts] = useState([]);
  const [cartDrawer, setCartDrawer] = useState(false);
  const userdata = useSelector((state) => state.userinfo.userdata);

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

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  useEffect(() => {
    console.log('stockProducts', stockProducts);
    if (stockProducts.length == 0) {
      setCartDrawer(false);
    }
  }, [stockProducts]);

  const isBelow1000 = useMediaQuery('(max-width:1000px)');

  useEffect(() => {
    if (isBelow1000) {
      setDrawerOpen(false);
    } else {
      setDrawerOpen(true);
    }
  }, [isBelow1000]);

  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
      .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 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 { data: SubCat, isLoading: subcatloading } = useQuery({
    queryKey: ['productsubcategory'],
    queryFn: () => getproductsubcategories()
  });
  useEffect(() => {
    console.log('getproductsubcategories', SubCat);
  }, [SubCat]);

  const { data: productList, isLoading: productlistloading } = useQuery({
    queryKey: ['productlist', selectedSubCat, page, rowsPerPage, debouncedSearchword],
    queryFn: () => getcatalougeproducts(selectedSubCat || 0, page, rowsPerPage, debouncedSearchword)
  });
  useEffect(() => {
    console.log('productList', productList);
  }, [productList]);

  const createproductlocation = async () => {
    let postStock = stockProducts.map((item) => ({
      tenantid: userdata?.tenantid,
      stocktype: 'IN',
      locationid: userdata?.locationid,
      productid: item.productid,
      quantity: item.quantity,
      status: 'Active'
    }));
    console.log('postStock', postStock);

    try {
      let response = await axios.post(`${process.env.REACT_APP_URL2}/products/createproductlocation`, postStock);
      if (response.data.status) {
        OpenToast(response.data.message, 'success', 2000);
        navigate('/products');
      }
    } catch (err) {
      OpenToast(err.message, 'error', 2000);
    }
  };

  return (
    <>
      {subcatloading && <CircularLoader />}
      <Stack sx={{ display: 'flex', position: 'relative', mt: 2, BorderColor: 'none', minHeight: 'auto' }}>
        {/* // ==============================||  Floating cart ||============================== // */}
        {stockProducts.length > 0 && <FloatingCart count={stockProducts?.length} onClick={() => setCartDrawer(true)} />}
        <Stack>
          {/* // ==============================||  Slide drawer ||============================== // */}
          <Slide direction="right" in={drawerOpen} mountOnEnter unmountOnExit timeout={300} style={{}}>
            <Box
              sx={{
                position: isMobile ? 'fixed' : 'absolute',
                top: isMobile ? 64 : 0,
                left: 0,
                zIndex: isMobile && 1000000,
                backgroundColor: 'white',
                border: '1px solid',
                borderColor: 'border.light'
              }}
            >
              <Stack sx={{ position: 'sticky', top: 0, zIndex: 1, p: 3.5 }}>
                <Typography variant="h4" sx={{}}>
                  Category
                </Typography>
              </Stack>
              <Divider sx={{ mt: -2 }} />
              <Paper
                elevation={0}
                sx={{
                  width: 260,
                  height: isMobile ? '100vh' : 'auto',
                  maxHeight: isMobile ? '100vh' : 'calc(100vh - 260px)',
                  overflowY: 'scroll',
                  position: 'relative'
                }}
              >
                <Box sx={{ pl: 2, pt: 1 }}>
                  {subcatloading ? (
                    <Stack spacing={2}>
                      {[...Array(10)].map((_, index) => (
                        <Skeleton key={index} variant="rectangular" height={20} sx={{ fontSize: '1rem' }} />
                      ))}
                    </Stack>
                  ) : (
                    <FormControl component="fieldset" sx={{ width: '100%' }}>
                      <FormGroup>
                        {SubCat?.map((category) => (
                          <FormControlLabel
                            key={category.subcatid}
                            control={
                              <Checkbox
                                size="small"
                                checked={selectedSubCat === category.subcatid.toString()}
                                onChange={() => {
                                  setSelectedSubCat((prev) => (prev === category.subcatid.toString() ? '' : category.subcatid.toString()));
                                }}
                              />
                            }
                            label={category.subcatname}
                            sx={{
                              mb: 1.5,
                              alignItems: 'center',
                              '.MuiFormControlLabel-label': {
                                fontSize: '15px',
                                fontWeight: 500,
                                color: 'text.primary',
                                lineHeight: 1.5
                              }
                            }}
                          />
                        ))}
                      </FormGroup>
                    </FormControl>
                  )}
                </Box>
              </Paper>
            </Box>
          </Slide>
          <Box
            flex={1}
            sx={{
              ml: !isMobile && drawerOpen ? '280px' : 0,
              transition: 'margin-left 0.3s ease',
              border: 'none'
            }}
          >
            {/* // ==============================||  Product header content ||============================== // */}
            <Stack
              sx={{
                width: '100%',
                backgroundColor: 'white',
                mb: 2,
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                p: 2.5,
                border: '1px solid',
                borderColor: 'border.light'
              }}
            >
              <Chip
                label="Filters"
                icon={<FilterAltOutlinedIcon sx={{ color: 'red' }} />}
                sx={{
                  backgroundColor: 'transparent',
                  border: 'none',
                  transition: 'all 0.3s ease-in-out',

                  '&:hover': {
                    backgroundColor: 'bg.light',
                    transform: 'scale(1.03)'
                  }
                }}
                onClick={() => setDrawerOpen((prev) => !prev)}
              />

              <OutlinedInput
                inputRef={textFieldRef}
                id="input-search-header"
                placeholder="Search (ctrl+k)"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                sx={{ flex: 1, maxWidth: { xs: '100%', custom500: 300 } }}
                startAdornment={
                  <InputAdornment position="start">
                    <SearchOutlined style={{ fontSize: 'medium', fontWeight: 'bold' }} />
                  </InputAdornment>
                }
                endAdornment={
                  <IconButton sx={{ visibility: search ? 'visible' : 'hidden' }} onClick={() => setSearch('')}>
                    <ClearIcon style={{ fontSize: 'medium', color: '#65387A' }} />
                  </IconButton>
                }
              />
            </Stack>
            {/* // ==============================||  Product Table  view ||============================== // */}

            {productList?.length == 0 || !productList ? (
              <Stack sx={{ height: '100%' }}>
                <ProductEmpty sx={{ border: 'none' }} />
              </Stack>
            ) : (
              <MainCard sx={{}} contentSX={{ p: 0 }}>
                <TableContainer>
                  <Table>
                    <TableHead>
                      <TableRow>
                        <TableCell>
                          <Checkbox
                            color="primary"
                            // Checked if all products are selected
                            checked={stockProducts.length > 0 && stockProducts.length === productList.length}
                            // Indeterminate when some but not all are selected
                            indeterminate={stockProducts.length > 0 && stockProducts.length < productList.length}
                            onChange={(e) => {
                              if (e.target.checked) {
                                // Select all
                                setStockProducts(productList);
                              } else {
                                // Deselect all
                                setStockProducts([]);
                              }
                            }}
                          />
                        </TableCell>
                        <TableCell>S.No</TableCell>
                        <TableCell>Product Description</TableCell>
                        <TableCell>Rate</TableCell>
                        <TableCell>MinStock</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {productList?.map((product, index) => (
                        <TableRow key={index}>
                          <TableCell>
                            <Checkbox
                              color="primary"
                              checked={stockProducts.some((p) => p?.productid === product?.productid)}
                              onChange={(e) => {
                                if (e.target.checked) {
                                  setStockProducts([...stockProducts, product]);
                                } else {
                                  setStockProducts(stockProducts.filter((p) => p.productid != product.productid));
                                }
                              }}
                            />
                          </TableCell>
                          <TableCell>{index + 1}</TableCell>
                          <TableCell>
                            <Stack direction="row" spacing={1.5} alignItems="center" sx={{ whiteSpace: 'nowrap' }}>
                              <Avatar
                                variant="rounded"
                                alt={product?.productname}
                                color="secondary"
                                size="sm"
                                src={product?.productimage}
                              />
                              <Stack spacing={0}>
                                <Typography>{product?.productname}</Typography>
                                <Typography variant="caption" color="textSecondary">
                                  {` ID : ${product?.productid}`}
                                </Typography>
                              </Stack>{' '}
                            </Stack>
                          </TableCell>
                          <TableCell sx={{ whiteSpace: 'nowrap' }}>
                            <Typography variant="body1">
                              ₹{product?.productcost}{' '}
                              <Typography component="span" variant="body1" color="text.secondary">
                                / {product?.unitvalue}
                                <Typography component="span" variant="body1">
                                  {product?.productunit}
                                </Typography>
                              </Typography>
                            </Typography>
                          </TableCell>
                          <TableCell sx={{ whiteSpace: 'nowrap' }}>
                            <Typography variant="body1">
                              {product?.quantity}{' '}
                              <Typography component="span" variant="body1" color="text.secondary">
                                {`(${product?.productunit})`}
                              </Typography>{' '}
                            </Typography>{' '}
                          </TableCell>

                          {/* <TableCell>
                        <Tooltip title={'Clear Stock'} placement="right">
                          <IconButton
                            color="error"
                            onClick={() => {
                              setClearStockDialog(true);
                              setSelectedStock(product);
                            }}
                          >
                            <CancelOutlinedIcon />
                          </IconButton>
                        </Tooltip>
                      </TableCell> */}
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </TableContainer>
                {!search && (
                  <TablePagination
                    rowsPerPageOptions={[5, 10, 25, 50, 100]}
                    component="div"
                    count={'100'}
                    rowsPerPage={rowsPerPage}
                    page={page}
                    onPageChange={handleChangePage}
                    onRowsPerPageChange={handleChangeRowsPerPage}
                  />
                )}
              </MainCard>
            )}
          </Box>
        </Stack>
        {/* // ==============================||  cart drawer ||============================== // */}
        <Drawer anchor={'right'} open={cartDrawer} onClose={() => setCartDrawer(false)}>
          <Box sx={{ width: 'auto', minWidth: '300px' }}>
            <MainCard
              sx={{ m: 1 }}
              contentSX={{ p: 0 }}
              title={
                <Stack display={'flex'} flexDirection={'row'} alignItems={'center'} justifyContent={'space-between'}>
                  <Typography variant="h5">Products List</Typography>
                  <Button
                    variant="contained"
                    color="primary"
                    endIcon={<PlusCircleOutlined />}
                    onClick={() => {
                      createproductlocation();
                      console.log('Stocks list', stockProducts);
                    }}
                  >
                    Import
                  </Button>
                </Stack>
              }
            >
              <TableContainer sx={{ maxHeight: 'calc(100vh - 250px' }}>
                <Table stickyHeader>
                  <TableHead>
                    <TableRow>
                      <TableCell sx={{ position: 'sticky !important' }}>S.No</TableCell>
                      <TableCell sx={{ position: 'sticky !important' }}>Product Description </TableCell>
                      <TableCell sx={{ position: 'sticky !important' }} align="right">
                        Rate
                      </TableCell>
                      <TableCell sx={{ position: 'sticky !important' }} align="center">
                        Stock
                      </TableCell>
                      <TableCell sx={{ position: 'sticky !important' }} align="center">
                        Actions
                      </TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {stockProducts?.map((product, index) => (
                      <TableRow key={index}>
                        <TableCell>{index + 1}</TableCell>
                        <TableCell>
                          <Stack direction="row" spacing={1.5} alignItems="center">
                            <Avatar variant="rounded" alt={product?.productname} color="secondary" size="sm" src={product?.productimage} />
                            <Stack spacing={0}>
                              <Typography>{product?.productname}</Typography>
                              <Typography variant="caption" color="textSecondary">
                                {product?.productdesc}
                              </Typography>
                            </Stack>
                          </Stack>
                        </TableCell>
                        <TableCell align="right">
                          <Typography variant="h5">
                            ₹{product?.productcost}{' '}
                            <Typography component="span" variant="h6">
                              / {product?.unitvalue}
                              {product?.productunit}
                            </Typography>
                          </Typography>
                        </TableCell>
                        <TableCell align="center">
                          {' '}
                          <Box display="flex" alignItems="center" gap={1}>
                            <IconButton
                              color="error"
                              onClick={() => {
                                setStockProducts((prev) =>
                                  prev.map((p) => (p.productid === product.productid ? { ...p, quantity: Math.max(p.quantity - 1, 0) } : p))
                                );
                              }}
                            >
                              <Remove />
                            </IconButton>

                            {/* Editable Text Field */}
                            <TextField
                              type="number"
                              placeholder={0}
                              value={product.quantity || ''}
                              onChange={(e) => {
                                const newStock = parseInt(e.target.value || '0');
                                setStockProducts((prev) =>
                                  prev.map((p) => (p.productid === product.productid ? { ...p, quantity: newStock } : p))
                                );
                              }}
                              sx={{
                                width: 120,
                                '& input': {
                                  textAlign: 'center'
                                }
                              }}
                            />

                            {/* Increase Button */}
                            <IconButton
                              color="success"
                              onClick={() => {
                                setStockProducts((prev) =>
                                  prev.map((p) => (p.productid === product.productid ? { ...p, quantity: p.quantity + 1 } : p))
                                );
                              }}
                            >
                              <Add />
                            </IconButton>
                          </Box>
                        </TableCell>
                        <TableCell>
                          <IconButton
                            color="error"
                            onClick={() => {
                              setStockProducts(stockProducts.filter((p) => p.productid !== product.productid));
                            }}
                          >
                            <DeleteOutlineOutlined />
                          </IconButton>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            </MainCard>
          </Box>
        </Drawer>
      </Stack>
    </>
  );
};

export default ProductCardView;
