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";
import type { MinistryProgressReportDecisionRow } from "./progress-report-decisions-data";
import {
  agencyDisplayNameToSelectId,
  agencySelectIdToDisplayName,
  agencySelectIdToLogo,
  getEditableFieldValue,
} from "./progress-report-issue-agencies";

function normalizeAgencyKey(value: string): string {
  return value.trim().toLowerCase().replace(/[^a-z0-9]/g, "");
}

function isEmptyAgencyName(name?: string | null): boolean {
  const trimmed = name?.trim();
  return !trimmed || trimmed === "No data" || trimmed === "Not Uploaded" || trimmed === "-";
}

function findAgencyByDisplayName(
  name: string,
  agencies: Agency[],
): Agency | undefined {
  const trimmed = name.trim();
  const normalized = normalizeAgencyKey(trimmed);

  const exact = agencies.find((agency) => agency.name === trimmed);
  if (exact) return exact;

  const caseInsensitive = agencies.find(
    (agency) => agency.name.toLowerCase() === trimmed.toLowerCase(),
  );
  if (caseInsensitive) return caseInsensitive;

  return agencies.find((agency) => {
    const agencyKey = normalizeAgencyKey(agency.name);
    return (
      normalized === agencyKey ||
      normalized.includes(agencyKey) ||
      agencyKey.includes(normalized)
    );
  });
}

function toCustomAgencyId(name: string): string {
  return `custom:${normalizeAgencyKey(name)}`;
}

export function buildProgressReportDecisionAgencies(
  decision: MinistryProgressReportDecisionRow,
): Agency[] {
  const options = new Map<string, Agency>();

  for (const agency of dashboardIssueAgencies) {
    options.set(agency.id, agency);
  }

  const slots: Array<{ name: string; logo?: string | null }> = [
    { name: decision.primaryAgency, logo: decision.primaryAgencyLogo },
    { name: decision.secondAgency, logo: decision.secondAgencyLogo },
    { name: decision.thirdAgency, logo: decision.thirdAgencyLogo },
    { name: decision.fourthAgency, logo: decision.fourthAgencyLogo },
    { name: decision.fifthAgency, logo: decision.fifthAgencyLogo },
  ];

  for (const slot of slots) {
    if (isEmptyAgencyName(slot.name)) continue;

    const matched = findAgencyByDisplayName(slot.name, Array.from(options.values()));
    if (matched) {
      options.set(matched.id, matched);
      continue;
    }

    const customId = toCustomAgencyId(slot.name);
    options.set(customId, {
      id: customId,
      name: slot.name.trim(),
      logo: slot.logo?.trim() || "",
    });
  }

  return Array.from(options.values());
}

export {
  agencyDisplayNameToSelectId,
  agencySelectIdToDisplayName,
  agencySelectIdToLogo,
  getEditableFieldValue,
};
