// Requirements pane — list of extracted requirements with traceability +
// unsupported flags. Click a requirement's traced block → focus that block
// in Model. Re-running Analyze MERGES; new and deprecated requirements
// surface for the user to keep or discard.

"use client";

import { useMemo } from "react";
import { PaneFrame } from "../PaneFrame";
import { PaneEmpty } from "../PaneEmpty";
import { PaneDrawer } from "../PaneDrawer";
import { StatusChip } from "../StatusChip";
import { useAnalysis, type ClientRequirement } from "../../../lib/workspace/analysisStore";
import { useOpenPanes } from "../../../lib/workspace/openPanesStore";
import { useModelStore } from "../../../lib/sync/ModelStore";

interface RequirementsPaneProps {
  index: number;
  onClose: () => void;
}

export function RequirementsPane({ index, onClose }: RequirementsPaneProps) {
  const { requirements, analyze, inFlight } = useAnalysis();
  const { pushFrom } = useOpenPanes();
  const { model } = useModelStore();
  const running = inFlight.has("requirements") || inFlight.has("all");

  const kept = useMemo(
    () => requirements.filter(r => r.status === "accepted"),
    [requirements]
  );
  const pending = useMemo(
    () => requirements.filter(r => r.status !== "accepted"),
    [requirements]
  );
  const unsupportedCount = kept.filter(r => r.unsupported).length;

  const labelOf = (id: string) => model.blocks.find(b => b.id === id)?.label ?? id;

  const subtitle =
    requirements.length === 0
      ? "no requirements yet"
      : pending.length > 0
        ? `${kept.length} kept · ${pending.length} pending`
        : unsupportedCount > 0
          ? `${kept.length} total · ${unsupportedCount} unsupported`
          : `${kept.length} total · all traced`;

  const right = (
    <div className="pane-controls">
      <button
        type="button"
        className="pane-action"
        onClick={() => void analyze("requirements")}
        disabled={running}
      >
        {running ? "Analyzing…" : "Analyze"}
      </button>
    </div>
  );

  const renderRow = (r: ClientRequirement) => (
    <RequirementItem
      key={r.id}
      req={r}
      labelOf={labelOf}
      onOpenSelf={() => pushFrom(index, { kind: "requirement", id: r.id })}
      onJumpToBlock={id => pushFrom(index, { kind: "block", id })}
      onJumpToTerm={id => pushFrom(index, { kind: "term", id })}
    />
  );

  return (
    <PaneFrame title="Requirements" subtitle={subtitle} right={right} onClose={onClose}>
      <div className="pane-drawer-stack">
        <div className="pane-drawer-main">
          {kept.length === 0 && pending.length === 0 ? (
            <PaneEmpty
              title="No requirements yet"
              hint={
                <>
                  Requirements are extracted from sentences in your prose that say the system
                  <em> must / should / needs to</em>. Run <strong>Analyze</strong> to scan.
                </>
              }
              action={{
                label: running ? "Analyzing…" : "Run Analyze →",
                onClick: () => void analyze("requirements"),
                disabled: running,
              }}
            />
          ) : kept.length === 0 ? (
            <PaneEmpty
              title="Nothing kept yet"
              hint="Review the pending requirements below."
            />
          ) : (
            <ul className="req-list">{kept.map(renderRow)}</ul>
          )}
        </div>

        {pending.length > 0 ? (
          <PaneDrawer
            title="Pending review"
            count={pending.length}
            tone="pending"
            defaultOpen
          >
            <ul className="req-list">{pending.map(renderRow)}</ul>
          </PaneDrawer>
        ) : null}
      </div>
    </PaneFrame>
  );
}

interface RequirementItemProps {
  req: ClientRequirement;
  labelOf: (id: string) => string;
  onOpenSelf: () => void;
  onJumpToBlock: (id: string) => void;
  onJumpToTerm: (id: string) => void;
}

function RequirementItem({ req, labelOf, onOpenSelf, onJumpToBlock, onJumpToTerm }: RequirementItemProps) {
  const { decideRequirement } = useAnalysis();
  return (
    <li
      className={`req-row req-status-${req.status} ${req.unsupported ? "req-row-unsupported" : ""}`}
      onClick={onOpenSelf}
      role="button"
      tabIndex={0}
      onKeyDown={e => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          onOpenSelf();
        }
      }}
    >
      <div className="req-row-head">
        <span className="req-tag">{req.tag}</span>
        <span className="req-row-meta">
          <ReqStatusBadge status={req.status} />
          {req.unsupported ? <StatusChip variant="warn" label="unsupported" /> : null}
        </span>
      </div>
      <div className="req-text">{req.text}</div>
      {req.linkedTermId ? (
        <button
          type="button"
          className="req-term-link"
          onClick={e => {
            e.stopPropagation();
            onJumpToTerm(req.linkedTermId!);
          }}
          title="Open concept detail"
        >
          ↪ concept
        </button>
      ) : null}
      {req.tracedToIds.length > 0 ? (
        <div className="req-traced" onClick={e => e.stopPropagation()}>
          Traced to:{" "}
          {req.tracedToIds.map((id, i) => (
            <button
              key={id}
              type="button"
              className="req-traced-link"
              onClick={e => {
                e.stopPropagation();
                onJumpToBlock(id);
              }}
            >
              {labelOf(id)}
              {i < req.tracedToIds.length - 1 ? ", " : ""}
            </button>
          ))}
        </div>
      ) : null}
      {req.status !== "accepted" ? (
        <div className="term-decision-row" onClick={e => e.stopPropagation()}>
          <button
            type="button"
            className="term-decide term-decide-keep"
            onClick={e => {
              e.stopPropagation();
              void decideRequirement(req.id, "keep");
            }}
          >
            Keep
          </button>
          <button
            type="button"
            className="term-decide term-decide-discard"
            onClick={e => {
              e.stopPropagation();
              void decideRequirement(req.id, "discard");
            }}
          >
            Discard
          </button>
        </div>
      ) : null}
    </li>
  );
}

function ReqStatusBadge({ status }: { status: ClientRequirement["status"] }) {
  if (status === "suggested") return <StatusChip variant="suggested" />;
  if (status === "deprecated") return <StatusChip variant="deprecated" />;
  return null;
}
