/**
 * Ticket AI assistant chat panel (ticket #8, F2).
 *
 * Consumes {@link useTicketAssistant} to drive a ticket-scoped assistant: pick
 * an AI profile, open a read-only session bound to this ticket, then converse.
 * The assistant can only read files and edit *this* ticket — its edits refresh
 * the ticket automatically (see {@link useTicketDetail}). Purely presentational:
 * all session/streaming logic lives in the hook.
 */

import { useEffect, useRef, useState } from "react";

import { Button, Spinner, cn } from "@/shared";
import { useTicketAssistant } from "./useTicketAssistant";

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

export interface TicketAssistantPanelProps {
  projectId: string;
  ticketRef: string;
}

export function TicketAssistantPanel({
  projectId,
  ticketRef,
}: TicketAssistantPanelProps) {
  const vm = useTicketAssistant(projectId, ticketRef);
  const [profileId, setProfileId] = useState("");
  const [draft, setDraft] = useState("");

  // Auto-scroll the transcript to the newest content as it streams in.
  const scrollRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [vm.turns]);

  const open = vm.sessionId !== null;

  function submit() {
    const text = draft.trim();
    if (!text || vm.busy) return;
    void vm.send(text);
    setDraft("");
  }

  return (
    <div className="flex flex-col gap-3">
      {!open ? (
        // ── Session opener ──
        <div className="flex flex-wrap items-center gap-2">
          <select
            aria-label="profil de l'assistant"
            className={selectClass}
            value={profileId}
            disabled={vm.opening || vm.profiles.length === 0}
            onChange={(e) => setProfileId(e.target.value)}
          >
            <option value="">
              {vm.profiles.length === 0
                ? "Aucun profil disponible"
                : "Choisir un profil IA…"}
            </option>
            {vm.profiles.map((p) => (
              <option key={p.id} value={p.id}>
                {p.name}
              </option>
            ))}
          </select>
          <Button
            size="sm"
            disabled={!profileId || vm.opening}
            loading={vm.opening}
            onClick={() => void vm.open(profileId)}
          >
            Ouvrir la conversation
          </Button>
        </div>
      ) : (
        // ── Live conversation ──
        <div className="flex flex-col gap-3">
          <div className="flex items-center justify-between gap-2">
            <span className="text-xs text-muted">
              Conversation ouverte — l'assistant peut lire le projet et éditer ce
              ticket.
            </span>
            <Button
              size="sm"
              variant="ghost"
              disabled={vm.busy}
              onClick={() => void vm.close()}
            >
              Fermer la conversation
            </Button>
          </div>

          <div
            ref={scrollRef}
            className="flex max-h-96 min-h-32 flex-col gap-2 overflow-auto rounded-md border border-border bg-raised/40 p-3"
          >
            {vm.turns.length === 0 ? (
              <p className="m-auto text-xs text-muted">
                Démarrez la conversation en décrivant ce que l'assistant doit
                faire sur ce ticket.
              </p>
            ) : (
              vm.turns.map((turn, i) => (
                <div
                  key={i}
                  className={cn(
                    "flex",
                    turn.role === "user" ? "justify-end" : "justify-start",
                  )}
                >
                  <div
                    className={cn(
                      "max-w-[85%] whitespace-pre-wrap break-words rounded-lg px-3 py-2 text-sm",
                      turn.role === "user"
                        ? "bg-primary/15 text-content"
                        : "bg-surface text-content",
                    )}
                  >
                    {turn.text}
                    {turn.pending && (
                      <span className="ml-1 inline-flex items-center align-middle text-muted">
                        <Spinner size={12} />
                      </span>
                    )}
                  </div>
                </div>
              ))
            )}
          </div>

          <div className="flex items-end gap-2">
            <textarea
              aria-label="message à l'assistant"
              className={cn(
                "min-h-10 flex-1 resize-none rounded-md bg-raised p-2 text-sm text-content",
                "border border-border outline-none transition-colors",
                "focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
              )}
              rows={2}
              placeholder="Votre message…"
              value={draft}
              disabled={vm.busy}
              onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  submit();
                }
              }}
            />
            <Button
              size="sm"
              disabled={!draft.trim() || vm.busy}
              loading={vm.busy}
              onClick={submit}
            >
              Envoyer
            </Button>
          </div>
        </div>
      )}

      {vm.error && (
        <p role="alert" className="text-xs text-danger">
          {vm.error}
        </p>
      )}
    </div>
  );
}
