import {
  PlusCircleOutlined,
  ShoppingCartOutlined,
  UnorderedListOutlined,
} from "@ant-design/icons";
import Titlecard from "pages/titleCard";
import React, { useState } from "react";
import {
  UserOutlined,
  EnvironmentOutlined,
  BellOutlined,
} from "@ant-design/icons";
import {
  Grid,
  Card,
  CardMedia,
  CardContent,
  Typography,
  CardActions,
  Button,
  Stack,
  CardActionArea,
  Box,
  Tabs,
  Tab,
  Chip,
  InputLabel,
  Autocomplete,
  TextField,
  useMediaQuery,
  IconButton,
  Divider,
  Avatar,
} from "@mui/material";
import dayjs from "dayjs";
import { useTheme } from "@emotion/react";
import MainCard from "components/MainCard";
import ProductsView from "./ProductsView";
import { useNavigate } from "react-router";
import {
  fetchAppLocations,
  getproductcategories,
  getproductsubcategories,
} from "pages/api/api";
import { useQuery } from "@tanstack/react-query";
import uploadImage from "../../assets/images/uploadImage.png";

const Products = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const [tabValue, setTabValue] = useState(0);
  const [selectedCat, setSelectedCat] = useState(null);
  const isMobile = useMediaQuery(theme.breakpoints.down("sm")); // true if screen < 600px

  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: locations } = useQuery({
    queryKey: ["applocation"],
    queryFn: fetchAppLocations,
  });

  // const { data: cat } = useQuery({
  //   queryKey: ["productcategory"],
  //   queryFn: getproductcategories,
  // });

  const { data: SubCat } = useQuery({
    queryKey: ["productsubcategory"],
    queryFn: getproductsubcategories,
    meta: {
      onSuccess: (data) => {
        console.log("getproductsubcategories:", data);
      },
    },
  });

  return (
    <Stack>
      <Titlecard title={"Products"}></Titlecard>
      <Box
        sx={{
          border: 1,
          borderColor: (theme) => theme.palette.bg.main,
          width: "100%",
          mt: 3,
          display: "flex",
          flexWrap: "wrap",
          justifyContent: "space-between",
          alignItems: "center",
          px: 2,
          py: 1.5,
          position: "sticky",
          top: 60,
          backgroundColor: "#fff",
          zIndex: 10,
          gap: 2,
        }}
      >
        {/* Left side: Tabs */}
        <Tabs
          value={tabValue}
          onChange={handleChange}
          variant="scrollable"
          scrollButtons="auto"
          aria-label="account profile tab"
          sx={{ flexShrink: 0, backgroundColor: "white" }}
        >
          <Tab
            label="Products"
            icon={<ShoppingCartOutlined />}
            iconPosition="start"
          />
          <Tab
            label="Categories"
            icon={<UnorderedListOutlined />}
            iconPosition="start"
            disabled
          />
        </Tabs>

        {/* Right side: Wrap container */}
        <Box
          sx={{
            display: "flex",
            flexWrap: "nowrap", // prevent wrapping between Autocomplete and Chip
            gap: 2,
            alignItems: "center",
            // minWidth: 280,
            flexGrow: 1,
            justifyContent: "flex-end",
            overflow: "hidden",
          }}
        >
          {tabValue === 0 && (
            <Autocomplete
              disablePortal
              id="combo-box-category"
              sx={{
                width: { xs: "100%", sm: 220 },
                // flexShrink: 1,
              }}
              options={SubCat || []}
              getOptionLabel={(option) => option?.subcatname || ""}
              onChange={(event, value) => {
                setSelectedCat(value);
              }}
              renderOption={(props, option) => (
                <Box
                  {...props}
                  sx={{ display: "flex", alignItems: "center", gap: 1 }}
                >
                  <Avatar
                    src={option.image || uploadImage}
                    alt={option.subcatname}
                    variant="square"
                    sx={{ width: 24, height: 24 }}
                  />
                  <Typography variant="h6">{option.subcatname}</Typography>
                </Box>
              )}
              renderInput={(params) => (
                <TextField {...params} placeholder="Select  Category" />
              )}
            />
          )}

          {useMediaQuery(theme.breakpoints.down("sm")) ? (
            <IconButton
              sx={{ backgroundColor: "primary.main", color: "white" }}
              onClick={() => {
                if (tabValue === 0) navigate("../products/add");
              }}
            >
              <PlusCircleOutlined />
            </IconButton>
          ) : (
            <Chip
              icon={<PlusCircleOutlined />}
              variant="filled"
              size="small"
              color="primary"
              label={tabValue === 0 ? "Add Products" : "Add Category"}
              onClick={() => {
                if (tabValue === 0) navigate("../products/add");
              }}
              sx={{
                whiteSpace: "normal", // allow wrapping
                maxWidth: 150, // control max width so it can wrap nicely
                px: 1.5,
                height: 36,
                overflowWrap: "break-word", // break long words if needed
              }}
            />
          )}
        </Box>
      </Box>

      {tabValue === 0 && (
        <ProductsView sx={{ mt: 1 }} selectedCat={selectedCat} />
      )}
      {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>
      )}
    </Stack>
  );
};

export default Products;
