"use client";

import { useState } from "react";
import type { StateItem } from "@/lib/types";
import WaitlistForm, { type WaitlistText } from "./WaitlistForm";

export interface RequirementRow {
  stateCode: string;
  label: string;
  description: string;
  finding: string;
  status: string;
  statusLabel: string;
}

export interface SourceLink {
  stateCode: string;
  label: string;
  url: string;
  note: string;
}

export interface RegisterText {
  selectLabel: string;
  openPill: string;
  soonPill: string;
  soonGroupLabel: string;
  alertHtml: string;
  eyebrowTemplate: string;
  headingTemplate: string;
  introByState: Record<string, string>;
  colRequirement: string;
  colFinding: string;
  colStatus: string;
  questionsHeading: string;
  sourcesHeading: string;
  sourcesFootnote: string;
  soonTitleTemplate: string;
  soonHtml: string;
}

/** Requirements register: pick a state; a researched state shows its
 *  requirement table, open questions and official sources; any other state
 *  shows a "research in progress" panel with a waitlist form. */
export default function RequirementsRegister({
  states,
  rows,
  questions,
  sources,
  text,
  initialState,
  formKey,
  waitlist
}: {
  states: StateItem[];
  rows: RequirementRow[];
  questions: { stateCode: string; text: string }[];
  sources: SourceLink[];
  text: RegisterText;
  initialState: string;
  formKey: string;
  waitlist: WaitlistText;
}) {
  const [code, setCode] = useState(initialState);
  const state = states.find((s) => s.code === code);
  const name = state?.name || code.toUpperCase();
  const stateRows = rows.filter((r) => r.stateCode === code);
  const researched = stateRows.length > 0;
  const isOpen = state?.status === "open";
  const fill = (t: string) => t.split("{name}").join(name).split("{CODE}").join(code.toUpperCase()).split("{code}").join(code);
  const open = states.filter((s) => s.status === "open");
  const soon = states.filter((s) => s.status !== "open");

  return (
    <>
      <div className="state-selector-bar">
        <label>{text.selectLabel}</label>
        <select value={code} onChange={(e) => setCode(e.target.value)}>
          {open.map((s) => (
            <option key={s.code} value={s.code}>
              {s.name}: {text.openPill}
            </option>
          ))}
          <optgroup label={text.soonGroupLabel}>
            {soon.map((s) => (
              <option key={s.code} value={s.code}>
                {s.name}
              </option>
            ))}
          </optgroup>
        </select>
        <span className={`state-status-pill ${isOpen ? "open" : "soon"}`}>{isOpen ? `● ${text.openPill}` : text.soonPill}</span>
      </div>

      {researched ? (
        <div className="req-panel active">
          {text.alertHtml && (
            <div className="alert alert-warning">
              <span />
              <div dangerouslySetInnerHTML={{ __html: text.alertHtml }} />
            </div>
          )}
          <div className="section-label">{fill(text.eyebrowTemplate)}</div>
          <h2 className="section-title">{fill(text.headingTemplate)}</h2>
          {text.introByState[code] && (
            <p style={{ color: "var(--gray-600)", marginBottom: 24 }} dangerouslySetInnerHTML={{ __html: text.introByState[code] || "" }} />
          )}
          <div className="req-table-wrap">
            <table className="req-table">
              <thead>
                <tr>
                  <th>{text.colRequirement}</th>
                  <th>{text.colFinding}</th>
                  <th>{text.colStatus}</th>
                </tr>
              </thead>
              <tbody>
                {stateRows.map((r, i) => (
                  <tr key={i}>
                    <td>
                      <div className="req-label">{r.label}</div>
                      <div className="req-detail">{r.description}</div>
                    </td>
                    <td data-label={text.colFinding}>
                      <div className="req-detail">{r.finding}</div>
                    </td>
                    <td data-label={text.colStatus}>
                      <span className={`status-badge ${r.status}`}>{r.statusLabel}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {questions.some((q) => q.stateCode === code) && (
            <div className="gap-checklist">
              <h4>{fill(text.questionsHeading)}</h4>
              {questions
                .filter((q) => q.stateCode === code)
                .map((q, i) => (
                  <div className="gap-item" key={i}>
                    <span className="gap-icon">?</span> {q.text}
                  </div>
                ))}
            </div>
          )}
          {sources.some((s) => s.stateCode === code) && (
            <div style={{ background: "white", border: "1px solid var(--gray-200)", borderRadius: "var(--radius-lg)", padding: 20, boxShadow: "var(--shadow)" }}>
              <h4 style={{ fontWeight: 700, color: "var(--navy)", marginBottom: 12 }}>{fill(text.sourcesHeading)}</h4>
              <ul style={{ listStyle: "none", fontSize: ".875rem", color: "var(--gray-600)" }}>
                {sources
                  .filter((s) => s.stateCode === code)
                  .map((s, i) => (
                    <li key={i} style={{ marginBottom: 8 }}>
                      <a href={s.url} target="_blank" rel="noopener noreferrer" style={{ color: "var(--navy)", fontWeight: 600 }}>
                        {s.label}
                      </a>
                      {s.note ? `, ${s.note}` : ""}
                    </li>
                  ))}
              </ul>
              {text.sourcesFootnote && <p style={{ fontSize: ".78rem", color: "var(--gray-400)", marginTop: 8 }}>{text.sourcesFootnote}</p>}
            </div>
          )}
        </div>
      ) : (
        <div className="req-panel active">
          <div className="coming-soon-panel">
            <h3>{fill(text.soonTitleTemplate)}</h3>
            <div dangerouslySetInnerHTML={{ __html: text.soonHtml }} />
            <WaitlistForm key={code} formKey={formKey} fixedState={name} text={{ ...waitlist, source: `${waitlist.source} (${name})` }} />
          </div>
        </div>
      )}
    </>
  );
}
