"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import type { StateItem } from "@/lib/types";
import { NamedIcon } from "@/components/icons";

/** Not-yet-open states are grouped in this order (repealing joins "full"). */
const GROUPS = ["full", "limited", "unknown", "none"];

function fill(template: string, name: string): string {
  return template.split("{name}").join(name);
}

/** Home-page "Select Your State" card: a select of every state from the CMS
 *  `states` collection, a status note that follows the choice, and Go.
 *  look "box" is the front-page sidebar box (heading, subhead, stacked select
 *  and button); the default is the older hero card. */
export default function StateSelectorHero({
  states,
  heading,
  description,
  placeholder,
  goLabel,
  soonGroupLabel,
  openSuffix,
  defaultNoteHtml,
  openNoteTemplate,
  soonNoteTemplate,
  pickFirstMessage,
  look = "hero",
  groupLabels = {}
}: {
  states: StateItem[];
  heading: string;
  description: string;
  placeholder: string;
  goLabel: string;
  soonGroupLabel: string;
  openSuffix: string;
  defaultNoteHtml: string;
  openNoteTemplate: string;
  soonNoteTemplate: string;
  pickFirstMessage: string;
  look?: "hero" | "box";
  /** Optgroup labels by CON status (full, repealing, limited, none, unknown);
   *  when given, the not-yet-open states are grouped by them, CON states first. */
  groupLabels?: Record<string, string>;
}) {
  const router = useRouter();
  const [value, setValue] = useState("");
  const grouped = Object.keys(groupLabels).length > 0;
  const open = grouped ? [] : states.filter((s) => s.status === "open");
  const soon = grouped ? states : states.filter((s) => s.status !== "open");
  const chosen = states.find((s) => s.slug === value);

  const onChange = (v: string) => {
    setValue(v);
    const s = states.find((x) => x.slug === v);
    window.dispatchEvent(new CustomEvent("msc:state-selected", { detail: s?.code || "" }));
  };

  const go = () => {
    if (!chosen) {
      window.alert(pickFirstMessage);
      return;
    }
    router.push(chosen.href);
  };

  let note: { dot: string; html: string } = { dot: "green", html: defaultNoteHtml };
  if (chosen) {
    note =
      chosen.status === "open"
        ? { dot: "green", html: fill(openNoteTemplate, chosen.name) }
        : { dot: "gray", html: fill(soonNoteTemplate, chosen.name) };
  }

  const select = (
    <select className="state-select-dropdown" value={value} onChange={(e) => onChange(e.target.value)} aria-label={heading}>
      <option value="">{placeholder}</option>
      {open.map((s) => (
        <option key={s.slug} value={s.slug}>
          {s.name}
          {openSuffix}
        </option>
      ))}
      {grouped
        ? GROUPS.map((g) => {
            const items = soon.filter((s) => (s.con.status || "unknown") === g || (g === "full" && s.con.status === "repealing"));
            return items.length > 0 ? (
              <optgroup key={g} label={groupLabels[g] || soonGroupLabel}>
                {items.map((s) => (
                  <option key={s.slug} value={s.slug}>
                    {s.name}
                  </option>
                ))}
              </optgroup>
            ) : null;
          })
        : soon.length > 0 && (
            <optgroup label={soonGroupLabel}>
              {soon.map((s) => (
                <option key={s.slug} value={s.slug}>
                  {s.name}
                </option>
              ))}
            </optgroup>
          )}
    </select>
  );
  const goButton = (
    <button type="button" className="state-go-btn" onClick={go}>
      {goLabel}
      <NamedIcon name="arrow-right" size={15} strokeWidth={2.4} />
    </button>
  );
  const status = (
    <div className="state-status-note">
      <span className={`status-dot ${note.dot}`} />
      <span dangerouslySetInnerHTML={{ __html: note.html }} />
    </div>
  );

  if (look === "box") {
    return (
      <div className="state-selector-box">
        <div className="box-headline">
          <span>{heading}</span>
          <NamedIcon name="pin" size={16} strokeWidth={2.2} />
        </div>
        {description && <div className="box-subhead">{description}</div>}
        {select}
        {goButton}
        {status}
      </div>
    );
  }

  return (
    <div className="state-selector-hero">
      <h3>{heading}</h3>
      <p>{description}</p>
      <div className="state-select-row">
        {select}
        {goButton}
      </div>
      {status}
    </div>
  );
}
