import Box from "@mui/material/Box";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import { useTheme } from "@mui/material/styles";
import type { SelectChangeEvent, SelectProps } from "@mui/material/Select";

import { AgencyDisplay } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/agency-display";
import {
  getSelectMenuProps,
  getSelectSx,
} from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog-styles";
import { FieldLabel } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/form-label";
import type { Agency } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog-types";
import { dashboardIssueAgencies } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/dashboard-issue-agencies";

type SelectMenuProps = NonNullable<SelectProps["MenuProps"]>;

type AgencySelectProps = {
  agencies?: Agency[];
  disabled?: boolean;
  emptyLabel?: string;
  label: string;
  menuProps?: SelectMenuProps;
  onChange: (value: string) => void;
  value: string;
};

export function AgencySelect({
  agencies = dashboardIssueAgencies,
  disabled = false,
  emptyLabel,
  label,
  menuProps,
  onChange,
  value,
}: AgencySelectProps) {
  const theme = useTheme();

  const selectedAgency = agencies.find(
    (agency) => agency.id === value
  );

  return (
    <Box>
      <FieldLabel>{label}</FieldLabel>

      <Select
        fullWidth
        size="small"
        displayEmpty
        disabled={disabled}
        value={value}
        onChange={(event: SelectChangeEvent) => onChange(event.target.value)}
        renderValue={() => (
          <AgencyDisplay agency={selectedAgency} emptyLabel={emptyLabel} />
        )}
        sx={getSelectSx(theme)}
        MenuProps={menuProps ?? getSelectMenuProps(theme)}
      >
        <MenuItem value="">
          <AgencyDisplay emptyLabel={emptyLabel} />
        </MenuItem>

        {agencies.map((agency) => (
          <MenuItem key={agency.id} value={agency.id}>
            <AgencyDisplay agency={agency} />
          </MenuItem>
        ))}
      </Select>
    </Box>
  );
}