'use client';

import { useSuspenseQuery } from '@tanstack/react-query';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { DataTable } from '@/components/ui/table/data-table';
import { useDataTable } from '@/hooks/use-data-table';
import { hasAnyPermission } from '@/lib/auth/authorization';
import { getSortingStateParser } from '@/lib/parsers';
import { announcementsQueryOptions } from '../api/queries';
import type { AnnouncementStatus } from '../api/types';
import { getAnnouncementColumns } from './announcement-columns';
import { AnnouncementToolbar } from './announcement-toolbar';

const columnIds = [
  'pin',
  'search',
  'status',
  'published_at',
  'end_date',
  'created_by_name',
  'actions'
];

export default function AnnouncementsPage({
  currentUserId,
  permissions
}: {
  currentUserId: string;
  permissions: readonly string[];
}) {
  const canReadAllAnnouncements = hasAnyPermission(permissions, ['announcement:read_all']);
  const [params] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    search: parseAsString,
    status: parseAsString,
    pin: parseAsString,
    sort: getSortingStateParser(columnIds).withDefault([])
  });

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(params.search && { search: params.search }),
    ...(canReadAllAnnouncements && params.status
      ? { status: params.status as AnnouncementStatus }
      : {}),
    ...(params.pin && { pin: params.pin as 'all' | 'pinned' }),
    ...(params.sort.length > 0 && { sort: JSON.stringify(params.sort) })
  };

  const { data } = useSuspenseQuery(announcementsQueryOptions(filters));
  const columns = getAnnouncementColumns({ currentUserId, permissions });
  const pageCount = Math.max(1, Math.ceil(data.total_announcements / params.perPage));

  const { table } = useDataTable({
    data: data.announcements,
    columns,
    pageCount,
    shallow: true,
    debounceMs: 400,
    initialState: {
      columnPinning: { right: ['actions'] }
    }
  });

  return (
    <div className='w-full min-w-0 max-w-full'>
      <DataTable
        table={table}
        tableClassName='w-full min-w-[940px] table-fixed'
        headerClassName='bg-muted/70'
        headClassName='h-12 px-4 py-2 align-middle text-sm font-medium'
        bodyRowClassName='h-18 hover:bg-muted/20'
        bodyCellClassName='px-4 py-3 align-middle'
        paginationProps={{
          labels: {
            total: (count) => `${count.toLocaleString('th-TH')} รายการ`,
            selected: (selected, total) =>
              `เลือกแล้ว ${selected.toLocaleString('th-TH')} จาก ${total.toLocaleString('th-TH')} รายการ`,
            rowsPerPage: 'ต่อหน้า',
            page: (page, totalPages) => `${page} / ${totalPages}`,
            firstPage: 'หน้าแรก',
            previousPage: 'หน้าก่อนหน้า',
            nextPage: 'หน้าถัดไป',
            lastPage: 'หน้าสุดท้าย'
          }
        }}
      >
        <AnnouncementToolbar table={table} showStatusFilter={canReadAllAnnouncements} />
      </DataTable>
    </div>
  );
}
