'use client';

import { useCallback, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { PageHeader } from '@/components/page-header';
import { Ticket } from 'lucide-react';
import type { TicketListItem, TicketStatus } from '@/types';

import { TicketFilters } from './components/TicketFilters';
import { TicketTable } from './components/TicketTable';
import { useTicketColumns } from './components/TicketColumns';
import { useTenantTicketTableEvents } from './hooks/useTenantTicketTableEvents';
import { useTicketsQuery } from './hooks/useTicketQueries';

export default function TicketPage() {
  const router = useRouter();
  const [skip, setSkip] = useState(0);
  const [limit, setLimit] = useState(10);
  const [status, setStatus] = useState<TicketStatus | 'all'>('all');
  const [segmentId, setSegmentId] = useState('');

  useTenantTicketTableEvents();

  const ticketsQuery = useTicketsQuery({
    skip,
    limit,
    status,
    chainageId: segmentId,
  });

  const columns = useTicketColumns();
  const tickets = ticketsQuery.data?.items ?? [];
  const total = ticketsQuery.data?.total ?? 0;

  const handleStatusChange = useCallback((nextStatus: TicketStatus | 'all') => {
    setStatus(nextStatus);
    setSkip(0);
  }, []);

  const handleSegmentChange = useCallback((nextSegmentId: string) => {
    setSegmentId(nextSegmentId);
    setSkip(0);
  }, []);

  const handleView = useCallback(
    (ticket: TicketListItem) => {
      router.push(
        `/ticket/${ticket.id}?defect_class=${encodeURIComponent(ticket.default_defect_class)}`,
      );
    },
    [router],
  );

  const toolbar = useMemo(
    () => (
      <TicketFilters
        status={status}
        segmentId={segmentId}
        onStatusChange={handleStatusChange}
        onSegmentChange={handleSegmentChange}
      />
    ),
    [handleSegmentChange, handleStatusChange, segmentId, status],
  );

  return (
    <main className="relative z-10 space-y-5">
      <PageHeader
        title="Tickets"
        description="Track detection, assignment, repair, review, and closure."
        icon={Ticket}
      />

      <TicketTable
        columns={columns}
        tickets={tickets}
        isLoading={ticketsQuery.isLoading}
        toolbar={toolbar}
        skip={skip}
        limit={limit}
        total={total}
        onPageChange={setSkip}
        onLimitChange={setLimit}
        onView={handleView}
      />
    </main>
  );
}
