"use client";

import { useMemo, useState } from "react";

import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { Dropdown, type DropdownOption } from "@/components/ui/dropdown";
import { ChevronDown } from "@/components/ui/icon";
import { IssueStatusSelect } from "@/features/ministry/meeting-summary/components/create-meeting-summary/issue-status-select";
import { useIssueStatusOptions } from "@/features/ministry/meeting-summary/hook/use-issue-status-options";
import { StatusBadge } from "@/features/pswg/working-group-issues/components/table/wg-issues-table-cells";
import type { IssueStatus } from "@/features/pswg/working-group-issues/wg-issues-data";
import type { WgIssuesLanguage } from "@/features/pswg/working-group-issues/wg-issues-i18n";

import type {
  CdcIssueMatrixAgency,
  CdcIssueMatrixRow,
} from "./cdc-issue-matrix-data";

/** How a row's Ministry cell behaves for the current user. */
export type MinistryEditControl = {
  canEdit: boolean;
  isUpdating: boolean;
  agencyOptions: DropdownOption[];
  selectionResetKey: number;
  onSave: (row: CdcIssueMatrixRow, agencies: CdcIssueMatrixAgency[]) => void;
};

/** How a row's Status cell behaves for the current user. */
export type StatusEditControl = {
  canEdit: boolean;
  isUpdating: boolean;
  onSave: (
    row: CdcIssueMatrixRow,
    statusId: number,
    statusName: string,
  ) => void;
};

/**
 * The ministry of an issue is its primary agency, so it can be re-assigned on
 * any row, whoever raised the issue. A row still needs a saved issue behind it.
 */
export function canEditGovernmentAgency(
  row: Pick<CdcIssueMatrixRow, "source" | "issueId">,
  canEdit: boolean,
): boolean {
  return canEdit && row.issueId > 0;
}

/** The ministry name + logo shown in a table cell. */
export function MinistryCell({
  value,
  image,
  trailing,
}: {
  value: string;
  image?: string;
  trailing?: React.ReactNode;
}) {
  const theme = useTheme();

  if (!value || value === "-") {
    return (
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: 1,
          width: "100%",
          minWidth: 0,
        }}
      >
        <Typography sx={{ color: theme.palette.text.primary, fontSize: 13 }}>
          -
        </Typography>
        {trailing}
      </Box>
    );
  }

  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        gap: 1,
        width: "100%",
        minWidth: 0,
      }}
    >
      <Box
        component="img"
        src={image || "/images/agencies/default.png"}
        alt={value}
        sx={{
          width: 24,
          height: 24,
          borderRadius: "50%",
          objectFit: "cover",
          flexShrink: 0,
          border: `1px solid ${alpha(theme.palette.divider, 0.8)}`,
          bgcolor:
            theme.palette.mode === "dark"
              ? alpha(theme.palette.primary.main, 0.14)
              : "#E8F4FF",
        }}
      />
      <Typography
        sx={{
          color: theme.palette.text.primary,
          fontSize: 13,
          fontWeight: 600,
          whiteSpace: "nowrap",
          overflow: "hidden",
          textOverflow: "ellipsis",
          minWidth: 0,
        }}
        title={value}
      >
        {value}
      </Typography>
      {trailing}
    </Box>
  );
}

// Match StatusSelectCell: borderless trigger + MUI ChevronDown end icon.
const cellTriggerSx = {
  height: "100%",
  bgcolor: "transparent",
  "& .MuiOutlinedInput-notchedOutline": { border: "none" },
  "&:hover .MuiOutlinedInput-notchedOutline": { border: "none" },
  "&.Mui-focused .MuiOutlinedInput-notchedOutline": { border: "none" },
  "& .MuiSelect-select": {
    px: 0,
    py: 0,
    minHeight: "auto !important",
    pr: "28px !important",
  },
  "& .MuiSelect-icon": {
    fontSize: 20,
    color: "text.secondary",
    right: 0,
  },
} as const;

export function MinistrySelectCell({
  row,
  control,
}: {
  row: CdcIssueMatrixRow;
  control?: MinistryEditControl;
}) {
  // The first agency is the primary agency saved by the API.
  const committedValue = useMemo(
    () => (row.agencies[0] ? String(row.agencies[0].id) : ""),
    [row.agencies],
  );
  // The pick while the menu is open. Null means the user is not editing.
  const [draftValue, setDraftValue] = useState<string | null>(null);

  const isEditable = canEditGovernmentAgency(row, Boolean(control?.canEdit));

  if (!isEditable || !control) {
    return (
      <MinistryCell
        value={row.primaryAgency}
        image={row.primaryAgencyImage ?? undefined}
      />
    );
  }

  const selectedValue = draftValue ?? committedValue;

  const toAgency = (value: string): CdcIssueMatrixAgency => {
    const saved = row.agencies.find((agency) => String(agency.id) === value);
    if (saved) return saved;

    const option = control.agencyOptions.find(
      (agencyOption) => agencyOption.value === value,
    );

    return {
      id: Number(value),
      name: option?.label ?? "-",
      logo: option?.logo ?? null,
    };
  };

  const handleChange = (value: string | string[]) => {
    const nextValue = Array.isArray(value) ? value[0] : value;

    if (!nextValue || nextValue === committedValue) return;

    setDraftValue(nextValue);
    control.onSave(row, [toAgency(nextValue)]);
  };

  const handleClose = () => {
    setDraftValue(null);
  };

  return (
    <Dropdown
      label={row.primaryAgency}
      options={control.agencyOptions}
      value={selectedValue}
      showCheckbox
      width="100%"
      disabled={control.isUpdating}
      onChange={handleChange}
      onClose={handleClose}
      triggerSx={cellTriggerSx}
      IconComponent={ChevronDown}
      renderTrigger={(values) => {
        const primary = values[0] ? toAgency(values[0]) : undefined;

        return (
          <MinistryCell
            value={primary?.name ?? row.primaryAgency}
            image={primary?.logo ?? row.primaryAgencyImage ?? undefined}
          />
        );
      }}
    />
  );
}

/**
 * The same badge-style status picker the CDC G-PSF progress report uses. Its
 * option list is already limited to In Progress, Solved and Not Addressed.
 */
export function StatusSelectCell({
  row,
  language,
  control,
}: {
  row: CdcIssueMatrixRow;
  language: WgIssuesLanguage;
  control?: StatusEditControl;
}) {
  const { data: statusOptions = [] } = useIssueStatusOptions();
  const isEditable = Boolean(control?.canEdit) && row.issueId > 0;

  if (!isEditable || !control) {
    return (
      <StatusBadge status={row.status as IssueStatus} language={language} />
    );
  }

  const handleChange = (statusName: string) => {
    if (statusName === row.status) return;

    const picked = statusOptions.find(
      (status) => status.name.toLowerCase() === statusName.toLowerCase(),
    );

    if (!picked) return;

    control.onSave(row, picked.id, picked.name);
  };

  return (
    <IssueStatusSelect
      value={row.status}
      disabled={control.isUpdating}
      onChange={handleChange}
      variant="badge"
      sx={{ width: "100%", minWidth: 0 }}
    />
  );
}
