import React, { useEffect, useState, useRef } from 'react';
import {
  AppstoreOutlined,
  ArrowLeftOutlined,
  PlusCircleOutlined,
  SearchOutlined,
  ShoppingCartOutlined,
  UnorderedListOutlined
} from '@ant-design/icons';

import ClearIcon from '@mui/icons-material/Clear';
import FilterListIcon from '@mui/icons-material/FilterList';

import { UserOutlined, EnvironmentOutlined, BellOutlined } from '@ant-design/icons';

import {
  Grid,
  Card,
  CardMedia,
  CardContent,
  Typography,
  CardActions,
  Button,
  Stack,
  CardActionArea,
  Box,
  Tabs,
  Tab,
  Chip,
  Autocomplete,
  TextField,
  useMediaQuery,
  IconButton,
  Popover,
  Divider,
  Avatar,
  Select,
  MenuItem,
  ListItemIcon,
  ListItemText,
  FormControl,
  InputLabel,
  ButtonGroup,
  InputAdornment,
  OutlinedInput,
  Paper,
  Dialog,
  DialogContent,
  Tooltip
} from '@mui/material';
import dayjs from 'dayjs';
import { useTheme } from '@emotion/react';
import MainCard from 'components/MainCard';

import { useNavigate } from 'react-router';
import VisibilityIcon from '@mui/icons-material/Visibility';
import ViewModuleIcon from '@mui/icons-material/ViewModule';
import ViewListIcon from '@mui/icons-material/ViewList';
import { getproductscount, getproductsubcategories, getsubcategories } from 'pages/nearle/api/api';
import { useQuery } from '@tanstack/react-query';
import uploadImage from '../../../assets/images/uploadImage.png';
import { useDebounce } from 'use-debounce';
import Titlecard from 'components/nearle_components/Titlecard';
import { FilterAltOutlined } from '@mui/icons-material';
import CatalogueCard from './CatalogueCard';

const Catalogues = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const textFieldRef = useRef(null);
  const [tabValue, setTabValue] = useState(0);
  const [selectedCat, setSelectedCat] = useState(null);
  const isMobile = useMediaQuery(theme.breakpoints.down('sm')); // true if screen < 600px
  const [view, setView] = useState('card');
  const [search, setSearch] = useState('');
  const [debouncedSearchword] = useDebounce(search, 700); // ⏱️ Debounce for 500ms
  const [anchorEl, setAnchorEl] = useState(null);
  const handleOpenPopover = (event) => setAnchorEl(event.currentTarget);
  const handleClosePopover = () => setAnchorEl(null);
  const [autoOpen, setAutoOpen] = useState(false);
  const [catDialog, setCatDialog] = useState(false);
  const [count, setCount] = useState(0);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const open = Boolean(anchorEl);
  const id = open ? 'filter-popover' : undefined;

  /* ============================================= || handleKeyPress (ctrl+k)| ============================================= */

  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();

        textFieldRef.current.focus();
      }
      if (event.key === 'Escape' && document.activeElement === textFieldRef.current) {
        // Remove focus from the TextField
        textFieldRef.current.blur();
      }
    };
    document.addEventListener('keydown', handleKeyPress);

    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, []);

  const { data: productCount } = useQuery({
    queryKey: ['productcount', selectedCat],
    queryFn: () => getproductscount(selectedCat?.subcatid || 0)
  });
  useEffect(() => {
    productCount && console.log('productCount', productCount);
  }, [productCount]);

  return (
    <>
      <Stack>
        <Titlecard
          title={'Catalogues'}
          starticon={
            <Tooltip title={'Back to Products'}>
              <IconButton
                variant="contained"
                color="secondary"
                sx={{ backgroundColor: 'secondary.lighter', border: '1px solid', borderColor: 'secondary.light' }}
                onClick={() => {
                  navigate('/products');
                }}
              >
                <ArrowLeftOutlined style={{ fontSize: 20 }} />
              </IconButton>
            </Tooltip>
          }
        ></Titlecard>
        <CatalogueCard />
      </Stack>
    </>
  );
};

export default Catalogues;
