"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import type { PublicForm, PublicFormField } from "@/lib/types";
import { useFormSubmit } from "@/lib/forms";
import { NamedIcon } from "@/components/icons";
import { SchemaField, layoutRows, type FieldExtras } from "./SchemaFields";

export interface InputStep {
  title: string;
  desc: string;
  summaryTitle?: string;
  fields: string[];
  rows?: string[][];
  alertHtml?: string;
  alertType?: "info" | "warning";
  afterHtml?: string;
  countField?: string;
}

export interface InfoStep {
  title: string;
  desc: string;
  html: string;
  nextLabel?: string;
  backLabel?: string;
}

export interface WizardConfig {
  progressLabels: string[];
  steps: InputStep[];
  review: { title: string; desc: string; ackHtml: string; submitLabel: string; ackMissing: string };
  afterSubmit: InfoStep[];
  final: { title: string; referencePrefix: string; html: string; links: { label: string; href: string; gold?: boolean }[] };
  continueLabel: string;
  backLabel: string;
  charsLabel: string;
  source: string;
  /** Ask Aggie for the next 5-digit request number for this form (00001, 00002...). */
  numberRequests?: boolean;
  /** The form field holding the state; its rules are shown once one is picked. */
  stateField?: string;
  stateRulesLabels?: { heading: string; by: string; rule: string; more: string; none: string };
}

/** One state's notice rules, shown under the state choice. */
export interface StateRule {
  name: string;
  slug: string;
  status: string;
  statusLabel: string;
  noticeRule: string;
  noticeCitation: string;
  noticeBy: string;
  href: string;
}

/**
 * The multi-step "Submit a CON Notice" request. Steps 1-4 collect the CMS
 * form's fields (grouped per step by the block config), step 5 reviews and
 * sends the request to Aggie (saved as a form submission + CRM lead for NSP
 * Foundation), and the remaining steps walk through what happens next.
 */
