import {
  Avatar,
  MenuItem,
  Select,
  SelectChangeEvent,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import Box from "@mui/material/Box";
import { FC, useCallback, useRef, useState } from "react";
import "./CustomSelect.css";
import arrow_down from "../../assets/icons/arrow_down.svg";

type CustomSelectProps = {
  items: string[];
  selectedItem: string | null;
  setSelectedItem: (value: string | null) => void;
};

export const CustomSelect: FC<CustomSelectProps> = ({
  items,
  selectedItem,
  setSelectedItem,
}) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(600));
  const [opened, setOpened] = useState<boolean>(false);
  const [currentValue, setCurrentValue] = useState<string | null>(selectedItem);
  const ref = useRef<HTMLDivElement | null>(null);

  const onSelectItem = useCallback(
    (event: SelectChangeEvent<HTMLDivElement>) => {
      const newValue = event.target.value.toString();
      setCurrentValue(newValue);
      setSelectedItem(newValue);
    },
    [setSelectedItem, setCurrentValue],
  );

  const toggleOpened = useCallback(() => {
    setOpened((isOpened) => !isOpened);
  }, []);

  return (
    <Box>
      <Box
        sx={{
          zIndex: 3,
          position: "relative",
          width: "100%",
          height: "56px",
          padding: "5px",
          color:
            currentValue === null
              ? theme.palette.grey2.main
              : theme.palette.brightPurple.main,
          border: `2px solid ${theme.palette.common.white}`,
          borderRadius: "30px",
          background: "#EFF0F5",
          display: "flex",
          alignItems: "center",
          cursor: "pointer",
        }}
        onClick={() => ref.current?.click()}
      >
        <Avatar sx={{ width: 46, height: 46, marginRight: 1 }} />
        <Typography
          sx={{
            marginLeft: isMobile ? "10px" : "20px",
            fontWeight: currentValue === null ? "400" : "500",
            fontSize: isMobile ? "14px" : "16px",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
            overflow: "hidden",
            flexGrow: 1,
          }}
        >
          {currentValue || "Выберите ответственного за сделку"}
        </Typography>
        <img
          src={arrow_down}
          alt="check"
          style={{
            position: "absolute",
            top: "50%",
            right: "10px",
            transform: `translateY(-50%) rotate(${opened ? "180deg" : "0deg"}`,
            height: "36px",
            width: "36px",
          }}
          className={`select-icon ${opened ? "opened" : ""}`}
        />
      </Box>
      <Select
        ref={ref}
        className="select"
        value={""}
        open={opened}
        MenuProps={{
          disablePortal: true,
          PaperProps: {
            style: {
              zIndex: 2,
              maxHeight: "300px",
              overflow: "auto",
            },
          },
        }}
        sx={{ width: "100%" }}
        onChange={onSelectItem}
        onClick={toggleOpened}
      >
        {items.map((item) => {
          const uniqueKey = `${item}-${Date.now()}`;
          return (
            <MenuItem
              key={uniqueKey}
              value={item}
              sx={{ padding: "12px", zIndex: 2 }}
            >
              {item}
            </MenuItem>
          );
        })}
      </Select>
    </Box>
  );
};
