import { Button } from "@code/ui/components/button";
import {
  AlertTriangle,
  Check,
  ChevronRight,
  FileCode2,
  Hammer,
  Play,
  RotateCcw,
  ScrollText,
  Sparkles,
  X,
} from "lucide-react";
import { useState } from "react";

import { changedFilesFor } from "@/lib/workspace/types";
import type { WorkRecord, WorkspaceState } from "@/lib/workspace/types";

interface WorkCardProps {
  readonly onSourceSelect: (rawText: string) => void;
  readonly work: WorkRecord;
  readonly workspace: WorkspaceState;
}

const starterDefinition = (work: WorkRecord) => ({
  acceptanceCriteria: ["The requested outcome is observable and documented"],
  affectedUsers: ["Project users"],
  assumptions: [],
  constraints: [],
  desiredOutcome: work.objective,
  inScope: [work.objective],
  outOfScope: ["Unrelated product changes"],
  problem: work.objective,
  questions: [],
  requiredArtifacts: ["Simulation activity and terminal outcome"],
  risk: "medium",
});

const starterDesign = (work: WorkRecord) => ({
  architectureSummary:
    "Validate the approved Definition, then exercise one deterministic fake slice.",
  callFlowDelta: [
    "Work -> Run -> Attempt -> normalized events -> terminal outcome",
  ],
  concerns: [],
  evidenceRequirements: ["Terminal Run classification"],
  fileTreeDelta: [],
  impactMap: {
    files: [],
    modules: [],
    risks: [],
    summary: "Compact vertical-slice simulation",
  },
  invariants: [
    "Simulation never claims implementation",
    "Every Attempt reaches a terminal classification",
  ],
  keyInterfaces: ["HarnessRuntime", "AttemptOutcome"],
  slices: [
    {
      codeBoundaries: ["workExecution"],
      dependsOn: [],
      evidenceRequirements: ["Normalized activity events"],
      id: "deterministic-simulation",
      objective: work.objective,
      observableBehavior: "A terminal fake Run is visible",
      reviewRequired: false,
      title: "Deterministic simulation",
      verification: ["Run completes with a terminal classification"],
    },
  ],
  tradeoffs: ["Fake runtime proves contract before sandbox integration"],
});

