import { STATEMENT_LOCALES } from "@accessibit/types";
import {
  LOCALIZED_FIELDS,
  REQUIRED_FIELD_IDS,
  futureDateFields,
  missingRequiredFields,
  type RequiredField,
  type StatementForm,
} from "./statementForm";

/**
 * The sections of the statement form (ACC-540), in the order the page shows
 * them. Each one opens and closes by itself and carries a mark: done, or
 * still to do.
 */
export const STATEMENT_SECTIONS = [
  "organization",
  "contact",
  "site",
  "conformance",
  "nonAccessible",
  "texts",
] as const;

export type StatementSection = (typeof STATEMENT_SECTIONS)[number];

export type SectionStatus = "done" | "todo";

/**
 * The section each field the statement may require is typed in. A `Record`
 * over `RequiredField`, so a field made required without a section fails the
 * build: a rejected save opens the section of the first gap before it moves
 * the focus there, and a field with no section would stay shut.
 */
const FIELD_SECTIONS: Record<RequiredField, StatementSection> = {
  orgName: "organization",
  employeesWithDisabilities: "organization",
  workstationsForDisabilities: "organization",
  contactEmail: "contact",
  firstName: "contact",
  lastName: "contact",
  siteCMS: "site",
  sitePublicationDate: "site",
  statementDate: "conformance",
  lawNonComplianceReason: "nonAccessible",
  disproportionateBurdenReason: "nonAccessible",
  outOfScopeContentReason: "nonAccessible",
};

export function sectionOfField(field: RequiredField): StatementSection {
  return FIELD_SECTIONS[field];
}

/** The form key of each field, by the id it has on the page. */
const FIELDS_BY_ID = new Map(
  (Object.entries(REQUIRED_FIELD_IDS) as Array<[RequiredField, string]>).map(
    ([field, id]) => [id, field] as const,
  ),
);

/**
 * The section a field sits in, from the id it has on the page; null for an
 * id that is not one of the form's.
 */
export function sectionOfFieldId(id: string): StatementSection | null {
  const field = FIELDS_BY_ID.get(id);
  return field ? FIELD_SECTIONS[field] : null;
}

/** The sections a list of fields falls in: once each, in form order. */
export function sectionsWithGaps(
  fields: readonly RequiredField[],
): StatementSection[] {
  const hit = new Set(fields.map(sectionOfField));
  return STATEMENT_SECTIONS.filter((section) => hit.has(section));
}

/**
 * What stops the statement from being generated: a required answer left
 * blank, or a date that says something has happened which has not yet.
 * `refusedDates` are the dates the server refused although this browser's
 * clock accepts them.
 */
function blockingFields(
  form: StatementForm,
  today: string,
  refusedDates: ReadonlySet<string> = new Set(),
): RequiredField[] {
  return [
    ...missingRequiredFields(form),
    ...futureDateFields(form, today),
    ...([...refusedDates] as RequiredField[]).filter(
      (field) => field in FIELD_SECTIONS,
    ),
  ];
}

/**
 * The free text is optional, in every language. Its section is done when
 * something is written and whatever is written is there in all three
 * languages: a text left out of one is published in English there, or not at
 * all when it is the English one that is missing.
 */
function textsDone(form: StatementForm): boolean {
  const written = (field: (typeof LOCALIZED_FIELDS)[number]) =>
    STATEMENT_LOCALES.filter(
      (locale) => form.localized[locale][field].trim().length > 0,
    ).length;
  const counts = LOCALIZED_FIELDS.map(written);
  return (
    counts.some((count) => count > 0) &&
    counts.every((count) => count === 0 || count === STATEMENT_LOCALES.length)
  );
}

/** The mark each section carries. */
export function sectionStatuses(
  form: StatementForm,
  today: string,
  refusedDates?: ReadonlySet<string>,
): Record<StatementSection, SectionStatus> {
  const open = new Set(
    sectionsWithGaps(blockingFields(form, today, refusedDates)),
  );
  const mark = (section: StatementSection): SectionStatus =>
    open.has(section) ? "todo" : "done";
  return {
    organization: mark("organization"),
    contact: mark("contact"),
    site: mark("site"),
    conformance: mark("conformance"),
    nonAccessible: mark("nonAccessible"),
    texts: textsDone(form) ? "done" : "todo",
  };
}

/**
 * The sections the form opens on: the ones with something missing, which is
 * where the work is. With nothing missing, the first, so the form does not
 * open as six closed rows. The texts never open it by themselves: they are
 * optional, and still to write on most statements.
 */
export function sectionsToOpen(
  form: StatementForm,
  today: string,
): StatementSection[] {
  const gaps = sectionsWithGaps(blockingFields(form, today));
  return gaps.length > 0 ? gaps : [STATEMENT_SECTIONS[0]];
}
