import { identityLabels, addressLabels } from "@/lib/myinfo-identity";
import type { MyinfoSnapshot } from "@/lib/application-assessment";
import styles from "./myinfo-records.module.css";

const shown = (value: string | null) =>
  value === null ? "Not available" : value;
const sourceLabels = {
  "1": "Government records",
  "2": "User-provided records",
  "3": "Source not applicable",
  "4": "Verified by Singpass",
};
function Source({
  record,
}: {
  record: Pick<MyinfoSnapshot["employer"], "source" | "lastUpdated">;
}) {
  return (
    <p className={styles.source}>
      {record.source ? sourceLabels[record.source] : "Source not supplied"}
      {record.lastUpdated ? ` · Updated ${record.lastUpdated}` : ""}
    </p>
  );
}
function Unavailable({
  status,
}: {
  status: "available" | "unavailable" | "invalid";
}) {
  return (
    <p>
      {status === "invalid"
        ? "These records could not be read reliably. Please provide supporting documents instead."
        : "Not available from Myinfo. You can provide details or supporting documents manually."}
    </p>
  );
}
export function MyinfoRecords({
  snapshot,
  demo = false,
}: {
  snapshot: MyinfoSnapshot;
  demo?: boolean;
}) {
  return (
    <section
      className={styles.records}
      aria-label="Myinfo identity, income and employment records"
    >
      <h3>Myinfo identity, income and employment records</h3>
      <p>
        Retrieved{" "}
        {snapshot.retrievedAt.replace("T", " ").replace(/\.\d+Z$/, " UTC")}
        {demo
          ? " · Synthetic demo records"
          : snapshot.environment === "staging"
            ? " · Staging test records"
            : ""}
        . These records are read-only.
      </p>
      {demo && (
        <p>
          <strong>Demo only:</strong> these records are synthetic and were not
          retrieved from Singpass. Source labels show how real records appear.
        </p>
      )}
      <p>
        Principal name: <strong>{shown(snapshot.principalName)}</strong>
      </p>
      {snapshot.identity && (
        <details>
          <summary>Identity and residency details</summary>
          <p>
            For borrower identification and application verification. Check
            these details against your identity documents. Missing details can
            be provided to our staff.
          </p>
          {(Object.keys(identityLabels) as (keyof typeof identityLabels)[]).map(
            (key) => {
              const record = snapshot.identity![key];
              if (!record) return null;
              return (
                <div key={key}>
                  <dl>
                    <div>
                      <dt>{identityLabels[key]}</dt>
                      <dd>
                        {record.status === "invalid"
                          ? "Could not be read reliably"
                          : shown(record.value)}
                        {record.code && record.code !== record.value
                          ? ` (${record.code})`
                          : ""}
                      </dd>
                    </div>
                  </dl>
                  <Source record={record} />
                </div>
              );
            },
          )}
          <h4>Registered address</h4>
          <Source record={snapshot.identity.regadd} />
          {snapshot.identity.regadd.status !== "available" ? (
            <Unavailable status={snapshot.identity.regadd.status} />
          ) : (
            <dl>
              {(Object.keys(addressLabels) as (keyof typeof addressLabels)[])
                .filter((key) => snapshot.identity!.regadd[key] !== null)
                .map((key) => (
                  <div key={key}>
                    <dt>{addressLabels[key]}</dt>
                    <dd>{snapshot.identity!.regadd[key]}</dd>
                  </div>
                ))}
            </dl>
          )}
        </details>
      )}
      <details>
        <summary>
          CPF contribution history ({snapshot.cpf.entries.length} records)
        </summary>
        <Source record={snapshot.cpf} />
        <p>
          Employment-related contributions received over up to 15 months.
          Contributions are not take-home salary. Non-employment contributions
          are not included.
        </p>
        {snapshot.cpf.status !== "available" ? (
          <Unavailable status={snapshot.cpf.status} />
        ) : snapshot.cpf.entries.length === 0 ? (
          <p>
            No contribution records were returned. This does not establish zero
            income.
          </p>
        ) : (
          <ol>
            {snapshot.cpf.entries.map((entry, index) => (
              <li key={index}>
                <dl>
                  <div>
                    <dt>Paid on</dt>
                    <dd>{shown(entry.paidOn)}</dd>
                  </div>
                  <div>
                    <dt>For month</dt>
                    <dd>{shown(entry.month)}</dd>
                  </div>
                  <div>
                    <dt>Employer</dt>
                    <dd>{shown(entry.employer)}</dd>
                  </div>
                  <div>
                    <dt>Contribution total (SGD)</dt>
                    <dd>{shown(entry.amount)}</dd>
                  </div>
                </dl>
              </li>
            ))}
          </ol>
        )}
      </details>
      <details>
        <summary>
          Income tax assessments ({snapshot.tax.entries.length} records)
        </summary>
        <Source record={snapshot.tax} />
        <p>
          Historical annual assessed income may differ from current monthly
          income.
        </p>
        {snapshot.tax.status !== "available" ? (
          <Unavailable status={snapshot.tax.status} />
        ) : snapshot.tax.entries.length === 0 ? (
          <p>
            No assessments were returned. This does not establish zero income.
          </p>
        ) : (
          <ol>
            {snapshot.tax.entries.map((entry, index) => (
              <li key={index}>
                <dl>
                  {Object.entries({
                    "Year of assessment": shown(entry.year),
                    Type: `${shown(entry.category)}${entry.taxClearance === "Y" ? " — Clearance" : ""}`,
                    "Tax clearance": shown(entry.taxClearance),
                    "Assessable income (SGD)": shown(entry.assessableIncome),
                    "Employment income (SGD)": shown(entry.employmentIncome),
                    "Trade income (SGD)": shown(entry.tradeIncome),
                    "Rent income (SGD)": shown(entry.rentIncome),
                    "Interest income (SGD)": shown(entry.interestIncome),
                  }).map(([label, value]) => (
                    <div key={label}>
                      <dt>{label}</dt>
                      <dd>{value}</dd>
                    </div>
                  ))}
                </dl>
              </li>
            ))}
          </ol>
        )}
      </details>
      <details>
        <summary>Employer and occupation</summary>
        <p>
          These fields are generally available for eligible FIN holders. CPF
          records may identify employers for citizens and permanent residents.
        </p>
        {(["employer", "occupation"] as const).map((key) => (
          <div key={key}>
            <h4>{key === "employer" ? "Employer" : "Occupation"}</h4>
            <Source record={snapshot[key]} />
            {snapshot[key].status === "available" ? (
              <p>{shown(snapshot[key].value)}</p>
            ) : (
              <Unavailable status={snapshot[key].status} />
            )}
          </div>
        ))}
      </details>
    </section>
  );
}
