import React, { useEffect, useState, useRef } from 'react';
import {
  Avatar,
  Button,
  Chip,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip,
  TextField,
  Typography,
  Box,
  Divider,
  Switch,
  Paper,
  Slide,
  FormControl,
  FormGroup,
  FormControlLabel,
  Checkbox,
  useMediaQuery,
  Card,
  CardMedia,
  CardContent,
  Drawer,
  Skeleton
} from '@mui/material';

import { Add, Remove, DeleteOutlineOutlined } from '@mui/icons-material';
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import MainCard from 'components/MainCard';
import Titlecard from 'components/nearle_components/Titlecard';

import { createproductstock, getlocationproducts, getlocationproductsummary } from '../api/api';
import { EditOutlined } from '@mui/icons-material';
import { useTheme } from '@emotion/react';
import axios from 'axios';
import OpenToast from 'components/nearle_components/OpenToast';
import { useSelector } from 'react-redux';
import ProductEmpty from 'sections/apps/e-commerce/products/ProductEmpty';
import FilterAltOutlinedIcon from '@mui/icons-material/FilterAltOutlined';
import { ArrowDownOutlined, CheckCircleFilled, PlusCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router';
import FloatingCart from 'components/cards/e-commerce/FloatingCart';
import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar';
import TanstackInfiniteScrollWrapper from 'components/nearle_components/TanstackInfiniteScrollWrapper';

const Products = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const userdata = useSelector((state) => state.userinfo.userdata);
  const [clearStockDialog, setClearStockDialog] = useState(false);
  const [selectedStock, setSelectedStock] = useState();
  const [drawerOpen, setDrawerOpen] = useState(true);
  const isMobile = useMediaQuery(theme.breakpoints.down('sm')); // true if screen < 600px
  const [selectedSubCat, setSelectedSubCat] = useState(null);
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [stockProducts, setStockProducts] = useState([]);
  const [cartDrawer, setCartDrawer] = useState(false);
  const scrollRef = useRef(null);
  const locationid = +localStorage.getItem('locationid');

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

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

  useEffect(() => {
    isMobile && setDrawerOpen(false);
  }, [isMobile]);

  const { data: SubCat } = useQuery({
    queryKey: ['locationproductsummary'],
    queryFn: () => getlocationproductsummary()
  });
  useEffect(() => {
    console.log('getproductsubcategories', SubCat);
  }, [SubCat]);

  const {
    data: productData,
    isLoading: isLoadingProductList,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch: productDataRefetch
  } = useInfiniteQuery({
    queryKey: ['stockproducts', selectedSubCat, debouncedSearch],
    // queryFn: ({ pageParam = 0 }) => getlocationproducts({ pageParam, selectedSubCat, debouncedSearch }),
    queryFn: async ({ pageParam = 0 }) => {
      return getlocationproducts({ pageParam, debouncedSearch, selectedSubCat });
    },
    getNextPageParam: (lastPage, allPages) => {
      if (!lastPage || lastPage.length < 10) return undefined;
      return allPages.length;
    }
  });

  const productList = productData?.pages.flat() || []; // data.pages = [[page1], [page2], [page3]].

  const updateproductlocation = async (props) => {
    try {
      const response = await axios.put(`${process.env.REACT_APP_URL}/products/updateproductlocation`, props);
      console.log('updateproductlocation', response.data.message);
      OpenToast(response.data.message, 'success', 1500);
      productDataRefetch();
      return response.data.data;
    } catch (err) {
      console.log('updateproductlocation', err);
      return err;
    }
  };

  const useCreateProductStock = () => {
    const queryClient = useQueryClient();
    return useMutation({
      mutationFn: createproductstock,
      onSuccess: (data) => {
        OpenToast(data.message, data.status ? 'success' : 'error', 2000);
        // Optionally refetch queries after stock creation
        queryClient.invalidateQueries(['stockproducts']);
        setClearStockDialog(false);
      },
      onError: (error) => {
        OpenToast(error?.response?.data?.message || error.message, 'error', 2000);
      }
    });
  };

  const { mutate: createProductStock, isLoading: createLoading } = useCreateProductStock();

  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);
        setStockProducts([]);
        setCartDrawer(false);
      }
    } catch (err) {
      OpenToast(err.message, 'error', 2000);
    }
  };

  return (
    <div>
      <Titlecard title={' Products'}>
        <Button
          startIcon={<ArrowDownOutlined />}
          variant="contained"
          onClick={() => {
            navigate('/catalogues');
          }}
        >
          Import Products
        </Button>
      </Titlecard>
      {stockProducts?.length > 0 && <FloatingCart count={stockProducts?.length} onClick={() => setCartDrawer(true)} />}

      <Stack sx={{ display: 'flex', position: 'relative', mt: 2, BorderColor: 'none', minHeight: 'auto' }}>
        <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
            }}
          >
            <Stack
              sx={{
                position: 'sticky',
                top: 0,
                zIndex: 1,
                p: 2.7,
                backgroundColor: 'white',
                border: '1px solid',
                borderColor: 'border.light'
              }}
            >
              <Typography variant="h4" sx={{}}>
                Category
              </Typography>
            </Stack>
            <Paper
              elevation={0}
              sx={{
                width: 300,
                height: isMobile ? '100vh' : 'auto',
                maxHeight: isMobile ? '100vh' : 'calc(100vh - 270px)',
                overflowY: 'scroll',
                position: 'relative',
                mt: 2,
                backgroundColor: 'white',
                border: '1px solid',
                borderColor: 'border.light'
              }}
            >
              <Box sx={{ pl: 2, pt: 1 }}>
                <FormControl component="fieldset" sx={{ width: '100%' }}>
                  <FormGroup>
                    {SubCat?.map((category) => (
                      <FormControlLabel
                        key={category.subcategoryid}
                        control={
                          <Checkbox
                            size="small"
                            checked={selectedSubCat?.subcategoryid === category.subcategoryid}
                            onChange={() => {
                              setSelectedSubCat((prev) => (prev?.subcategoryid === category.subcategoryid ? null : category));
                              isMobile && setDrawerOpen(false);
                            }}
                          />
                        }
                        label={
                          <Typography variant="h5">
                            {category.subcategroyname}
                            <Chip
                              size="small"
                              color="primary"
                              variant="combined"
                              label={category.productcount}
                              sx={{
                                ml: 1,
                                height: 20,
                                fontSize: '0.75rem',
                                '.MuiChip-label': {
                                  px: 0.5,
                                  fontSize: '0.7rem',
                                  fontWeight: 500
                                }
                              }}
                            />
                          </Typography>
                        }
                        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 ? '320px' : 0,
            transition: 'margin-left 0.3s ease'
          }}
        >
          <Stack
            sx={{
              width: '100%',
              backgroundColor: 'white',
              mb: 2,
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              p: 2,
              border: '1px solid',
              borderColor: 'border.light',
              position: 'sticky',
              top: 0,
              zIndex: 10
            }}
          >
            <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)}
            />
            <DebounceSearchBar value={searchword} onChange={setSearchword} onDebouncedChange={setDebouncedSearch} />
          </Stack>
          {/* // ==============================||  Product card view ||============================== // */}
          {isLoadingProductList ? (
            <div
              style={{
                display: 'grid',
                justifyContent: 'center',
                gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
                gap: '16px'
              }}
            >
              {Array.from({ length: 10 }).map((_, index) => (
                <CardSkleton key={index} />
              ))}
            </div>
          ) : (
            (productList?.length <= 0 || !productList) && (
              <MainCard>
                <ProductEmpty sx={{ height: 'calc(100vh - 330px)' }} />
              </MainCard>
            )
          )}
          <Stack
            ref={scrollRef}
            sx={{
              maxHeight: 'calc(100vh - 270px)',
              overflow: 'scroll',
              mt: 2
            }}
          >
            <TanstackInfiniteScrollWrapper
              hasNextPage={hasNextPage}
              fetchNextPage={fetchNextPage}
              isFetchingNextPage={isFetchingNextPage}
              scrollContainerRef={scrollRef}
            >
              <div
                style={{
                  display: 'grid',
                  justifyContent: 'center',
                  gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
                  gap: '16px'
                }}
              >
                {productList?.map((product, index) => (
                  <Card
                    key={index}
                    elevation={0}
                    sx={{
                      height: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      border: `1px solid ${theme.palette.border.light}`,
                      overflow: 'hidden',
                      cursor: !product?.approve && 'not-allowed',
                      transition: 'all 0.3s ease',
                      backgroundColor: stockProducts?.some((s) => s.productid == product.productid) && 'primary.lighter'
                      // borderColor: stockProducts?.some((s) => s.productid == product.productid) && 'primary.light'
                    }}
                  >
                    <CardMedia
                      component="img"
                      image={product.productimage}
                      alt={product.productname}
                      sx={{
                        // maxWidth: '200px',
                        height: { xs: '250px' },
                        width: '100%',
                        objectFit: 'cover',
                        filter: product.approve === 0 ? 'grayscale(100%) brightness(0.8)' : 'none', // ✅ grayscale the image only
                        transition: 'filter 0.3s ease',
                        p: 2
                      }}
                    />
                    <Divider />
                    <CardContent sx={{}}>
                      <Stack spacing={1} direction={'row'} alignItems={'center'} justifyContent={'space-between'}>
                        <Typography
                          component="span"
                          sx={{
                            fontWeight: 600,
                            lineHeight: 1.2,
                            wordBreak: 'break-word',
                            fontSize: {
                              xs: 14, // <600px
                              sm: 16, // ≥600px
                              md: 16, // ≥900px
                              lg: 16 // ≥1200px
                            }
                          }}
                        >
                          {product.productname}
                          <Typography variant="body2" color={'secondary'}>
                            {`Id : ${product.productid}`}
                          </Typography>
                        </Typography>
                        <Tooltip placement="top" title={`To Make ${product.status === 'available' ? 'Outofstock' : 'Available'}`}>
                          <Switch
                            size="small"
                            checked={product.status === 'available'}
                            onChange={() =>
                              updateproductlocation({
                                productlocationid: product.productlocationid,
                                status: product.status === 'available' ? 'outofstock' : 'available'
                              })
                            }
                          />
                        </Tooltip>
                      </Stack>
                      <Stack
                        sx={{ width: '100%' }}
                        direction={'row'}
                        alignItems={'center'}
                        justifyContent={'space-between'}
                        spacing={3}
                        sx={{ mr: -1 }}
                      >
                        <Typography component="span" sx={{ fontSize: 14 }}>
                          ₹{product.productcost} / {product.unitvalue}
                          {product.productunit}
                        </Typography>
                        <Tooltip placement="left" title={'Add Stocks'}>
                          <IconButton
                            disabled={!product.approve}
                            size="large"
                            color={stockProducts?.some((s) => s.productid == product.productid) ? 'success' : 'error'}
                            onClick={() => {
                              if (stockProducts?.some((s) => s.productid == product.productid)) {
                                setStockProducts(stockProducts?.filter((p) => p.productid != product.productid));
                              } else {
                                setStockProducts((prev) => [...prev, product]);
                              }
                            }}
                          >
                            {stockProducts?.some((s) => s.productid == product.productid) ? <CheckCircleFilled /> : <PlusCircleOutlined />}
                          </IconButton>
                        </Tooltip>
                      </Stack>
                      <Stack>
                        <Chip
                          disabled={!product.approve}
                          color="primary"
                          variant="contained"
                          label={`Stock : ${product.quantity} ( ${product.productunit} ) `}
                          sx={{ my: 1 }}
                        />
                      </Stack>
                    </CardContent>
                  </Card>
                ))}
                {isFetchingNextPage && <CardSkleton len={1} />}
              </div>
            </TanstackInfiniteScrollWrapper>
          </Stack>
        </Box>
        {/* // ==============================||  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);
                    }}
                  >
                    Update Stocks
                  </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">
                                {`Id : ${product?.productid}`}
                              </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}>
                            {/* Decrease Button */}
                            <IconButton
                              color="error"
                              disabled={product.quantity <= 1} // 🔹 disable when quantity is 1 or less
                              onClick={() => {
                                setStockProducts((prev) =>
                                  prev.map((p) =>
                                    p.productid === product.productid
                                      ? { ...p, quantity: Math.max(p.quantity - 1, 1) } // 🔹 ensure min = 1
                                      : p
                                  )
                                );
                              }}
                            >
                              <Remove />
                            </IconButton>

                            {/* Editable Text Field */}
                            <TextField
                              type="number"
                              placeholder="1"
                              value={product.quantity || 1} // 🔹 fallback to 1
                              onChange={(e) => {
                                const newStock = Math.max(parseInt(e.target.value || '1', 10), 1); // 🔹 enforce min 1
                                // parseInt(e.target.value || '1', 10) , converts str to base 10 integer
                                // Math.max(parseInt(e.target.value || '1', 10), 1); // ,1 makes 1 as min
                                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>

      {/* ============================= || Clear Stocks || =================================== */}
      <Dialog
        open={clearStockDialog}
        onClose={() => {
          setClearStockDialog(false);
          setSelectedStock({});
        }}
        fullWidth
        maxWidth="sm"
      >
        {/* Title */}
        <DialogTitle sx={{ backgroundColor: theme.palette.error.main, color: 'white' }}>
          <Stack direction="row" spacing={2} alignItems="center">
            <IconButton>
              <EditOutlined sx={{ color: 'white' }} />
            </IconButton>
            <Typography variant="h3">Clear Stock</Typography>
          </Stack>
        </DialogTitle>

        {/* Content */}
        <DialogContent sx={{ m: 2 }}>
          <Typography textAlign="center" variant="h4">
            Are you sure you want to clear all stock for <span style={{ color: 'red' }}>{selectedStock?.productname}</span>?
          </Typography>
        </DialogContent>
        <Divider />
        {/* Actions */}
        <DialogActions>
          <Button variant="outlined" onClick={() => setClearStockDialog(false)}>
            Cancel
          </Button>
          <Button
            variant="contained"
            disabled={createLoading}
            onClick={() =>
              createProductStock([
                {
                  tenantid: userdata?.tenantid,
                  stocktype: 'out',
                  locationid: userdata?.locationid,
                  productid: selectedStock.productid,
                  quantity: selectedStock.quantity,
                  minquantity: 10,
                  maxquantity: 100000,
                  status: 'Active'
                }
              ])
            }
          >
            Clear
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
};
const CardSkleton = () => (
  <Card
    elevation={0}
    sx={{
      height: 400,
      display: 'flex',
      flexDirection: 'column',
      border: (theme) => `1px solid ${theme.palette.border.light}`,
      overflow: 'hidden'
    }}
  >
    {/* Image loader */}
    <CardMedia
      sx={{
        height: { xs: '250px' },
        width: '100%',
        backgroundColor: 'grey.200'
      }}
    >
      <Skeleton variant="rectangular" width="100%" height="100%" />
    </CardMedia>

    <Divider />

    <CardContent>
      <Stack direction="row" alignItems="center" justifyContent="space-between">
        <Stack>
          <Skeleton variant="text" width={120} height={24} />
          <Skeleton variant="text" width={80} height={18} />
        </Stack>
        <Tooltip title="Loading...">
          <Skeleton variant="circular" width={32} height={20}>
            <Switch size="small" />
          </Skeleton>
        </Tooltip>
      </Stack>

      {/* Price + IconButton */}
      <Stack direction="row" alignItems="center" justifyContent="space-between" spacing={3} sx={{ mt: 2 }}>
        <Typography component="span">
          <Skeleton variant="text" width={100} height={20} />
        </Typography>
        <Skeleton variant="circular" width={36} height={36}>
          <IconButton size="large" />
        </Skeleton>
      </Stack>

      {/* Stock Chip */}
      <Stack sx={{ mt: 1 }}>
        <Skeleton variant="rounded" width={140} height={32}>
          <Chip label="Stock: ..." />
        </Skeleton>
      </Stack>
    </CardContent>
  </Card>
);

export default Products;
