"use client"

import type React from "react"
import { Box, Select, MenuItem, type SxProps, type Theme } from "@mui/material"
import { useTheme } from "@mui/material/styles"

export interface PriorityOption {
  value: string
  label: string
}

interface PrioritySelectProps {
  value: string
  options: PriorityOption[]
  onChange: (value: string) => void
  chipComponent: React.ComponentType<any>
  sx?: SxProps<Theme>
}

export default function PriorityMenu({
  value,
  options,
  onChange,
  chipComponent: ChipComponent,
  sx = {},
}: PrioritySelectProps) {
  const theme = useTheme()
  const currentOption = options.find((opt) => opt.value === value)

  if (!currentOption) {
    console.warn(`Value ${value} not found in options`)
  }

  const handleClick = (event: React.MouseEvent) => {
    event.stopPropagation()
  }

  return (
    <Box sx={{ display: "inline-flex", alignItems: "center" }}>
      <Select
        value={value || ""}
        onClick={handleClick}
        size="small"
        onChange={(e) => {
          e.stopPropagation()
          onChange(e.target.value)
        }}
        renderValue={(selected) => {
          const option = currentOption || options[0]
          return ChipComponent ? (
            <ChipComponent label={option.label} priority={option.value} theme={theme} size="small" />
          ) : (
            <></>
          )
        }}
        sx={{
          height: "32px",
          width: "140px",
          "& .MuiSelect-select": {
            padding: "4px 32px 4px 8px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          },
          "& .MuiOutlinedInput-notchedOutline": {
            border: "none",
          },
          ...sx,
        }}
      >
        {options.map((option) => (
          <MenuItem
            key={option.value}
            value={option.value}
            sx={{
              display: "flex",
              justifyContent: "center",
            }}
          >
            {ChipComponent ? (
              <ChipComponent label={option.label} priority={option.value} theme={theme} size="small" />
            ) : (
              <></>
            )}
          </MenuItem>
        ))}
      </Select>
    </Box>
  )
}
