import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, CalendarClock, Package, Tag } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { StatusBadge } from "@/components/shared/status-badge";
import { CloseTicketButton } from "@/components/panel/tickets/ticket-actions";
import { ReplyBox } from "@/components/panel/tickets/reply-box";
import { TicketThread } from "@/components/panel/tickets/ticket-thread";
import type {
  TicketMessageDTO,
  TicketStatusValue,
} from "@/components/panel/tickets/types";
import { db } from "@/lib/db";
import { formatDateTime, timeAgo } from "@/lib/format";
import { requireUser } from "@/lib/guards";
import { ticketsTexts as tx } from "@/lib/i18n/tickets";
import { readStoredAttachments, ticketRef } from "@/lib/validation/tickets";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Ticket",
};

function initialsOf(value: string): string {
  const parts = value.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return "?";
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
}

export default async function TicketDetailPage(props: {
  params: Promise<{ id: string }>;
}) {
  const user = await requireUser();
  const { id } = await props.params;

  const ticket = await db.ticket.findUnique({
    where: { id },
    select: {
      id: true,
      userId: true,
      subject: true,
      status: true,
      category: true,
      subcategory: true,
      orderId: true,
      createdAt: true,
      updatedAt: true,
      messages: {
        orderBy: { createdAt: "asc" },
        select: {
          id: true,
          body: true,
          attachments: true,
          createdAt: true,
          authorId: true,
          author: {
            select: { id: true, username: true, firstName: true, lastName: true, role: true },
          },
        },
      },
    },
  });

  // Ownership guard — a ticket belongs to exactly one user.
  if (!ticket || ticket.userId !== user.id) notFound();

  const status = ticket.status as TicketStatusValue;
  const closed = status === "CLOSED";

  const messages: TicketMessageDTO[] = ticket.messages.map((message) => {
    const isOwn = message.authorId === user.id;
    const isStaff = message.author.role === "ADMIN" || message.author.role === "STAFF";
    const fullName = [message.author.firstName, message.author.lastName]
      .filter(Boolean)
      .join(" ")
      .trim();
    const authorName = isOwn
      ? tx.you
      : isStaff
        ? tx.supportTeam
        : fullName || message.author.username;
    return {
      id: message.id,
      body: message.body,
      isOwn,
      authorName,
      authorInitials: isOwn
        ? initialsOf(fullName || user.username)
        : isStaff
          ? "SP"
          : initialsOf(fullName || message.author.username),
      createdAtLabel: formatDateTime(message.createdAt),
      createdAgo: timeAgo(message.createdAt),
      attachments: readStoredAttachments(message.attachments),
    };
  });

  return (
    <div className="mx-auto w-full max-w-4xl">
      <Link
        href="/tickets"
        className="mb-4 inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
      >
        <ArrowLeft className="size-4" />
        {tx.backToTickets}
      </Link>

      <Card className="mb-6 rounded-2xl border shadow-sm ring-0">
        <CardContent className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div className="min-w-0 space-y-2">
            <div className="flex flex-wrap items-center gap-2">
              <span className="font-mono text-xs text-muted-foreground" title={ticket.id}>
                {tx.ticketRef} {ticketRef(ticket.id)}
              </span>
              <StatusBadge status={status} />
            </div>
            <h1 className="font-display text-lg font-semibold tracking-tight break-words sm:text-xl">
              {ticket.subject}
            </h1>
            <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-muted-foreground">
              <span className="inline-flex items-center gap-1.5">
                <Tag className="size-3.5" />
                {ticket.category}
                {ticket.subcategory ? ` · ${ticket.subcategory}` : ""}
              </span>
              {ticket.orderId ? (
                <span className="inline-flex items-center gap-1.5">
                  <Package className="size-3.5" />
                  {tx.relatedOrder}
                  <span className="font-mono text-foreground">#{ticket.orderId}</span>
                </span>
              ) : null}
              <span className="inline-flex items-center gap-1.5">
                <CalendarClock className="size-3.5" />
                {tx.openedOn} {formatDateTime(ticket.createdAt)}
              </span>
            </div>
          </div>

          {!closed ? (
            <CloseTicketButton
              ticketId={ticket.id}
              className="h-10 shrink-0 gap-2 rounded-lg px-4"
            />
          ) : null}
        </CardContent>
      </Card>

      <Card className="mb-6 rounded-2xl border shadow-sm ring-0">
        <CardContent className="py-2">
          <h2 className="sr-only">{tx.conversation}</h2>
          <TicketThread messages={messages} />
        </CardContent>
      </Card>

      <ReplyBox ticketId={ticket.id} closed={closed} />
    </div>
  );
}
