import Link from "next/link";
import { notFound } from "next/navigation";
import { CommentForm, WorkPanel } from "@/components/features/tickets";
import { Card, PageHeader, StatusBadge } from "@/components/ui";
import type { DashboardKind } from "@/lib/authz/context";
import { requireDashboard } from "@/lib/authz/guard";
import { AuthError } from "@/lib/authz/errors";
import { isOverdue } from "@/lib/domain/ticket-workflow";
import type { TicketStatus } from "@/lib/domain/enums";
import { formatDateTime } from "@/lib/utils";
import { getTicketDetail } from "@/lib/services/tickets";

export async function TicketScreen({ kind, ticketId }: { kind: Extract<DashboardKind, "admin" | "maintenance">; ticketId: string }) {
  await requireDashboard(kind);
  let d;
  try { d = await getTicketDetail(ticketId); } catch (e) { if (e instanceof AuthError) notFound(); throw e; }
  const { ticket: t, flags, comments, activities } = d;
  const overdue = isOverdue({ status: t.status as TicketStatus, slaDueAt: t.slaDueAt });
  return (
    <>
      <p className="text-xs text-muted-foreground"><Link href={`/dashboard/${kind}/tickets`} className="hover:underline">Tickets</Link></p>
      <PageHeader title={`TKT-${t.number}: ${t.subject}`} description={`${t.site.name} · raised by ${d.reporterName} · ${d.assigneeName ? `assigned to ${d.assigneeName}` : "unassigned"}`} actions={<span className="flex gap-2"><StatusBadge value={t.priority} /><StatusBadge value={t.status} />{t.escalatedAt ? <StatusBadge value="ESCALATED" /> : null}</span>} />
      <div className="grid gap-4 lg:grid-cols-[1fr_22rem]">
        <div className="space-y-4">
          <Card className="space-y-2 p-4">
            <h2 className="text-sm font-semibold">Description</h2>
            <p className="whitespace-pre-wrap text-sm">{t.description}</p>
            <p className={overdue ? "text-xs text-danger" : "text-xs text-muted-foreground"}>Response due {formatDateTime(t.slaDueAt)}{overdue ? " (overdue)" : ""}</p>
            {t.resolutionNotes ? <div className="rounded-md bg-muted p-3 text-sm"><p className="text-xs font-medium">Resolution</p><p className="whitespace-pre-wrap">{t.resolutionNotes}</p></div> : null}
          </Card>
          <Card className="p-4">
            <h2 className="mb-3 text-sm font-semibold">Conversation</h2>
            {comments.length === 0 ? <p className="text-sm text-muted-foreground">No comments yet.</p> : (
              <ol className="space-y-3">
                {comments.map((c) => (
                  <li key={c.id} className={c.visibility === "INTERNAL" ? "rounded-md border border-dashed border-border bg-muted p-3" : "rounded-md border border-border p-3"}>
                    <p className="text-xs text-muted-foreground">{c.author.name} · {formatDateTime(c.createdAt)}{c.visibility === "INTERNAL" ? " · internal note" : ""}</p>
                    <p className="mt-1 whitespace-pre-wrap text-sm">{c.body}</p>
                  </li>
                ))}
              </ol>
            )}
          </Card>
          {t.status !== "CLOSED" ? <CommentForm ticketId={t.id} canInternal={flags.resolve} /> : null}
        </div>
        <div className="space-y-4">
          {flags.resolve ? (
            <>
              <WorkPanel ticketId={t.id} status={t.status} nextStatuses={[...d.nextStatuses]} assignees={d.assignees} assigneeId={t.assigneeId} canAssign={flags.assign} />
              <Card className="p-4 text-sm">
                <h2 className="mb-2 text-sm font-semibold">Time spent: {Math.floor(t.timeSpentMinutes / 60)}h {t.timeSpentMinutes % 60}m</h2>
                {activities.length === 0 ? <p className="text-muted-foreground">Nothing logged.</p> : <ul className="space-y-1">{activities.map((a) => <li key={a.id}><span className="font-medium">{a.minutes} min</span> · {a.note} <span className="text-xs text-muted-foreground">({a.user.name}, {formatDateTime(a.createdAt)})</span></li>)}</ul>}
              </Card>
            </>
          ) : null}
        </div>
      </div>
    </>
  );
}
