"use client";

import { TicketsHeader } from "@/features/tickets/components/tickets-header";
import { TicketThread } from "@/features/tickets/components/ticket-thread";
import { ticketsDict } from "@/features/tickets/dict";
import {
  useReplyTicketMutation,
  useTicket,
} from "@/features/tickets/hooks/use-tickets";
import {
  formatTicketDate,
  getStatusBadgeClass,
} from "@/features/tickets/utils/ticket-helpers";
import { panelDict } from "@/features/panel/dict";

type TicketDetailPageContentProps = {
  ticketId: string;
};

export function TicketDetailPageContent({ ticketId }: TicketDetailPageContentProps) {
  const { data: ticket, isLoading } = useTicket(ticketId);
  const replyMutation = useReplyTicketMutation(ticketId);

  if (isLoading) {
    return (
      <div className="mx-auto flex w-full max-w-3xl flex-1 flex-col gap-4 px-4 py-4 sm:px-6">
        <TicketsHeader backHref="/panel/support" />
        <p className="text-sm text-muted-foreground">{panelDict.loading}</p>
      </div>
    );
  }

  if (!ticket) {
    return null;
  }

  const canReply = ticket.status !== "CLOSED";

  return (
    <div className="mx-auto flex w-full max-w-3xl flex-1 flex-col gap-4 px-4 py-4 pb-28 sm:px-6 md:pb-6">
      <TicketsHeader backHref="/panel/support" />

      <section className="rounded-3xl bg-card p-4 shadow-soft-sm sm:p-5">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div className="min-w-0">
            <h2 className="text-lg font-bold text-card-foreground">{ticket.subject}</h2>
            {ticket.category ? (
              <p className="mt-1 text-sm text-muted-foreground">{ticket.category}</p>
            ) : null}
          </div>
          <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${getStatusBadgeClass(ticket.status)}`}>
            {ticketsDict.statuses[ticket.status]}
          </span>
        </div>
        <p className="mt-3 text-xs text-muted-foreground">
          {formatTicketDate(ticket.updatedAt)}
        </p>
      </section>

      <TicketThread
        messages={ticket.messages}
        canReply={canReply}
        isSubmitting={replyMutation.isPending}
        onSubmit={(body) => replyMutation.mutate({ body })}
      />
    </div>
  );
}