export default function SubmitWizard({
  form,
  config,
  extras,
  stateRules = []
}: {
  form: PublicForm;
  config: WizardConfig;
  extras: FieldExtras;
  stateRules?: StateRule[];
}) {
  const total = config.steps.length + 1 + config.afterSubmit.length + 1;
  const [step, setStep] = useState(1);
  // A required choice with only one option (e.g. the only open state) starts selected.
  const [values, setValues] = useState<Record<string, string>>(() =>
    Object.fromEntries(
      form.fields
        .filter((f) => f.isRequired && f.fieldType.toLowerCase() === "select" && (f.options || []).length === 1)
        .map((f) => [f.fieldKey, (f.options || [])[0] as string])
    )
  );
  const [ack, setAck] = useState(false);
  const [ackError, setAckError] = useState(false);
  const cardRef = useRef<HTMLDivElement>(null);
  const { state, error, send, resultId, requestNumber } = useFormSubmit(form.formKey);

  const byKey = (k: string) => form.fields.find((f) => f.fieldKey === k);
  const set = (k: string, v: string) => setValues((o) => ({ ...o, [k]: v }));

  // Arriving from a state page (/submit?state=<slug>) picks that state.
  const stateKey = config.stateField || "state";
  useEffect(() => {
    const slug = new URLSearchParams(window.location.search).get("state");
    if (!slug) return;
    const rule = stateRules.find((r) => r.slug === slug);
    const opts = (byKey(stateKey)?.options || []).map(String);
    const match = rule && opts.find((o) => o === rule.name || o.startsWith(rule.name + " "));
    if (match) set(stateKey, match);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const chosenRule = stateRules.find((r) => values[stateKey] === r.name || (values[stateKey] || "").startsWith(r.name + " "));
  const RL = config.stateRulesLabels || {
    heading: "{name}: what the rules say",
    by: "Who publishes the notice",
    rule: "Public notice rule",
    more: "See {name}'s full requirements",
    none: "{name} has no Certificate of Need program on record. You can still publish a notice here."
  };
  const fillName = (t: string) => t.split("{name}").join(chosenRule?.name || "");

  const go = (n: number) => {
    setStep(n);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const validateCurrent = (): boolean => {
    const el = cardRef.current;
    if (!el) return true;
    const inputs = Array.from(el.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>("input,select,textarea"));
    for (const i of inputs) {
      if (!i.checkValidity()) {
        i.reportValidity();
        return false;
      }
    }
    return true;
  };

  const next = () => {
    if (validateCurrent()) go(step + 1);
  };

  const reviewStep = config.steps.length + 1;
  const finalStep = total;

  const submit = async () => {
    if (!ack) {
      setAckError(true);
      return;
    }
    const payload: Record<string, unknown> = { ...values, source: config.source };
    if (config.numberRequests) payload.requestNumber = "auto";
    for (const s of config.steps) {
      if (s.countField && values[s.countField] !== undefined) {
        payload[`${s.countField}Length`] = `${(values[s.countField] || "").length} characters`;
      }
    }
    if (await send(payload)) go(reviewStep + 1);
  };

  const progress = (
    <div className="progress-bar">
      <div className="steps-track">
        {config.progressLabels.map((label, i) => {
          const n = i + 1;
          const cls = n < step ? "dot done" : n === step ? "dot current" : "dot";
          return (
            <div className="step-dot" key={n}>
              <div className={cls}>{n < step && n <= reviewStep ? <NamedIcon name="check" size={14} strokeWidth={3} /> : n}</div>
              <div className={`step-label${n === step ? " current" : ""}`}>{label}</div>
            </div>
          );
        })}
      </div>
    </div>
  );

  const renderFields = (s: InputStep) => {
    const fields = s.fields.map(byKey).filter((f): f is PublicFormField => !!f);
    return layoutRows(fields, s.rows || []).map((group) => {
      const items = group.map((f) => (
        <div key={f.fieldKey} style={{ display: "contents" }}>
          <SchemaField field={f} extras={extras} value={values[f.fieldKey] ?? ""} onChange={(v) => set(f.fieldKey, v)} />
          {s.countField === f.fieldKey && (
            <div className="char-count" style={{ marginTop: -10, marginBottom: 16 }}>
              {(values[f.fieldKey] || "").length.toLocaleString()} {config.charsLabel}
            </div>
          )}
        </div>
      ));
      return group.length > 1 ? (
        <div className="form-row" key={group.map((g) => g.fieldKey).join("-")}>
          {items}
        </div>
      ) : (
        items
      );
    });
  };

  let body: React.ReactNode = null;
  if (step <= config.steps.length) {
    const s = config.steps[step - 1]!;
    body = (
      <div className="form-card" ref={cardRef}>
        <h2>{s.title}</h2>
        <p className="step-desc">{s.desc}</p>
        {s.alertHtml && (
          <div className={`alert alert-${s.alertType || "warning"}`}>
            <span />
            <div dangerouslySetInnerHTML={{ __html: s.alertHtml }} />
          </div>
        )}
        {renderFields(s)}
        {s.fields.includes(stateKey) && chosenRule && (
          <div className="state-rules-panel" role="note" aria-live="polite">
            <h3>{fillName(RL.heading)}</h3>
            <p className="srp-status">{chosenRule.statusLabel}</p>
            {chosenRule.status === "none" ? (
              <p>{fillName(RL.none)}</p>
            ) : (
              <>
                {chosenRule.noticeBy && (
                  <p>
                    <strong>{RL.by}:</strong> {chosenRule.noticeBy}
                  </p>
                )}
                {chosenRule.noticeRule && (
                  <p className="srp-rule">
                    <strong>{RL.rule}:</strong> {chosenRule.noticeRule}
                    {chosenRule.noticeCitation && <span className="srp-cite"> ({chosenRule.noticeCitation})</span>}
                  </p>
                )}
              </>
            )}
            <Link href={chosenRule.href}>{fillName(RL.more)}</Link>
          </div>
        )}
        {s.afterHtml && <div dangerouslySetInnerHTML={{ __html: s.afterHtml }} />}
        <div className="btn-row">
          {step > 1 ? (
            <button type="button" className="btn-back" onClick={() => go(step - 1)}>
              {config.backLabel}
            </button>
          ) : (
            <span />
          )}
          <button type="button" className="btn-next" onClick={next}>
            {config.continueLabel}
          </button>
        </div>
      </div>
    );
  } else if (step === reviewStep) {
    body = (
      <div className="form-card">
        <h2>{config.review.title}</h2>
        <p className="step-desc">{config.review.desc}</p>
        <div>
          {config.steps.map((s) => (
            <div className="review-section" key={s.title}>
              <h4>{s.summaryTitle || s.title}</h4>
              {s.fields.map((k) => {
                const f = byKey(k);
                if (!f || f.fieldType === "heading") return null;
                const v = values[k] || "";
                const shown = s.countField === k ? `${v.length.toLocaleString()} ${config.charsLabel}` : v || "Not provided";
                return (
                  <div className="review-row" key={k}>
                    <span className="review-label">{f.label}</span>
                    <span className="review-value">{shown}</span>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
        <div className="proto-ack">
          <input
            type="checkbox"
            id="protoAck"
            checked={ack}
            onChange={(e) => {
              setAck(e.target.checked);
              setAckError(false);
            }}
          />
          <label htmlFor="protoAck" dangerouslySetInnerHTML={{ __html: config.review.ackHtml }} />
        </div>
        {ackError && <p className="msc-form-error">{config.review.ackMissing}</p>}
        {state === "error" && <p className="msc-form-error">{error}</p>}
        <div className="btn-row">
          <button type="button" className="btn-back" onClick={() => go(step - 1)}>
            {config.backLabel}
          </button>
          <button type="button" className="btn-submit" onClick={submit} disabled={state === "sending"}>
            {state === "sending" ? "Submitting…" : config.review.submitLabel}
          </button>
        </div>
      </div>
    );
  } else if (step < finalStep) {
    const s = config.afterSubmit[step - reviewStep - 1]!;
    body = (
      <div className="form-card">
        <h2>{s.title}</h2>
        <p className="step-desc">{s.desc}</p>
        <div dangerouslySetInnerHTML={{ __html: s.html }} />
        <div className="btn-row">
          {s.backLabel && step - 1 > reviewStep ? (
            <button type="button" className="btn-back" onClick={() => go(step - 1)}>
              {s.backLabel}
            </button>
          ) : (
            <span />
          )}
          <button type="button" className="btn-next" onClick={() => go(step + 1)} style={{ background: "var(--gold)", color: "var(--navy)" }}>
            {s.nextLabel || config.continueLabel}
          </button>
        </div>
      </div>
    );
  } else {
    const ref = `${config.final.referencePrefix}${requestNumber || (resultId ? resultId.padStart(5, "0") : "")}`;
    body = (
      <div className="form-card">
        <div className="success-screen">
          <h2>{config.final.title}</h2>
          <p style={{ fontSize: "1rem", color: "var(--navy)", fontWeight: 600, marginBottom: 12 }}>{ref}</p>
          <div dangerouslySetInnerHTML={{ __html: config.final.html }} />
          <div style={{ marginTop: 24, display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
            {config.final.links.map((l) => (
              <Link
                key={l.href}
                href={l.href}
                className="btn-next"
                style={{
                  textDecoration: "none",
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 8,
                  ...(l.gold ? { background: "var(--gold)", color: "var(--navy)" } : {})
                }}
              >
                {l.label}
              </Link>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="submit-wrap">
      {progress}
      {body}
    </div>
  );
}
