import { useInfiniteQuery } from '@tanstack/react-query';
import React, { useState, useRef } from 'react';
import { getstockstatement } from '../api/api';
import { Avatar, Chip, Skeleton, Stack, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Typography } from '@mui/material';
import MainCard from 'components/MainCard';
import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar';
import SubcatAutocomplete from 'components/nearle_components/SubcatAutocomplete';
import Titlecard from 'components/nearle_components/Titlecard';
import TanstackInfiniteScrollWrapper from 'components/nearle_components/TanstackInfiniteScrollWrapper';
import ProductEmpty from 'sections/apps/e-commerce/products/ProductEmpty';

const StockStatement = () => {
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [selectedSubCat, setSelectedSubCat] = useState(null);
  const scrollRef = useRef(null);
  // const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  const {
    data: statementData,
    isLoading: isLoadingStatement,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage
  } = useInfiniteQuery({
    queryKey: ['stockStatement', debouncedSearch, selectedSubCat],
    // queryFn: ({ pageParam = 0 }) => getstockstatement({ pageParam, debouncedSearch, selectedSubCat }),
    queryFn: async ({ pageParam = 0 }) => {
      // 👇 wait 5 seconds before calling API
      // await sleep(5000);
      return getstockstatement({ pageParam, debouncedSearch, selectedSubCat });
    },
    getNextPageParam: (lastPage, allPages) => {
      if (!lastPage || lastPage.length < 10) {
        return undefined; // 👈 stop when no more data
      }
      return allPages.length; // 👈 next page index
    }
  });

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

  return (
    <Stack>
      <Titlecard title={'Product Statement'}></Titlecard>
      <MainCard
        sx={{}}
        contentSX={{ p: 0 }}
        title={
          <Stack display={'flex'} flexDirection={{ xs: 'column', custom700: 'row' }} alignItems={'center'} justifyContent={'end'} gap={3}>
            <SubcatAutocomplete onSelect={setSelectedSubCat} sx={{ minWidth: 260 }} />
            <DebounceSearchBar value={searchword} onChange={setSearchword} onDebouncedChange={setDebouncedSearch} sx={{ minWidth: 260 }} />
          </Stack>
        }
      >
        <TableContainer ref={scrollRef} sx={{ maxHeight: 'calc(100vh - 270px)' }}>
          <TanstackInfiniteScrollWrapper
            hasNextPage={hasNextPage}
            fetchNextPage={fetchNextPage}
            isFetchingNextPage={isFetchingNextPage}
            scrollContainerRef={scrollRef}
          >
            <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' }}>Rate</TableCell>
                  <TableCell sx={{ position: 'sticky !important' }}>Opening</TableCell>
                  <TableCell sx={{ position: 'sticky !important' }}>Credit</TableCell>
                  <TableCell sx={{ position: 'sticky !important' }}>Debit</TableCell>
                  <TableCell sx={{ position: 'sticky !important' }}>Closing</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {isLoadingStatement && <TableSkleton len={10} />}
                {(statementList?.length <= 0 || !statementList) && (
                  <TableRow>
                    <TableCell colSpan={7}>
                      <ProductEmpty />
                    </TableCell>
                  </TableRow>
                )}
                {statementList?.map((product, index) => (
                  <TableRow key={index}>
                    <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={{}}>
                      <Chip
                        color="primary"
                        variant="combined"
                        sx={{ minWidth: 100 }}
                        label={
                          <Typography variant="body1">
                            {product?.opening}{' '}
                            <Typography component="span" variant="body2">
                              {`(${product?.productunit})`}
                            </Typography>
                          </Typography>
                        }
                      />
                    </TableCell>
                    <TableCell sx={{}}>
                      <Chip
                        color="success"
                        variant="combined"
                        sx={{ minWidth: 100 }}
                        label={
                          <Typography variant="body1">
                            {product?.credit}{' '}
                            <Typography component="span" variant="body2">
                              {`(${product?.productunit})`}
                            </Typography>
                          </Typography>
                        }
                      />
                    </TableCell>
                    <TableCell sx={{}}>
                      <Chip
                        color="error"
                        variant="combined"
                        sx={{ minWidth: 100 }}
                        label={
                          <Typography variant="body1">
                            {product?.debit}{' '}
                            <Typography component="span" variant="body2">
                              {`(${product?.productunit})`}
                            </Typography>
                          </Typography>
                        }
                      />
                    </TableCell>
                    <TableCell sx={{}}>
                      <Chip
                        color="primary"
                        variant="combined"
                        sx={{ minWidth: 100 }}
                        label={
                          <Typography variant="body1">
                            {product?.closing}{' '}
                            <Typography component="span" variant="body2">
                              {`(${product?.productunit})`}
                            </Typography>
                          </Typography>
                        }
                      />
                    </TableCell>
                  </TableRow>
                ))}
                {isFetchingNextPage && <TableSkleton len={3} />}
              </TableBody>
            </Table>
          </TanstackInfiniteScrollWrapper>
        </TableContainer>
      </MainCard>
    </Stack>
  );
};

/* // ==============================||  TableSkleton ||============================== // */

const TableSkleton = ({ len }) =>
  Array.from({ length: len }).map((_, index) => (
    <TableRow key={index}>
      {/* Index */}
      <TableCell>
        <Skeleton variant="text" width={20} />
      </TableCell>

      {/* Avatar + Name + ID */}
      <TableCell>
        <Stack direction="row" spacing={1.5} alignItems="center">
          <Skeleton variant="rounded" width={40} height={40} />
          <Stack spacing={0.5}>
            <Skeleton variant="text" width={120} />
            <Skeleton variant="text" width={80} />
          </Stack>
        </Stack>
      </TableCell>

      {/* Cost */}
      <TableCell>
        <Skeleton variant="text" width={80} />
      </TableCell>

      {/* Opening */}
      <TableCell>
        <Chip label={<Skeleton variant="text" width={60} />} sx={{ minWidth: 100 }} />
      </TableCell>

      {/* Credit */}
      <TableCell>
        <Chip label={<Skeleton variant="text" width={60} />} sx={{ minWidth: 100 }} />
      </TableCell>

      {/* Debit */}
      <TableCell>
        <Chip label={<Skeleton variant="text" width={60} />} sx={{ minWidth: 100 }} />
      </TableCell>

      {/* Closing */}
      <TableCell>
        <Chip label={<Skeleton variant="text" width={60} />} sx={{ minWidth: 100 }} />
      </TableCell>
    </TableRow>
  ));

export default StockStatement;
