import { Button, Dialog, i18nMessage } from "@govoplan/core-webui";

import { asArray, asRecord, formatDateTime, humanize } from "../utils/campaignView";
import { formatAddressList } from "./reviewFormatters";

export default function DeliveryJobDetailOverlay({
  detail,
  onClose
}: {
  detail: Record<string, unknown>;
  onClose: () => void;
}) {
  const job = asRecord(detail.job);
  const attempts = asRecord(detail.attempts);
  const smtpAttempts = asArray(attempts.smtp).map(asRecord);
  const imapAttempts = asArray(attempts.imap).map(asRecord);
  const issues = asArray(job.issues).map(asRecord);

  return (
    <Dialog
      open
      title="i18n:govoplan-campaign.delivery_job_details.0d9c5b1f"
      className="template-preview-modal"
      onClose={onClose}
      footer={
        <Button variant="primary" onClick={onClose}>
          i18n:govoplan-campaign.close.bbfa773e
        </Button>
      }
    >
      <dl className="detail-list">
        <div>
          <dt>i18n:govoplan-campaign.recipient.90343260</dt>
          <dd>
            {formatAddressList(asRecord(job.resolved_recipients).to) ||
              String(job.recipient_email ?? "-")}
          </dd>
        </div>
        <div>
          <dt>i18n:govoplan-campaign.subject.8d183dbd</dt>
          <dd>{String(job.subject ?? "-")}</dd>
        </div>
        <div>
          <dt>i18n:govoplan-campaign.smtp_status.6211cb2b</dt>
          <dd>{humanize(String(job.send_status ?? "-"))}</dd>
        </div>
        <div>
          <dt>i18n:govoplan-campaign.imap_status.dbc2e430</dt>
          <dd>{humanize(String(job.imap_status ?? "-"))}</dd>
        </div>
        {job.last_error ? (
          <div>
            <dt>i18n:govoplan-campaign.last_error.5e4df866</dt>
            <dd>{String(job.last_error)}</dd>
          </div>
        ) : null}
      </dl>
      {issues.length > 0 && (
        <AttemptList
          title="i18n:govoplan-campaign.message_issues.9092a7db"
          rows={issues}
        />
      )}
      <AttemptList
        title="i18n:govoplan-campaign.smtp_attempts.eb0a9ca6"
        rows={smtpAttempts}
        emptyText="i18n:govoplan-campaign.no_smtp_attempts_were_recorded.ff5b4c5d"
      />
      <AttemptList
        title="i18n:govoplan-campaign.imap_attempts.e815f0c2"
        rows={imapAttempts}
        emptyText="i18n:govoplan-campaign.no_imap_append_attempts_were_recorded_if_status_.12279f7e"
      />
    </Dialog>
  );
}

function AttemptList({
  title,
  rows,
  emptyText = "i18n:govoplan-campaign.no_rows.fdbeab75"
}: {
  title: string;
  rows: Record<string, unknown>[];
  emptyText?: string;
}) {
  return (
    <section className="review-flow-data-section">
      <h3>{title}</h3>
      {rows.length === 0 ? (
        <p className="muted small-note">{emptyText}</p>
      ) : (
        <dl className="detail-list">
          {rows.map((row, index) => (
            <div key={`${String(row.id ?? row.code ?? index)}:${index}`}>
              <dt>
                {String(
                  row.status ??
                    row.severity ??
                    row.code ??
                    i18nMessage("i18n:govoplan-campaign.value.44b8c76f", {
                      value0: index + 1
                    })
                )}
              </dt>
              <dd>
                <strong>
                  {String(
                    row.message ??
                      row.error_message ??
                      row.smtp_response ??
                      row.folder ??
                      row.path ??
                      "-"
                  )}
                </strong>
                {row.started_at || row.created_at ? (
                  <span className="muted">
                    {" · "}
                    {formatDateTime(String(row.started_at ?? row.created_at))}
                  </span>
                ) : null}
                {row.finished_at || row.updated_at ? (
                  <span className="muted">
                    {" → "}
                    {formatDateTime(String(row.finished_at ?? row.updated_at))}
                  </span>
                ) : null}
              </dd>
            </div>
          ))}
        </dl>
      )}
    </section>
  );
}
