"use client";

import { useMemo, useState } from "react";
import type { NoticeItem } from "@/lib/types";
import NoticeCard, { type NoticeCardLabels } from "@/components/notices/NoticeCard";

interface Option {
  value: string;
  label: string;
}

function uniqueOptions(items: NoticeItem[], key: (n: NoticeItem) => string, label: (n: NoticeItem) => string): Option[] {
  const seen = new Map<string, string>();
  for (const n of items) {
    const k = key(n);
    if (k && !seen.has(k)) seen.set(k, label(n));
  }
  return [...seen.entries()].map(([value, l]) => ({ value, label: l }));
}

/** Home page "Recent Notices": state filter over a notice grid. */
export function RecentNotices({
  notices,
  labels,
  filterLabel,
  allStatesLabel,
  stateOptions,
  emptyText
}: {
  notices: NoticeItem[];
  labels: NoticeCardLabels;
  filterLabel: string;
  allStatesLabel: string;
  stateOptions: Option[];
  emptyText: string;
}) {
  const [state, setState] = useState("all");
  const opts = stateOptions.length ? stateOptions : uniqueOptions(notices, (n) => n.stateCode, (n) => n.stateName);
  const visible = notices.filter((n) => state === "all" || n.stateCode === state).length;
  return (
    <>
      <div className="filters-bar" style={{ marginTop: 28 }}>
        <span className="filter-label">{filterLabel}</span>
        <select className="filter-select" aria-label={filterLabel.replace(/:$/, "")} value={state} onChange={(e) => setState(e.target.value)}>
          <option value="all">{allStatesLabel}</option>
          {opts.map((o) => (
            <option key={o.value} value={o.value}>
              {o.label}
            </option>
          ))}
        </select>
      </div>
      <div className="notice-cascade">
        {notices.map((n) => (
          <NoticeCard key={n.slug} notice={n} look="list" labels={labels} hidden={state !== "all" && n.stateCode !== state} />
        ))}
      </div>
      {visible === 0 && emptyText && <div className="no-results msc-empty">{emptyText}</div>}
    </>
  );
}

export interface DirectoryLabels {
  panelHeading: string;
  search: string;
  searchPlaceholder: string;
  state: string;
  allStates: string;
  county: string;
  allCounties: string;
  facility: string;
  allFacilities: string;
  status: string;
  allStatuses: string;
  clear: string;
  showing: string;
  showingOne: string;
  noResults: string;
  clearInline: string;
}

/** Directory page: search + state / county / facility / status filters.
 *  Every filter's options come from the notices themselves, so a new county
 *  or facility type appears as soon as a notice using it is published. */
export function NoticeDirectory({
  notices,
  labels,
  cardLabels,
  stateOptions
}: {
  notices: NoticeItem[];
  labels: DirectoryLabels;
  cardLabels: NoticeCardLabels;
  /** Every state and territory (from the CMS states collection); falls back
   *  to the states that have notices. */
  stateOptions?: Option[];
}) {
  const [q, setQ] = useState("");
  const [state, setState] = useState("all");
  const [county, setCounty] = useState("all");
  const [facility, setFacility] = useState("all");
  const [status, setStatus] = useState("all");

  const states = useMemo(
    () => (stateOptions && stateOptions.length ? stateOptions : uniqueOptions(notices, (n) => n.stateCode, (n) => n.stateName)),
    [notices, stateOptions]
  );
  const counties = useMemo(
    () => uniqueOptions(notices, (n) => n.countyKey, (n) => n.county).sort((a, b) => a.label.localeCompare(b.label)),
    [notices]
  );
  const facilities = useMemo(() => uniqueOptions(notices, (n) => n.facilityKey, (n) => n.facilityShort), [notices]);
  const statuses = useMemo(
    () =>
      uniqueOptions(
        notices,
        (n) => n.status,
        (n) => (n.status === "scheduled" ? cardLabels.scheduled : cardLabels.published)
      ),
    [notices, cardLabels]
  );

  const visible = notices.map((n) => {
    const text = [n.title, n.summary, n.organization, n.county, n.stateName, n.facilityType, n.noticeNumber].join(" ").toLowerCase();
    return (
      (!q || text.includes(q.toLowerCase())) &&
      (state === "all" || n.stateCode === state) &&
      (county === "all" || n.countyKey === county) &&
      (facility === "all" || n.facilityKey === facility) &&
      (status === "all" || n.status === status)
    );
  });
  const count = visible.filter(Boolean).length;

  const clear = () => {
    setQ("");
    setState("all");
    setCounty("all");
    setFacility("all");
    setStatus("all");
  };

  const select = (label: string, value: string, set: (v: string) => void, all: string, opts: Option[]) => (
    <div className="filter-group">
      <label>{label}</label>
      <select className="filter-select" aria-label={label} value={value} onChange={(e) => set(e.target.value)}>
        <option value="all">{all}</option>
        {opts.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </div>
  );

  return (
    <div className="directory-layout">
      <aside className="filters-panel">
        <h3>{labels.panelHeading}</h3>
        <div className="filter-group">
          <label>{labels.search}</label>
          <input type="text" className="filter-input" placeholder={labels.searchPlaceholder} value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
        {select(labels.state, state, setState, labels.allStates, states)}
        {select(labels.county, county, setCounty, labels.allCounties, counties)}
        {select(labels.facility, facility, setFacility, labels.allFacilities, facilities)}
        {select(labels.status, status, setStatus, labels.allStatuses, statuses)}
        <button type="button" className="clear-filters-btn" onClick={clear}>
          {labels.clear}
        </button>
      </aside>
      <div>
        <div className="results-header">
          <span className="results-count">
            {(count === 1 ? labels.showingOne : labels.showing).replace("{count}", String(count))}
          </span>
        </div>
        <div className="notice-cascade">
          {notices.map((n, i) => (
            <NoticeCard key={n.slug} notice={n} look="list" labels={cardLabels} hidden={!visible[i]} />
          ))}
        </div>
        {count === 0 && (
          <div className="no-results">
            <p>
              {labels.noResults}{" "}
              <button
                type="button"
                onClick={clear}
                style={{ background: "none", border: "none", color: "var(--navy)", fontWeight: 700, cursor: "pointer", fontFamily: "'Inter',sans-serif" }}
              >
                {labels.clearInline}
              </button>
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
