"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { postMessageAction } from "@/lib/support/actions";
import { relativeTime } from "@/lib/support/relative-time";
import type { TicketThread } from "@/lib/support/types";
import { cn } from "@/lib/utils";
import { PriorityBadge, StatusBadge } from "./ticket-badges";

export function SupportTicketThread({ thread }: { thread: TicketThread }) {
  const router = useRouter();
  const { ticket, messages } = thread;
  const [content, setContent] = useState("");
  const [pending, startTransition] = useTransition();
  const resolved = ticket.status === "resolved";

  function send() {
    if (!content.trim()) return;
    startTransition(async () => {
      try {
        await postMessageAction(ticket.id, content);
        setContent("");
        router.refresh();
      } catch (err) {
        toast.error(err instanceof Error ? err.message : "Erreur");
      }
    });
  }

  return (
    <div className="space-y-6">
      <header className="flex flex-wrap items-center gap-3">
        <h1 className="min-w-0 flex-1 text-xl font-semibold">{ticket.title}</h1>
        <PriorityBadge priority={ticket.priority} />
        <StatusBadge status={ticket.status} />
      </header>

      <ul className="space-y-4">
        {messages.map((m) => {
          const staff = m.senderType === "staff";
          return (
            <li
              key={m.id}
              className={cn(
                "flex flex-col",
                staff ? "items-start" : "items-end",
              )}
            >
              <div
                className={cn(
                  "max-w-[85%] rounded-lg px-4 py-2.5 text-sm whitespace-pre-wrap",
                  staff
                    ? "bg-primary text-primary-foreground"
                    : "bg-muted text-foreground",
                )}
              >
                {m.content}
              </div>
              <span className="mt-1 px-1 text-xs text-muted-foreground">
                {m.senderName ?? (staff ? "Support" : "Vous")} ·{" "}
                {relativeTime(m.createdAt)}
              </span>
            </li>
          );
        })}
      </ul>

      {resolved ? (
        <div className="rounded-lg border border-dashed bg-muted/40 p-4 text-center text-sm text-muted-foreground">
          Ce ticket est résolu.
        </div>
      ) : (
        <div className="space-y-2">
          <Textarea
            value={content}
            rows={3}
            placeholder="Écris ta réponse…"
            onChange={(e) => setContent(e.target.value)}
          />
          <div className="flex justify-end">
            <Button onClick={send} disabled={pending || !content.trim()}>
              {pending ? "Envoi…" : "Envoyer"}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
