import React, { useState, useEffect } from "react";
import {
  Typography,
  Box,
  ButtonBase,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import {
  Spa as SpaIcon,
  Grass as GrassIcon,
  Grain as GrainIcon,
  BlurOn as BlurOnIcon,
  Texture as TextureIcon,
} from "@mui/icons-material";
import { motion } from "framer-motion";

const products = {
  bran: { label: "سبوس", icon: <SpaIcon fontSize="small" /> },
  barley: { label: "جو", icon: <GrassIcon fontSize="small" /> },
  soy: { label: "سویا", icon: <BlurOnIcon fontSize="small" /> },
  corn: { label: "ذرت", icon: <GrainIcon fontSize="small" /> },
  sheep_concentrate: {
    label: "کنسانتره گوسفندی",
    icon: <TextureIcon fontSize="small" />,
  },
  high_cow_concentrate: {
    label: "کنسانتره گاو شیری پرتولید",
    icon: <TextureIcon fontSize="small" />,
  },
  medium_cow_concentrate: {
    label: "کنسانتره گاو شیری متوسط",
    icon: <TextureIcon fontSize="small" />,
  },
  fattening_calf_concentrate: {
    label: "کنسانتره گوساله پرواری",
    icon: <TextureIcon fontSize="small" />,
  },
};

const LOCAL_STORAGE_KEY = "selectedProduct";

const MotionBox = motion(Box);

const ProductSelector = ({ onSelect }) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const [selected, setSelected] = useState("bran");

  useEffect(() => {
    const saved = localStorage.getItem(LOCAL_STORAGE_KEY);
    if (saved) {
      const parsed = JSON.parse(saved);
      if (parsed.key && products[parsed.key]) {
        setSelected(parsed.key);
        onSelect(parsed);
      }
    } else {
      onSelect({ key: "bran", label: products["bran"].label });
    }
  }, [onSelect]);

  const handleSelect = (key) => {
    const selectedProduct = { key, label: products[key].label };
    setSelected(key);
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(selectedProduct));
    onSelect(selectedProduct);
  };

  return (
    <Box sx={{ mt: 2 }}>
      <Typography variant="h6" textAlign="center" color="primary" mb={1}>
        انتخاب محصول
      </Typography>

      <Box
        sx={{
          display: "flex",
          flexWrap: isMobile ? "nowrap" : "wrap",
          overflowX: isMobile ? "auto" : "visible",
          gap: 1,
          px: 2,
          py: 1,
          justifyContent: isMobile ? "flex-start" : "center",
          scrollbarWidth: "none",
          "&::-webkit-scrollbar": { display: "none" },
        }}
      >
        {Object.entries(products).map(([key, { label, icon }]) => {
          const isSelected = selected === key;

          return (
            <MotionBox
              key={key}
              whileTap={{ scale: 0.95 }}
              whileHover={{ scale: 1.05 }}
              transition={{ duration: 0.15 }}
            >
              <ButtonBase
                onClick={() => handleSelect(key)}
                sx={{
                  borderRadius: "30px",
                  border: `1px solid ${
                    isSelected ? theme.palette.primary.main : "#ddd"
                  }`,
                  backgroundColor: isSelected ? "#e3f2fd" : "#fff",
                  px: 2,
                  py: 1,
                  display: "flex",
                  alignItems: "center",
                  gap: 1,
                  whiteSpace: "nowrap",
                  boxShadow: isSelected ? "0 2px 5px rgba(0,0,0,0.1)" : "none",
                  transition: "all 0.2s ease-in-out",
                  minWidth: 150,
                  justifyContent: "center",
                }}
              >
                {icon}
                <Typography fontSize={13}>{label}</Typography>
              </ButtonBase>
            </MotionBox>
          );
        })}
      </Box>
    </Box>
  );
};

export default ProductSelector;
