import MenuItem from "@mui/material/MenuItem";
import ListSubheader from "@mui/material/ListSubheader";
import Select from "@mui/material/Select";
import { styleTextSelectRight } from "@/mui";
import IconMultipleSelect from "@/components/icons/IconMultipleSelect";

function groupSpecialtiesByParent(specialties) {
  const groups = [];

  const parents = specialties.filter((item) => item.parent_id === null || item.parent_id === undefined);

  parents.forEach((parent) => {
    const children = specialties.filter((item) => String(item.parent_id) === String(parent.id));
    if (children.length > 0) {
      groups.push({
        parent,
        children,
      });
    }
  });

  return groups;
}

export default function GroupedSelect({
  list,
  name,
  updateData,
  data,
  nameKey = "name",
}) {
  const groupedList = groupSpecialtiesByParent(list);

  const handleChange = (event) => {
    const value = event.target.value;
    updateData && updateData(value, "value", name);
  };

  return (
    <div className="w-full auto-complete-selector">
      <Select
        value={data}
        onChange={handleChange}
        IconComponent={IconMultipleSelect}
        MenuProps={{
          style: {
            maxHeight: 300,
          },
        }}
        className="!w-full"
        sx={{
          ...styleTextSelectRight,
          "& .MuiSelect-icon": {
            left: "16px",
            right: "auto",
          },
          "& .MuiInputBase-input": { padding: "12.5px 14px !important" },
          "& .MuiInputBase-root": {
            borderRadius: 2,
            padding: "0 !important",
            height: {
              xs: "43px !important",
              sm: "43px !important",
              md: "46px !important",
              lg: "48px !important",
            },
          },
          "& .MuiOutlinedInput-notchedOutline": {
            border: "1px solid #D7D7D7",
          },
          "& .MuiInput-underline:hover:not(.Mui-disabled):before, .MuiOutlinedInput-notchedOutline":
            {
              borderColor: "#D7D7D7 !important",
            },
          "& .muirtl-1kiro5a-MuiInputBase-root-MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline":
            {
              border: "1px solid #5559CE !important",
            },
        }}
      >
        {groupedList.map((group) => [
          <ListSubheader
            key={group.parent.id}
            sx={{
              backgroundColor: "#35343D",
              color: "#fff",
              fontSize: "14px",
            }}
          >
            {group.parent[nameKey]}
          </ListSubheader>,
          ...group.children.map((child) => (
            <MenuItem key={child.id} value={child.id}>
              {child[nameKey]}
            </MenuItem>
          )),
        ])}
      </Select>
    </div>
  );
}
