import type { ConProfile, ConStatus } from "@/lib/types";
import { formatDate } from "@/lib/content";
import { NamedIcon } from "@/components/icons";

export interface ConLabels {
  status: Record<ConStatus | "unknown", string>;
  confidence: Record<string, string>;
  scope: string;
  notice: string;
  noticeMissing: string;
  noticeBy: string;
  noticeByValue: Record<string, string>;
  agency: string;
  law: string;
  notes: string;
  sources: string;
  reviewed: string;
  lastSearched: string;
  disclaimer: string;
}

export const DEFAULT_CON_LABELS: ConLabels = {
  status: {
    full: "Certificate of Need state",
    repealing: "CON program being phased out",
    limited: "Limited CON program",
    none: "No CON program",
    "": "Research in progress",
    unknown: "Research in progress"
  },
  confidence: {
    primary: "Checked against official state sources",
    secondary: "From secondary sources; verify with the state",
    unverified: "Not yet verified"
  },
  scope: "What needs a CON",
  notice: "Public notice rule",
  noticeMissing: "Not yet confirmed. Ask the state agency what notice it requires before you publish.",
  noticeBy: "Who publishes it",
  noticeByValue: {
    applicant: "The applicant places a paid legal notice in a newspaper.",
    agency: "The state agency publishes the notice itself; the applicant does not place an ad.",
    unclear: "The rule requires a newspaper notice but does not say who places it."
  },
  agency: "Agency",
  law: "Law",
  notes: "Notes",
  sources: "Sources",
  reviewed: "Last reviewed",
  lastSearched: "Last searched",
  disclaimer: "Research findings, not legal advice. Confirm the requirements for your filing with your attorney or the state agency."
};

/** Short tag for menus and cards. */
export function conShortLabel(status: ConStatus): string {
  return { full: "CON", repealing: "CON (phasing out)", limited: "Limited CON", none: "No CON", "": "" }[status];
}

function host(u: string): string {
  try {
    return new URL(u).hostname.replace(/^www\./, "");
  } catch {
    return u;
  }
}

function Ext({ href, children }: { href: string; children: React.ReactNode }) {
  return href ? (
    <a href={href} target="_blank" rel="noopener noreferrer">
      {children}
    </a>
  ) : (
    <>{children}</>
  );
}

/**
 * A state's Certificate of Need requirements, from its "states" entry:
 * whether it runs a CON program, what needs a CON, what its rules say about
 * the public notice (the part this paper prints), the agency and the law,
 * with sources and how well the research is verified.
 */
export default function ConProfileSection({ name, con, labels }: { name: string; con: ConProfile; labels: ConLabels }) {
  const key = con.status || "unknown";
  const icon = con.status === "none" ? "info" : con.status === "" ? "search" : "scales";
  return (
    <div className={`con-profile con-${key}`}>
      <div className="con-status">
        <NamedIcon name={icon} size={20} />
        <div>
          <strong>{labels.status[key]}</strong>
          {(con.lastSearched || con.reviewed) && (
            <span className="con-searched">
              {labels.lastSearched}: {formatDate(con.lastSearched || con.reviewed, true)}
            </span>
          )}
          {con.confidence && <span className="con-confidence">{labels.confidence[con.confidence] || con.confidence}</span>}
        </div>
      </div>
      <dl className="con-facts">
        {con.scope && (
          <div>
            <dt>{labels.scope}</dt>
            <dd>{con.scope}</dd>
          </div>
        )}
        {con.status !== "none" && (
          <div className="con-notice">
            <dt>{labels.notice}</dt>
            <dd>
              {con.noticeRule || labels.noticeMissing}
              {con.noticeCitation && (
                <span className="con-cite">
                  <Ext href={con.noticeUrl}>{con.noticeCitation}</Ext>
                </span>
              )}
            </dd>
          </div>
        )}
        {con.status !== "none" && con.noticeBy && labels.noticeByValue[con.noticeBy] && (
          <div className={`con-by con-by-${con.noticeBy}`}>
            <dt>{labels.noticeBy}</dt>
            <dd>{labels.noticeByValue[con.noticeBy]}</dd>
          </div>
        )}
        {con.agency && (
          <div>
            <dt>{labels.agency}</dt>
            <dd>
              <Ext href={con.agencyUrl}>{con.agency}</Ext>
            </dd>
          </div>
        )}
        {con.statute && (
          <div>
            <dt>{labels.law}</dt>
            <dd>
              <Ext href={con.statuteUrl}>{con.statute}</Ext>
            </dd>
          </div>
        )}
        {/* con.notes are the researchers' working notes: kept in Aggie for staff, not shown here. */}
      </dl>
      {con.status === "none" && con.sources.length > 0 && (
        <div className="con-sources-list">
          <h4>{labels.sources}</h4>
          <ul>
            {con.sources.map((u) => (
              <li key={u}>
                <a href={u} target="_blank" rel="noopener noreferrer">
                  {u.replace(/^https?:\/\/(www\.)?/, "")}
                </a>
              </li>
            ))}
          </ul>
        </div>
      )}
      {con.status !== "none" && con.sources.length > 0 && (
        <div className="con-sources">
          <span>{labels.sources}:</span>
          {con.sources.map((u) => (
            <a key={u} href={u} target="_blank" rel="noopener noreferrer">
              {host(u)}
            </a>
          ))}
        </div>
      )}
      <p className="con-disclaimer">
        {con.reviewed && (
          <>
            {labels.reviewed} {formatDate(con.reviewed, true)}.{" "}
          </>
        )}
        {labels.disclaimer.split("{name}").join(name)}
      </p>
    </div>
  );
}
