/**
 * Tickets list panel (F2) — the project's ticket board in the sidebar.
 *
 * Filterable by status / priority / assignee + free-text search; each row shows
 * the `#ref`, title, status, priority and assigned agents. Clicking a row (or
 * its `#ref`) opens the detail via `onOpen`. Refreshes live on `Issue*` events
 * through {@link useTickets}.
 */

import { useState } from "react";

import type {
  Sprint,
  TicketPriority,
  TicketStatus,
  TicketSummary,
} from "@/domain";
import { Button, Input, Panel, Spinner, cn } from "@/shared";
import { useTickets } from "./useTickets";
import { useProjectAgents } from "./useProjectAgents";
import {
  PriorityBadge,
  StatusBadge,
  TICKET_PRIORITIES,
  TICKET_STATUSES,
  TicketRef,
  priorityLabel,
  statusLabel,
} from "./ticketMeta";

const selectClass = cn(
  "h-8 rounded-md bg-raised px-2 text-xs text-content",
  "border border-border outline-none transition-colors",
  "focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
);

export interface TicketsPanelProps {
  projectId: string;
  /** Opens the detail overlay for the given `#ref` (F7). */
  onOpen: (ref: string) => void;
}

export function TicketsPanel({ projectId, onOpen }: TicketsPanelProps) {
  const vm = useTickets(projectId);
  const { agents, nameOf } = useProjectAgents(projectId);
  const [showCreate, setShowCreate] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const [newPriority, setNewPriority] = useState<TicketPriority>("medium");

  const items = vm.list?.items ?? [];

  // Group tickets by sprint (ticket #10): one ordered section per sprint that
  // holds tickets, then a "Sans sprint" bucket. Tickets referencing an unknown
  // sprint fall into the bucket so none are ever hidden.
  const sprintIds = new Set(vm.sprints.map((s) => s.id));
  const grouped = vm.sprints
    .map((sprint) => ({
      sprint,
      tickets: items.filter((t) => t.sprintId === sprint.id),
    }))
    .filter((g) => g.tickets.length > 0);
  const noSprint = items.filter(
    (t) => !t.sprintId || !sprintIds.has(t.sprintId),
  );

  async function submitCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!newTitle.trim()) return;
    const created = await vm.create({
      title: newTitle.trim(),
      priority: newPriority,
    });
    if (created) {
      setNewTitle("");
      setNewPriority("medium");
      setShowCreate(false);
      onOpen(created.ref);
    }
  }

  return (
    <Panel
      title="Tickets"
      actions={
        <div className="flex items-center gap-1">
          <Button
            size="sm"
            variant="ghost"
            onClick={() => setShowCreate((v) => !v)}
          >
            {showCreate ? "Cancel" : "New"}
          </Button>
          <Button
            size="sm"
            variant="ghost"
            onClick={() => void vm.refresh()}
            loading={vm.busy}
          >
            Refresh
          </Button>
        </div>
      }
    >
      {vm.error && (
        <p
          role="alert"
          className="mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger"
        >
          {vm.error}
        </p>
      )}

      {showCreate && (
        <form
          onSubmit={submitCreate}
          className="mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2"
        >
          <Input
            aria-label="new ticket title"
            placeholder="Ticket title"
            value={newTitle}
            onChange={(e) => setNewTitle(e.target.value)}
          />
          <div className="flex items-center gap-2">
            <select
              aria-label="new ticket priority"
              className={selectClass}
              value={newPriority}
              onChange={(e) => setNewPriority(e.target.value as TicketPriority)}
            >
              {TICKET_PRIORITIES.map((p) => (
                <option key={p} value={p}>
                  {priorityLabel(p)}
                </option>
              ))}
            </select>
            <Button
              type="submit"
              size="sm"
              disabled={!newTitle.trim() || vm.busy}
            >
              Create
            </Button>
          </div>
        </form>
      )}

      {/* ── Filters ── */}
      <div className="mb-3 flex flex-col gap-2">
        <Input
          aria-label="search tickets"
          placeholder="Search title/description…"
          value={vm.query.text ?? ""}
          onChange={(e) =>
            vm.setQuery({ ...vm.query, text: e.target.value || undefined })
          }
        />
        <div className="flex flex-wrap items-center gap-2">
          <select
            aria-label="filter by status"
            className={selectClass}
            value={vm.query.status ?? ""}
            onChange={(e) =>
              vm.setQuery({
                ...vm.query,
                status: (e.target.value || undefined) as TicketStatus | undefined,
              })
            }
          >
            <option value="">All statuses</option>
            {TICKET_STATUSES.map((s) => (
              <option key={s} value={s}>
                {statusLabel(s)}
              </option>
            ))}
          </select>
          <select
            aria-label="filter by priority"
            className={selectClass}
            value={vm.query.priority ?? ""}
            onChange={(e) =>
              vm.setQuery({
                ...vm.query,
                priority: (e.target.value || undefined) as
                  | TicketPriority
                  | undefined,
              })
            }
          >
            <option value="">All priorities</option>
            {TICKET_PRIORITIES.map((p) => (
              <option key={p} value={p}>
                {priorityLabel(p)}
              </option>
            ))}
          </select>
          <select
            aria-label="filter by assignee"
            className={selectClass}
            value={vm.query.assignedAgentId ?? ""}
            onChange={(e) =>
              vm.setQuery({
                ...vm.query,
                assignedAgentId: e.target.value || undefined,
              })
            }
          >
            <option value="">All assignees</option>
            {agents.map((a) => (
              <option key={a.id} value={a.id}>
                {a.name}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* ── List, grouped by sprint (F2) ── */}
      {vm.busy && vm.list === null ? (
        <div className="flex items-center gap-2 text-sm text-muted">
          <Spinner size={14} />
          <span>Loading tickets…</span>
        </div>
      ) : items.length === 0 ? (
        <p className="text-sm text-muted">No tickets.</p>
      ) : (
        <div className="flex flex-col gap-4">
          {grouped.map((g) => (
            <SprintSection
              key={g.sprint.id}
              heading={g.sprint.name}
              count={g.tickets.length}
              tickets={g.tickets}
              sprints={vm.sprints}
              onOpen={onOpen}
              nameOf={nameOf}
              onAssignSprint={vm.assignSprint}
            />
          ))}
          {noSprint.length > 0 && (
            <SprintSection
              heading="Sans sprint"
              count={noSprint.length}
              tickets={noSprint}
              sprints={vm.sprints}
              onOpen={onOpen}
              nameOf={nameOf}
              onAssignSprint={vm.assignSprint}
            />
          )}
        </div>
      )}

      {vm.list?.nextCursor && (
        <div className="mt-3 flex justify-center">
          <Button
            size="sm"
            variant="ghost"
            loading={vm.busy}
            onClick={() =>
              vm.setQuery({
                ...vm.query,
                limit: (vm.query.limit ?? 100) + 100,
              })
            }
          >
            Load more
          </Button>
        </div>
      )}
    </Panel>
  );
}

/**
 * One sprint section (F2): a heading with the ticket count and the grouped
 * ticket rows. Each row carries a simple sprint selector wired to
 * `onAssignSprint` (assignment only — creation/reorder is ticket #11).
 */
function SprintSection({
  heading,
  count,
  tickets,
  sprints,
  onOpen,
  nameOf,
  onAssignSprint,
}: {
  heading: string;
  count: number;
  tickets: TicketSummary[];
  sprints: Sprint[];
  onOpen: (ref: string) => void;
  nameOf: (id: string) => string;
  onAssignSprint: (ref: string, sprintId: string | null) => void;
}) {
  return (
    <section aria-label={`sprint section ${heading}`}>
      <h3 className="mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted">
        {heading}
        <span className="rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted">
          {count}
        </span>
      </h3>
      <ul className="flex flex-col divide-y divide-border">
        {tickets.map((t) => (
          <li key={t.ref} className="py-2 first:pt-0 last:pb-0">
            <div className="flex items-start gap-2">
              <TicketRef ticketRef={t.ref} onOpen={onOpen} className="mt-0.5" />
              <button
                type="button"
                className="min-w-0 flex-1 text-left"
                onClick={() => onOpen(t.ref)}
              >
                <span className="block truncate text-sm font-medium text-content hover:underline">
                  {t.title}
                </span>
                {t.assignedAgentIds.length > 0 && (
                  <span className="mt-0.5 block truncate text-xs text-muted">
                    {t.assignedAgentIds.map(nameOf).join(", ")}
                  </span>
                )}
              </button>
              <span className="flex shrink-0 flex-col items-end gap-1">
                <StatusBadge status={t.status} />
                <PriorityBadge priority={t.priority} />
              </span>
            </div>
            <div className="mt-1 pl-6">
              <select
                aria-label={`sprint for ${t.ref}`}
                className={selectClass}
                value={t.sprintId ?? ""}
                onChange={(e) =>
                  onAssignSprint(t.ref, e.target.value || null)
                }
              >
                <option value="">— No sprint —</option>
                {sprints.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.name}
                  </option>
                ))}
              </select>
            </div>
          </li>
        ))}
      </ul>
    </section>
  );
}
