'use client';

import { useParams, useRouter } from 'next/navigation';
import { ArrowLeft, Loader2, Ticket } from 'lucide-react';

import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';

import { TicketHistoryCard } from './components/TicketHistoryCard';
import { TicketOverviewCard } from './components/TicketOverviewCard';
import { TicketRepairReportCard } from './components/TicketRepairReportCard';
import { TicketStatusActions } from './components/TicketStatusActions';
import { useTicketDetailEvents } from '../hooks/useTicketDetailEvents';
import { useTicketDetailQuery } from '../hooks/useTicketQueries';

export default function TicketDetailPage() {
  const router = useRouter();
  const { ticketId } = useParams() as { ticketId: string };

  const ticketQuery = useTicketDetailQuery(ticketId);
  const ticket = ticketQuery.data;

  const liveState = useTicketDetailEvents(
    ticketId,
    Boolean(ticketId && ticket && ticket.status !== 'closed'),
  );

  if (ticketQuery.isLoading) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <Loader2 className="size-8 animate-spin text-primary" />
      </div>
    );
  }

  if (ticketQuery.isError || !ticket) {
    return (
      <div className="flex min-h-[60vh] flex-col items-center justify-center gap-3">
        <p className="text-sm text-destructive">Failed to load ticket.</p>
        <Button
          variant="outline"
          size="sm"
          onClick={() => router.push('/ticket')}
        >
          <ArrowLeft />
          Back to Tickets
        </Button>
      </div>
    );
  }

  return (
    <main className="relative z-10 space-y-5">
      <PageHeader
        title="Ticket Detail"
        description={`Ticket ID: ${ticket.id}`}
        icon={Ticket}
        actions={
          <Button
            variant="outline"
            size="sm"
            onClick={() => router.push('/ticket')}
          >
            <ArrowLeft />
            Back
          </Button>
        }
      />

      <div className="grid gap-5 xl:grid-cols-[minmax(0,1fr)_480px]">
        <div className="space-y-5">
          <TicketOverviewCard ticket={ticket} />
          <TicketRepairReportCard ticket={ticket} />
          <TicketHistoryCard ticket={ticket} />
        </div>

        <div>
          <TicketStatusActions ticket={ticket} liveState={liveState} />
        </div>
      </div>
    </main>
  );
}
