/**
 * `SkillsPanel` — feature component for skill management (L12).
 *
 * Pure presentation: all behaviour comes from {@link useSkills}. Styled with
 * `@/shared` design system tokens; no inline styles.
 *
 * Provides, per scope (Global + Project):
 * - Skill list (name + scope)
 * - "New skill" button that opens {@link SkillEditor} in create-mode
 * - Per-skill "Edit" (opens the editor in edit-mode) and "Delete"
 *
 * Skills are assigned to agents from the `AgentsPanel`, not here — this panel is
 * the authoring surface only ("no direct invoke": a skill is never run from the
 * UI, only injected into an agent's convention file at activation).
 */

import { useState } from "react";

import type { Skill, SkillScope } from "@/domain";
import { Button, Panel, Spinner } from "@/shared";
import { SkillEditor } from "./SkillEditor";
import { useSkills } from "./useSkills";

export interface SkillsPanelProps {
  /** The project whose skills to manage. */
  projectId: string;
}

/** Editor open-state: "create" or edit-mode for a specific skill. */
type EditorState = { mode: "create" } | { mode: "edit"; skill: Skill };

export function SkillsPanel({ projectId }: SkillsPanelProps) {
  const vm = useSkills(projectId);

  const [editorState, setEditorState] = useState<EditorState | null>(null);
  const [editorBusy, setEditorBusy] = useState(false);

  async function handleSave(name: string, content: string, scope: SkillScope) {
    if (!editorState) return;
    setEditorBusy(true);
    try {
      if (editorState.mode === "create") {
        await vm.createSkill({ name, content, scope });
      } else {
        await vm.updateSkill(editorState.skill.scope, editorState.skill.id, content);
      }
      setEditorState(null);
    } finally {
      setEditorBusy(false);
    }
  }

  function renderList(scope: SkillScope, skills: Skill[]) {
    return (
      <div className="p-4">
        {skills.length === 0 ? (
          <p className="text-sm text-muted">No {scope} skills yet.</p>
        ) : (
          <ul className="flex flex-col divide-y divide-border">
            {skills.map((s) => (
              <li
                key={s.id}
                className="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0"
              >
                <span className="min-w-0 font-medium text-content">{s.name}</span>
                <div className="flex items-center gap-1.5 shrink-0">
                  <Button
                    size="sm"
                    variant="ghost"
                    aria-label={`edit skill ${s.name}`}
                    disabled={vm.busy}
                    onClick={() => setEditorState({ mode: "edit", skill: s })}
                  >
                    Edit
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    aria-label={`delete skill ${s.name}`}
                    disabled={vm.busy}
                    onClick={() => void vm.deleteSkill(s.scope, s.id)}
                    className="text-danger hover:text-danger"
                  >
                    Delete
                  </Button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    );
  }

  return (
    <>
      {/* ── Fullscreen skill editor overlay ── */}
      {editorState !== null && (
        <SkillEditor
          skill={editorState.mode === "edit" ? editorState.skill : null}
          onSave={handleSave}
          onClose={() => setEditorState(null)}
          busy={editorBusy}
        />
      )}

      <Panel title="Skills" className="flex flex-col gap-0">
        {vm.error && (
          <p
            role="alert"
            className="mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger"
          >
            {vm.error}
          </p>
        )}

        {/* ── Create button ── */}
        <div className="flex items-center justify-between border-b border-border px-4 py-3">
          <h4 className="text-xs font-semibold uppercase tracking-wide text-faint">
            Skills
          </h4>
          <div className="flex items-center gap-2">
            {vm.busy && <Spinner size={14} />}
            <Button
              type="button"
              variant="primary"
              aria-label="create skill"
              disabled={vm.busy}
              onClick={() => setEditorState({ mode: "create" })}
            >
              New skill
            </Button>
          </div>
        </div>

        {/* ── Project skills ── */}
        <div className="border-b border-border px-4 pt-3">
          <h5 className="text-xs font-semibold uppercase tracking-wide text-faint">
            Project
          </h5>
        </div>
        {renderList("project", vm.projectSkills)}

        {/* ── Global skills ── */}
        <div className="border-y border-border px-4 pt-3">
          <h5 className="text-xs font-semibold uppercase tracking-wide text-faint">
            Global
          </h5>
        </div>
        {renderList("global", vm.globalSkills)}
      </Panel>
    </>
  );
}
