/**
 * 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 { useEffect, useState } from "react";

import type { Sprint, TicketPriority, TicketSummary } from "@/domain";
import { Button, Input, Panel, Spinner, cn } from "@/shared";
import { useTickets } from "./useTickets";
import { useProjectAgents } from "./useProjectAgents";
import { SprintManager } from "./SprintManager";
import { SprintPicker } from "./SprintPicker";
import { TicketFacetsBar } from "./TicketFacetsBar";
import {
  PriorityBadge,
  StatusBadge,
  TICKET_PRIORITIES,
  TicketRef,
  priorityLabel,
} 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, loaded: agentsLoaded } = useProjectAgents(projectId);

  // Reconcile a *restored* assignee filter (ticket #29) against the live roster:
  // once the agents are known, an assignee that no longer exists is dropped
  // (which also clears it from persisted storage via `useTickets`). Guarded on
  // `agentsLoaded` so a still-valid assignee is never cleared during the load
  // window when the roster is momentarily empty.
  useEffect(() => {
    if (!agentsLoaded) return;
    const id = vm.query.assignedAgentId;
    if (id && !agents.some((a) => a.id === id)) {
      const { assignedAgentId: _drop, ...rest } = vm.query;
      vm.setQuery(rest);
    }
  }, [agentsLoaded, agents, vm.query, vm.setQuery]);
  const [showCreate, setShowCreate] = useState(false);
  const [showSprints, setShowSprints] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const [newPriority, setNewPriority] = useState<TicketPriority>("medium");
  // Sprint chosen for the new ticket (`null` ⇒ "Sans sprint"), and whether its
  // picker popup is open (#38).
  const [newSprint, setNewSprint] = useState<Sprint | null>(null);
  const [showSprintPicker, setShowSprintPicker] = useState(false);

  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) return; // create failed; `vm.error` already carries the reason.
    // Two-step assignment (#38): the ticket exists either way. If the sprint
    // assignment fails, the ticket is kept and `vm.assignSprint` surfaces the
    // failure via `vm.error` — we never lose the created ticket.
    if (newSprint) {
      await vm.assignSprint(created.ref, newSprint.id);
    }
    setNewTitle("");
    setNewPriority("medium");
    setNewSprint(null);
    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"
            aria-label="manage sprints"
            onClick={() => setShowSprints(true)}
          >
            Sprints
          </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>
          {/* Sprint field (#38): opens the SprintPicker popup; shows the choice
              (or "Sans sprint"). */}
          <div className="flex items-center gap-2">
            <span className="text-xs text-muted">Sprint</span>
            <Button
              type="button"
              size="sm"
              variant="ghost"
              aria-label="choose sprint for new ticket"
              disabled={vm.busy}
              onClick={() => setShowSprintPicker(true)}
              className="border border-border"
            >
              {newSprint ? newSprint.name : "Sans sprint"}
            </Button>
          </div>
        </form>
      )}

      {/* ── Filters ── */}
      <div className="mb-3 flex flex-col gap-2">
        {/* Shared search + status/priority facets (#18). Assignee stays here —
            it needs the project agent roster and is out of the picker's scope. */}
        <TicketFacetsBar
          text={vm.query.text ?? ""}
          onTextChange={(text) =>
            vm.setQuery({ ...vm.query, text: text || undefined })
          }
          statuses={vm.query.statuses ?? []}
          priorities={vm.query.priorities ?? []}
          onToggleStatus={vm.toggleStatus}
          onTogglePriority={vm.togglePriority}
          onClearFacets={vm.clearFacets}
          sort={vm.query.sort}
          onSortChange={(sort) => {
            const { sort: _drop, ...rest } = vm.query;
            vm.setQuery(sort ? { ...rest, sort } : rest);
          }}
        />
        <div className="flex flex-wrap items-center gap-2">
          <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>
      )}

      {showSprints && (
        <SprintManager
          projectId={projectId}
          vm={vm}
          onClose={() => setShowSprints(false)}
        />
      )}

      {/* Sprint picker for the create form (#38) — chrome-level, nested z-index,
          focus-trapped. Selecting an entry sets the pending sprint and closes. */}
      <SprintPicker
        open={showSprintPicker}
        projectId={projectId}
        selectedSprintId={newSprint?.id ?? null}
        title="Sprint du nouveau ticket"
        onSelect={(sprint) => setNewSprint(sprint)}
        onClose={() => setShowSprintPicker(false)}
      />
    </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>
  );
}
