import React, { useRef, useEffect, useState } from 'react';
import TitleCard from '../titleCard';
import {
  Button,
  Chip,
  CircularProgress,
  FormControl,
  IconButton,
  InputAdornment,
  OutlinedInput,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography
} from '@mui/material';
import MainCard from 'components/MainCard';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { gettenantcustomers } from '../api/api';
import { useTheme } from '@mui/material/styles';
import { useNavigate } from 'react-router';
import { FormOutlined, SearchOutlined } from '@ant-design/icons';
import SearchBar from 'components/nearle_components/SearchBar';
import { Empty } from 'antd';

const Customers = () => {
  const navigate = useNavigate();
  const theme = useTheme();
  const loadMoreRef = useRef();
  const containerRef = useRef();
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [customerSearch, setCustomerSearch] = useState('');
  const [debounceCustomerSearch, setDebounceCustomerSearch] = useState('');

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebounceCustomerSearch(customerSearch);
    }, 400);

    return () => clearTimeout(handler);
  }, [customerSearch]);

  const {
    data: customerdata,
    isLoading: isLoadingCustomer,
    isError: isErrorCustomer,
    error: errorCustomer,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage
  } = useInfiniteQuery({
    queryKey: ['customers', rowsPerPage, debounceCustomerSearch],
    queryFn: gettenantcustomers,
    getNextPageParam: (lastPage) => lastPage.nextPage
  });
  const rows = customerdata ? customerdata.pages.flatMap((p) => p.details) : [];
  useEffect(() => {
    customerdata && console.log(customerdata);
  }, [customerdata]);
  useEffect(() => {
    if (!hasNextPage) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          fetchNextPage();
        }
      },
      {
        root: document.querySelector('.MuiTableContainer-root'), // 👈 or explicitly TableContainer
        rootMargin: '0px',
        threshold: 1.0
      }
    );
    if (loadMoreRef.current) observer.observe(loadMoreRef.current);
    return () => {
      if (loadMoreRef.current) observer.unobserve(loadMoreRef.current);
    };
  }, [hasNextPage, fetchNextPage]);

  const handleScroll = (event) => {
    const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
    if (scrollTop + clientHeight >= scrollHeight - 50) {
      if (hasNextPage && !isFetchingNextPage) {
        fetchNextPage();
      }
    }
  };

  return (
    <>
      <TitleCard
        title={'Customers'}
        secondary={
          <Button variant="contained" onClick={() => navigate('/nearle/customers/create')}>
            Create Customers
          </Button>
        }
      />
      <MainCard
        content={false}
        sx={{ width: '100%', overflow: 'hidden' }}
        title={
          <SearchBar
            value={customerSearch}
            placeholder="Search Location"
            onChange={(e) => setCustomerSearch(e.target.value)}
            sx={{
              width: '100%',
              maxWidth: 300,
              minWidth: 200,
              bgcolor: 'white'
            }}
          />
        }
      >
        <TableContainer
          onScroll={handleScroll}
          ref={containerRef}
          sx={{
            width: '100%',
            borderBottom: 1,
            borderColor: 'divider',
            maxHeight: 'calc(100vh - 200px)',
            overflow: 'auto',
            '&::-webkit-scrollbar': {
              width: '12px', // scroll bar widthP
              cursor: 'pointer'
            },
            '&::-webkit-scrollbar-thumb': {
              backgroundColor: theme.palette.primary.main, // thumb color
              borderRadius: '8px',
              cursor: 'pointer'
            },
            '&::-webkit-scrollbar-thumb:hover': {
              backgroundColor: theme.palette.primary.dark, // hover color
              cursor: 'pointer'
            },
            '&::-webkit-scrollbar-track': {
              backgroundColor: theme.palette.primary.lighter,
              cursor: 'pointer'
            }
          }}
        >
          <Table stickyHeader>
            <TableHead sx={{}}>
              <TableRow sx={{ backgroundColor: theme.palette.primary.main }}>
                <TableCell sx={{ position: 'sticky!important', bgcolor: 'secondary.light' }}>#</TableCell>
                <TableCell sx={{ position: 'sticky!important', bgcolor: 'secondary.light' }}>Name</TableCell>
                <TableCell sx={{ position: 'sticky!important', bgcolor: 'secondary.light' }}>suburb</TableCell>
                <TableCell sx={{ position: 'sticky!important', bgcolor: 'secondary.light' }}>Address</TableCell>
                <TableCell sx={{ position: 'sticky!important', bgcolor: 'secondary.light' }}>Lat/Lng</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {rows?.length == 0 && (
                <TableRow>
                  <TableCell colSpan={5}>
                    <Empty description={'Customer Not Found'} />
                  </TableCell>
                </TableRow>
              )}
              {rows?.map((customer, index) => (
                <TableRow key={index}>
                  <TableCell>{index + 1}</TableCell>
                  <TableCell>
                    <Stack>
                      <Typography variant="subtitle1">{customer.firstname}</Typography>
                      <Typography variant="subtitle2">{customer.contactno}</Typography>
                      <Typography variant="subtitle2">{`ID : ${customer.customerid}`}</Typography>
                    </Stack>
                  </TableCell>
                  <TableCell>
                    <Stack>
                      <Typography variant="subtitle1">{customer.suburb}</Typography>
                      <Typography variant="subtitle2">{customer.city}</Typography>
                    </Stack>
                  </TableCell>
                  <TableCell>{customer.address}</TableCell>
                  <TableCell>
                    <Stack display={'flex'} flexDirection={'column'} gap={2}>
                      <Chip size="small" label={customer.latitude} />
                      <Chip size="small" label={customer.longitude} />
                    </Stack>
                  </TableCell>
                </TableRow>
              ))}
              {rows?.length != 0 && (
                <TableRow>
                  <TableCell colSpan={15} rowSpan={3}>
                    <div ref={loadMoreRef} style={{ height: 40, textAlign: 'center' }}>
                      {isFetchingNextPage ? <CircularProgress /> : hasNextPage ? <CircularProgress /> : 'No More Orders'}
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </MainCard>
    </>
  );
};

export default Customers;
