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 { ViewMeetingSummaryIssueRow } from "@/features/ministry/meeting-summary/components/view-meeting-summary/view-meeting-summary-data";

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 === "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 buildMeetingSummaryIssueAgencies(
  issue: ViewMeetingSummaryIssueRow,
): 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: issue.secondAgency, logo: issue.secondAgencyLogo },
    { name: issue.thirdAgency, logo: issue.thirdAgencyLogo },
    { name: issue.fourthAgency, logo: issue.fourthAgencyLogo },
    { name: issue.fifthAgency, logo: issue.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 function agencyDisplayNameToSelectId(
  name: string,
  agencies: Agency[] = dashboardIssueAgencies,
): string {
  if (isEmptyAgencyName(name)) return "";

  const matched = findAgencyByDisplayName(name, agencies);
  if (matched) return matched.id;

  return toCustomAgencyId(name);
}

export function agencySelectIdToDisplayName(
  id: string,
  agencies: Agency[] = dashboardIssueAgencies,
): string {
  if (!id.trim()) return "";

  return agencies.find((agency) => agency.id === id)?.name ?? "";
}

export function agencySelectIdToLogo(
  id: string,
  agencies: Agency[] = dashboardIssueAgencies,
): string | null {
  if (!id.trim()) return null;

  const logo = agencies.find((agency) => agency.id === id)?.logo?.trim();
  return logo || null;
}

export function resolveAgencyLogoForDisplay(
  name: string,
  logo?: string | null,
): string | null {
  const trimmedLogo = logo?.trim();
  if (trimmedLogo) return trimmedLogo;

  if (isEmptyAgencyName(name)) return null;

  return findAgencyByDisplayName(name, dashboardIssueAgencies)?.logo ?? null;
}