// oxlint-disable-next-line complexity -- this card intentionally coordinates review actions and run evidence.
export const WorkCard = ({
  onSourceSelect,
  work,
  workspace,
}: WorkCardProps) => {
  const [sourcesOpen, setSourcesOpen] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [logsOpen, setLogsOpen] = useState(false);
  const sources = work.signals.flatMap((signal) => signal.sources);
  const [latestRun] = work.runs;
  const openQuestions =
    work.definition?.questions?.filter((question) => question.status === "open")
      .length ?? 0;

  return (
    <article className="border border-[#d7d3c7] bg-[#fffefa] p-4 text-[#20201d] shadow-[0_10px_30px_rgba(30,30,20,0.06)]">
      <div className="flex items-start gap-3">
        <span className="grid size-8 shrink-0 place-items-center bg-[#dcff68]">
          <Sparkles className="size-4" />
        </span>
        <div className="min-w-0 flex-1">
          <p className="text-[10px] font-semibold uppercase text-[#65713a]">
            Proposed Work
          </p>
          <h2 className="mt-1 text-[15px] font-semibold leading-5">
            {work.title}
          </h2>
          <p className="mt-1.5 text-[13px] leading-5 text-[#626057]">
            {work.objective}
          </p>
        </div>
      </div>
      <button
        className="mt-3 flex w-full items-center justify-between border-t border-[#e7e3d9] pt-3 text-left text-xs text-[#69675e]"
        onClick={() => setSourcesOpen((open) => !open)}
        type="button"
      >
        <span>
          {sources.length} exact source{" "}
          {sources.length === 1 ? "message" : "messages"}
        </span>
        <ChevronRight
          className={`size-4 transition-transform ${sourcesOpen ? "rotate-90" : ""}`}
        />
      </button>
      <button
        className="mt-2 flex w-full items-center justify-between border-t border-[#e7e3d9] pt-3 text-left text-xs font-medium text-[#20201d]"
        onClick={() => setExpanded((open) => !open)}
        type="button"
      >
        <span>{expanded ? "Hide Work details" : "Open Work details"}</span>
        <ChevronRight
          className={`size-4 transition-transform ${expanded ? "rotate-90" : ""}`}
        />
      </button>
      {sourcesOpen ? (
        <div className="mt-3 space-y-2">
          {sources.map((source) => (
            <button
              className="flex w-full items-start gap-2 border-l-2 border-[#a8b750] bg-[#f4f2e9] px-3 py-2 text-left text-xs leading-5 hover:bg-[#ece9dd]"
              key={source.messageId}
              onClick={() => onSourceSelect(source.rawText)}
              type="button"
            >
              <span className="min-w-0 flex-1">{source.rawText}</span>
            </button>
          ))}
        </div>
      ) : null}
      {expanded ? (
        <div className="mt-4 space-y-4 border-t border-[#e7e3d9] pt-4 text-xs">
          <section>
            <p className="font-semibold uppercase tracking-wide text-[#65713a]">
              Outcome
            </p>
            <p className="mt-1 leading-5 text-[#626057]">{work.objective}</p>
            <p className="mt-2 text-[#747168]">
              Risk: {work.definition?.risk ?? "not defined"}
            </p>
            {openQuestions > 0 ? (
              <p className="mt-1 text-amber-800">
                {openQuestions} open question(s)
              </p>
            ) : null}
            <div className="mt-2 flex flex-wrap gap-2">
              {work.status === "proposed" ? (
                <Button
                  size="sm"
                  onClick={() => void workspace.requestDefinition(work._id)}
                >
                  <Sparkles className="size-3.5" /> Define
                </Button>
              ) : null}
              {work.status === "defining" ? (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() =>
                    void workspace.saveDefinition(
                      work._id,
                      starterDefinition(work)
                    )
                  }
                >
                  <Hammer className="size-3.5" /> Save definition
                </Button>
              ) : null}
              {work.status === "awaiting-definition-approval" &&
              work.definitionVersion ? (
                <Button
                  size="sm"
                  onClick={() =>
                    void workspace.approveDefinition(
                      work._id,
                      work.definitionVersion as number
                    )
                  }
                >
                  <Check className="size-3.5" /> Approve
                </Button>
              ) : null}
            </div>
          </section>
          <section>
            <p className="font-semibold uppercase tracking-wide text-[#65713a]">
              Design
            </p>
            <p className="mt-1 leading-5 text-[#626057]">
              {work.design?.architectureSummary ?? "No Design Packet yet."}
            </p>
            {work.design?.slices?.map((item) => (
              <p className="mt-1 text-[#747168]" key={item.id}>
                {item.title}: {item.observableBehavior}
              </p>
            ))}
            <div className="mt-2 flex flex-wrap gap-2">
              {work.status === "designing" ? (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() =>
                    void workspace.saveDesign(work._id, starterDesign(work))
                  }
                >
                  <Hammer className="size-3.5" /> Save design
                </Button>
              ) : null}
              {work.status === "awaiting-design-approval" &&
              work.definitionApprovalVersion &&
              work.designVersion ? (
                <Button
                  size="sm"
                  onClick={() =>
                    void workspace.approveDesign(
                      work._id,
                      work.definitionApprovalVersion as number,
                      work.designVersion as number
                    )
                  }
                >
                  <Check className="size-3.5" /> Approve design
                </Button>
              ) : null}
            </div>
          </section>
          <section>
            <p className="font-semibold uppercase tracking-wide text-[#65713a]">
              Build
            </p>
            {workspace.operationError ? (
              <p className="mt-2 flex items-start gap-1.5 border border-red-300 bg-red-50 px-2 py-1.5 text-red-800">
                <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
                <span className="min-w-0 flex-1 leading-5">
                  {workspace.operationError.message}
                </span>
                <button
                  aria-label="Dismiss error"
                  className="shrink-0"
                  onClick={() => workspace.clearOperationError()}
                  type="button"
                >
                  <X className="size-3.5" />
                </button>
              </p>
            ) : null}
            {latestRun ? (
              <div className="mt-1 space-y-2 text-[#626057]">
                <p className="leading-5">
                  {latestRun.executionKind === "real"
                    ? "AgentOS"
                    : "Simulation"}{" "}
                  run {latestRun.status}:{" "}
                  {latestRun.terminalSummary ??
                    latestRun.terminalClassification ??
                    "activity is still arriving"}
                </p>
                {latestRun.baseRevision ? (
                  <p className="font-mono text-[10px] text-[#747168]">
                    {latestRun.baseRevision.slice(0, 8)} →{" "}
                    {latestRun.candidateRevision?.slice(0, 8) ?? "working"}
                  </p>
                ) : null}
                {latestRun.artifacts?.map((artifact) => (
                  <div key={artifact._id} className="space-y-1">
                    <p className="font-medium">
                      {artifact.uri ? (
                        <a
                          className="underline"
                          href={artifact.uri}
                          rel="noreferrer"
                          target="_blank"
                        >
                          {artifact.title}
                        </a>
                      ) : (
                        artifact.title
                      )}
                    </p>
                    {changedFilesFor(artifact).length > 0 ? (
                      <ul className="space-y-0.5">
                        {changedFilesFor(artifact).map((file) => (
                          <li
                            className="flex items-start gap-1.5 font-mono text-[11px] leading-5 text-[#747168]"
                            key={file}
                          >
                            <FileCode2 className="mt-0.5 size-3 shrink-0 text-[#9a985f]" />
                            <span className="min-w-0 break-all">{file}</span>
                          </li>
                        ))}
                      </ul>
                    ) : null}
                  </div>
                ))}
                {latestRun.attemptEvents &&
                latestRun.attemptEvents.length > 0 ? (
                  <div className="space-y-1">
                    {(logsOpen
                      ? latestRun.attemptEvents
                      : latestRun.attemptEvents.slice(-3)
                    ).map((item) => (
                      <p
                        className="border-l-2 border-[#b8c760] pl-2 leading-5"
                        key={item._id}
                      >
                        {item.message}
                      </p>
                    ))}
                    {latestRun.attemptEvents.length > 3 ? (
                      <button
                        className="flex items-center gap-1 font-medium text-[#65713a] hover:underline"
                        onClick={() => setLogsOpen((open) => !open)}
                        type="button"
                      >
                        <ScrollText className="size-3.5" />
                        {logsOpen
                          ? "Show recent activity"
                          : `Show full activity log (${latestRun.attemptEvents.length})`}
                        <ChevronRight
                          className={`size-3.5 transition-transform ${logsOpen ? "rotate-90" : ""}`}
                        />
                      </button>
                    ) : null}
                  </div>
                ) : null}
              </div>
            ) : (
              <p className="mt-1 text-[#747168]">No implementation Run yet.</p>
            )}
            <div className="mt-2 flex flex-wrap gap-2">
              {work.status === "ready" ? (
                <>
                  <Button
                    size="sm"
                    disabled={!workspace.projectGitConnection}
                    onClick={() => void workspace.startExecution(work._id)}
                  >
                    <Play className="size-3.5" /> Run
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() =>
                      void workspace.startSimulation(work._id, "success")
                    }
                  >
                    <Play className="size-3.5" /> Simulate
                  </Button>
                </>
              ) : null}
              {latestRun?.status === "running" ? (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() =>
                    void (latestRun.executionKind === "real"
                      ? workspace.cancelExecution(latestRun._id)
                      : workspace.cancelSimulation(latestRun._id))
                  }
                >
                  <X className="size-3.5" /> Cancel
                </Button>
              ) : null}
              {latestRun?.executionKind !== "real" &&
              latestRun?.status === "terminal" &&
              latestRun.terminalClassification === "RetryableFailure" ? (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => void workspace.retrySimulation(latestRun._id)}
                >
                  <RotateCcw className="size-3.5" /> Retry
                </Button>
              ) : null}
            </div>
          </section>
        </div>
      ) : null}
    </article>
  );
};
