"use client";

import Box from "@mui/material/Box";
import CircularProgress from "@mui/material/CircularProgress";
import MenuItem from "@mui/material/MenuItem";
import Select, { type SelectChangeEvent } from "@mui/material/Select";
import Typography from "@mui/material/Typography";
import { useTheme, type SxProps, type Theme } from "@mui/material/styles";

import { ChevronDown } from "@/components/ui/icon";
import { IssueStatusBadge } from "@/components/ui/issue-status-badge";
import {
  getElevatedSelectMenuProps,
  getSelectMenuProps,
  getSelectSx,
} from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog-styles";
import type { IssueStatusLookup } from "@/features/ministry/meeting-summary/meeting-summary-service";
import { useIssueStatusOptions } from "@/features/ministry/meeting-summary/hook/use-issue-status-options";

const STATUS_COLORS_BY_CODE: Record<string, string> = {
  IN_PROGRESS: "#f79009",
  SOLVED: "#3ead46",
  NOT_ADDRESSED: "#f04438",
};

function findStatusByName(
  status: string,
  options: IssueStatusLookup[],
): IssueStatusLookup | undefined {
  const trimmed = status.trim();
  if (!trimmed) return undefined;

  return options.find(
    (option) => option.name.toLowerCase() === trimmed.toLowerCase(),
  );
}

export function getInitialIssueStatus(status: string): string {
  const trimmed = status.trim();

  if (
    !trimmed ||
    trimmed === "New Submitted" ||
    trimmed === "New Submission" ||
    trimmed === "Draft" ||
    trimmed === "Saved"
  ) {
    return "";
  }

  if (trimmed === "Not Address") {
    return "Not Addressed";
  }

  return trimmed;
}

const statusSelectSx = {
  height: 28,
  minWidth: 136,
  bgcolor: "#fafafa",
  borderRadius: "6px",
  "& .MuiOutlinedInput-notchedOutline": {
    borderColor: "#f5f5f5",
  },
  "&:hover .MuiOutlinedInput-notchedOutline": {
    borderColor: "#f5f5f5",
  },
  "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
    borderColor: "#f5f5f5",
    borderWidth: "1px",
  },
  "& .MuiSelect-select": {
    height: 28,
    minHeight: "28px !important",
    py: "2px",
    px: "8px",
    display: "flex",
    alignItems: "center",
    boxSizing: "border-box",
  },
  "& .MuiSelect-icon": {
    fontSize: 20,
    color: "#717680",
    right: 8,
  },
} as const;

const statusBadgeSelectSx = {
  height: 28,
  minWidth: 136,
  bgcolor: "transparent",
  fieldset: { border: "none" },
  "& .MuiOutlinedInput-notchedOutline": {
    border: "none",
  },
  "&:hover .MuiOutlinedInput-notchedOutline": {
    border: "none",
  },
  "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
    border: "none",
  },
  "& .MuiSelect-select": {
    height: 28,
    minHeight: "28px !important",
    py: 0,
    px: 0,
    pr: "28px !important",
    display: "flex",
    alignItems: "center",
    boxSizing: "border-box",
  },
  "& .MuiSelect-icon": {
    fontSize: 20,
    color: "#717680",
    right: 0,
  },
} as const;

function StatusOptionLabel({
  name,
  code,
}: {
  name: string;
  code?: string;
}) {
  const color = code ? STATUS_COLORS_BY_CODE[code] : undefined;

  if (!color) {
    return (
      <Typography
        sx={{
          fontSize: 12,
          fontWeight: 400,
          color: "#414651",
          lineHeight: 1,
          whiteSpace: "nowrap",
        }}
      >
        {name}
      </Typography>
    );
  }

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: "6px", minWidth: 0 }}>
      <Box
        sx={{
          width: 7,
          height: 7,
          borderRadius: "50%",
          bgcolor: color,
          flexShrink: 0,
        }}
      />
      <Typography
        sx={{
          fontSize: 12,
          fontWeight: 400,
          color,
          lineHeight: 1,
          whiteSpace: "nowrap",
        }}
      >
        {name}
      </Typography>
    </Box>
  );
}

type IssueStatusSelectProps = {
  value: string;
  placeholder?: string;
  menuZIndex?: number;
  onChange: (value: string) => void;
  sx?: SxProps<Theme>;
  disabled?: boolean;
  /** Use the shared IssueStatusBadge pill for the closed select value. */
  variant?: "default" | "badge";
};

export function IssueStatusSelect({
  value,
  placeholder = "Select status",
  menuZIndex,
  onChange,
  sx,
  disabled = false,
  variant = "default",
}: IssueStatusSelectProps) {
  const theme = useTheme();
  const { data: options = [], isLoading } = useIssueStatusOptions();
  const useBadge = variant === "badge";

  const handleChange = (event: SelectChangeEvent<string>) => {
    onChange(event.target.value);
  };

  const baseMenuProps =
    menuZIndex != null
      ? getElevatedSelectMenuProps(theme, menuZIndex)
      : getSelectMenuProps(theme);

  const menuProps = {
    ...baseMenuProps,
    slotProps: {
      ...baseMenuProps.slotProps,
      paper: {
        ...baseMenuProps.slotProps?.paper,
        sx: {
          ...(baseMenuProps.slotProps?.paper as { sx?: object } | undefined)?.sx,
          minWidth: 136,
        },
      },
    },
  };

  return (
    <Select
      displayEmpty
      size="small"
      value={value}
      onChange={handleChange}
      disabled={disabled || isLoading}
      IconComponent={ChevronDown}
      renderValue={(selected) => {
        if (isLoading) {
          return (
            <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
              <CircularProgress size={14} sx={{ color: "#717680" }} />
              <Typography
                sx={{
                  fontSize: 12,
                  fontWeight: 500,
                  color: "#717680",
                  lineHeight: 1,
                }}
              >
                Loading...
              </Typography>
            </Box>
          );
        }

        if (!selected) {
          return (
            <Typography
              sx={{
                fontSize: 12,
                fontWeight: 500,
                color: "#717680",
                lineHeight: 1,
                whiteSpace: "nowrap",
              }}
              noWrap
            >
              {placeholder}
            </Typography>
          );
        }

        const option = findStatusByName(String(selected), options);
        const statusName = option?.name ?? String(selected);

        if (useBadge) {
          return <IssueStatusBadge status={statusName} />;
        }

        return (
          <StatusOptionLabel
            name={statusName}
            code={option?.code}
          />
        );
      }}
      sx={{
        ...getSelectSx(theme),
        ...(useBadge ? statusBadgeSelectSx : statusSelectSx),
        ...sx,
      }}
      MenuProps={menuProps}
    >
      {options.map((option) => (
        <MenuItem
          key={option.id}
          value={option.name}
          sx={{
            px: "12px",
            py: "10px",
            minHeight: "unset",
          }}
        >
          <StatusOptionLabel name={option.name} code={option.code} />
        </MenuItem>
      ))}
    </Select>
  );
}
