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

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

import {
  Grid,
  Card,
  CardContent,
  Typography,
  Button,
  Stack,
  CardActionArea,
  Box,
  Tabs,
  Tab,
  Chip,
  Autocomplete,
  TextField,
  useMediaQuery,
  IconButton,
  Avatar,
  ButtonGroup,
  InputAdornment,
  OutlinedInput,
  Dialog,
  DialogContent
} from '@mui/material';

import { useTheme } from '@emotion/react';
import MainCard from 'components/MainCard';

// import { useNavigate } from 'react-router';
import { getproductscount, getproductsubcategories } from './api';
import { useQuery } from '@tanstack/react-query';
import uploadImage from '../../assets/images/uploadImage.png';
import { useDebounce } from 'use-debounce';
import { FilterAltOutlined } from '@mui/icons-material';
import TitleCard from 'components/TitleCard';
import ProductsView from './ProductsView';
import Addproducts from './Addproducts';

const Products = () => {
  const theme = useTheme();
  // const navigate = useNavigate();
  const textFieldRef = useRef(null);
  const [tabValue, setTabValue] = useState(0);
  const [selectedCat, setSelectedCat] = useState(null);
  const [view, setView] = useState('card');
  const [search, setSearch] = useState('');
  const [debouncedSearchword] = useDebounce(search, 700); // ⏱️ Debounce for 500ms
  const [catDialog, setCatDialog] = useState(false);
  const custom700 = useMediaQuery(theme.breakpoints.up('custom700'));
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const [addDialog, setAddDialog] = useState(false);
  /* ============================================= || 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 handleViewChange = (newView) => {
    setView(newView);
  };
  const categories = [
    {
      title: 'Fresh Fruits & Vegetables',
      image: '/images/fruits.png',
      selected: true
    },
    {
      title: 'Dairy & Eggs',
      image: '/images/dairy.png'
    },
    {
      title: 'Grains & Staples',
      image: '/images/grains.png'
    },
    {
      title: 'Oils, Masalas & Condiments',
      image: '/images/oils.png'
    },
    {
      title: 'Bakery & Breads',
      image: '/images/bakery.png'
    },
    {
      title: 'Breakfast & Spreads',
      image: '/images/breakfast.png'
    }
  ];

  const handleChange = (event, newValue) => {
    console.log(newValue);
    setTabValue(newValue);
  };

  const { data: SubCat } = useQuery({
    queryKey: ['getubcategories'],
    queryFn: getproductsubcategories
  });

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

  const CatAutocomplete = ({ forceOpen = false }) => {
    console.log('forceOpen', forceOpen);
    const [localOpen, setLocalOpen] = useState(false);
    return (
      <Autocomplete
        disablePortal
        open={forceOpen || localOpen} // by default false, when forceopen prop passes makes autoOpen
        onOpen={() => setLocalOpen(true)} // make open
        onClose={() => setLocalOpen(false)} // make close
        id="combo-box-category"
        options={SubCat || []}
        getOptionLabel={(option) => option?.subcatname || ''}
        onChange={(event, value) => setSelectedCat(value)}
        sx={{ minWidth: { xs: 300, custom450: 250 } }}
        slotProps={{
          paper: {
            sx: {
              minWidth: 300,
              // maxHeight: 300,
              overflowY: 'auto'
            }
          }
        }}
        renderOption={(props, option) => (
          <Box {...props} sx={{ display: 'flex', alignItems: 'center', gap: 1, width: '100%' }}>
            <Avatar src={option.image || uploadImage} alt={option.subcatname} variant="square" sx={{ width: 24, height: 24 }} />
            <Typography variant="body1">{option.subcatname}</Typography>
          </Box>
        )}
        renderInput={(params) => <TextField {...params} placeholder="Select Category" value={selectedCat?.subcatname || ''} />}
      />
    );
  };

  return (
    <Stack>
      <TitleCard
        title={'Products'}
        secondary={
          <Stack display={'flex'} flexDirection="row" gap={2}>
            <ButtonGroup
              variant="outlined"
              aria-label="view toggle"
              sx={{
                borderRadius: 2,
                boxShadow: 'none'
              }}
            >
              <Button
                onClick={() => handleViewChange('card')}
                variant={view === 'card' ? 'contained' : 'outlined'}
                color={view === 'card' ? 'primary' : 'inherit'}
              >
                <AppstoreOutlined />
              </Button>

              <Button
                onClick={() => handleViewChange('list')}
                variant={view === 'list' ? 'contained' : 'outlined'}
                color={view === 'list' ? 'primary' : 'inherit'}
              >
                <UnorderedListOutlined />
              </Button>
            </ButtonGroup>
            {isMobile ? (
              <IconButton
                sx={{
                  backgroundColor: 'primary.main',
                  color: 'white',
                  '&:hover': {
                    backgroundColor: 'primary.main'
                  }
                }}
                onClick={() => {
                  if (tabValue === 0) setAddDialog(true);
                }}
              >
                <PlusCircleOutlined />
              </IconButton>
            ) : (
              <Chip
                icon={<PlusCircleOutlined />}
                label={tabValue === 0 ? 'Add Products' : 'Add Category'}
                variant="filled"
                color="primary"
                onClick={() => {
                  if (tabValue === 0) setAddDialog(true);
                }}
                sx={{
                  whiteSpace: 'nowrap',
                  px: 1.5,
                  height: 36
                }}
              />
            )}
          </Stack>
        }
        sx={{ backgroundColor: '' }}
      />

      <Grid
        container
        direction={{ xs: 'column', custom500: 'row' }}
        alignItems="center"
        justifyContent={{ xs: 'space-between' }}
        flexWrap={'nowrap'}
        sx={{
          border: 1,
          borderColor: 'border.light',
          px: 2,
          py: 1.5,
          position: 'sticky',
          top: 128,
          backgroundColor: '#fff', // changed from 'red'
          zIndex: 2
        }}
      >
        {/* Left: Tabs */}
        <Grid item xs={4}>
          <Tabs
            value={tabValue}
            onChange={handleChange}
            variant="scrollable"
            scrollButtons="auto"
            aria-label="product tabs"
            sx={{
              flexShrink: 0,
              minHeight: 48
            }}
          >
            <Tab label="Products" icon={<ShoppingCartOutlined />} iconPosition="start" />
            <Tab label="Categories" icon={<UnorderedListOutlined />} iconPosition="start" disabled />
          </Tabs>
        </Grid>

        {tabValue === 0 && (
          <Grid
            item
            xs={8}
            sx={{
              display: 'flex',
              justifyContent: { xs: 'space-between', custom500: 'flex-end' },
              flexDirection: { xs: 'row-reverse', custom500: 'row' },
              gap: 2,
              width: '100%',
              mt: { xs: 1, custom500: 0 }
            }}
          >
            {custom700 ? (
              <CatAutocomplete /> // desktop view
            ) : (
              <IconButton
                sx={{ bgcolor: 'secondary.lighter' }}
                onClick={() => {
                  setCatDialog(true); // open dialog
                }}
              >
                <FilterAltOutlined />
              </IconButton>
            )}
            <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>
              }
            />
          </Grid>
        )}
      </Grid>

      {tabValue === 0 && (
        <ProductsView
          sx={{ mt: 1, overflow: 'hidden' }}
          selectedCat={selectedCat}
          view={view}
          productCount={productCount}
          debouncedSearchword={debouncedSearchword}
        />
      )}
      {/*  categories tab */}
      {tabValue === 1 && (
        <MainCard>
          <Grid container spacing={2} sx={{}}>
            {categories.map((cat, index) => (
              <Grid item xs={6} sm={4} md={2} key={index}>
                <Card
                  sx={{
                    border: `1px solid ${theme.palette.bg.main}`,
                    height: '100%'
                  }}
                >
                  <CardActionArea sx={{ height: '100%' }}>
                    <CardContent
                      sx={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        gap: 1.5
                      }}
                    >
                      {cat.productstatus === 'outofstock' && (
                        <Box
                          component="img"
                          src={cat.image}
                          alt={cat.title}
                          sx={{
                            width: '80px',
                            height: '80px',
                            objectFit: 'contain',
                            filter: cat.productstatus === 'outofstock' ? 'grayscale(100%) brightness(0.8)' : 'none', // ✅ grayscale the image only
                            transition: 'filter 0.3s ease'
                          }}
                        />
                      )}
                      <Typography
                        variant="body1"
                        sx={{
                          textAlign: 'center',
                          fontWeight: 500
                        }}
                      >
                        {cat.title}
                      </Typography>
                    </CardContent>
                  </CardActionArea>
                </Card>
              </Grid>
            ))}
          </Grid>
        </MainCard>
      )}
      <Dialog open={catDialog} onClose={() => setCatDialog(false)} sx={{ minWidth: 300 }}>
        <DialogContent sx={{ minHeight: 300 }}>
          <CatAutocomplete forceOpen />
          {/* same as  <CatAutocomplete forceOpen={true} /> */}
          {/* In JSX (like <CatAutocomplete forceOpen />), if you write a prop without a value, React automatically treats it as true. */}
        </DialogContent>
      </Dialog>
      <Dialog open={addDialog} onClose={() => setAddDialog(false)} sx={{}} fullScreen>
        <DialogContent>
          <Addproducts setAddDialog={setAddDialog} />
        </DialogContent>
      </Dialog>
    </Stack>
  );
};

export default Products;
