'use client';

import Link from 'next/link';
import { useSuspenseQuery } from '@tanstack/react-query';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { Icons } from '@/components/icons';
import { buttonVariants } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { DataTable } from '@/components/ui/table/data-table';
import { DataTableToolbar } from '@/components/ui/table/data-table-toolbar';
import { useDataTable } from '@/hooks/use-data-table';
import { getSortingStateParser } from '@/lib/parsers';
import { cn } from '@/lib/utils';
import { trainingRecordsQueryOptions } from '../api/queries';
import { pendingReviewColumns } from './pending-review-columns';

const columnIds = pendingReviewColumns.map((column) => column.id).filter(Boolean) as string[];

export function PendingReviewTable() {
  const [params] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    search: parseAsString,
    year: parseAsString,
    company: parseAsString,
    department: parseAsString,
    sort: getSortingStateParser(columnIds).withDefault([]),
  });

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(params.search && { search: params.search }),
    statuses: 'pending',
    ...(params.year && { year: params.year }),
    ...(params.company && { company: params.company }),
    ...(params.department && { department: params.department }),
    ...(params.sort.length > 0 && { sort: JSON.stringify(params.sort) }),
  };

  const { data } = useSuspenseQuery(trainingRecordsQueryOptions(filters));
  const hasActiveFilters = Boolean(
    params.search || params.year || params.company || params.department,
  );
  const pageCount = Math.ceil(data.total_training_records / params.perPage);

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

  if (data.training_records.length === 0) {
    return (
      <Card className='border-dashed'>
        <CardContent className='flex flex-col items-center justify-center gap-4 py-12 text-center'>
          <div className='bg-muted flex h-12 w-12 items-center justify-center rounded-full'>
            <Icons.checks className='text-muted-foreground h-6 w-6' />
          </div>
          <div className='space-y-1'>
            <h3 className='text-lg font-semibold'>
              {hasActiveFilters ? 'ไม่พบรายการที่ตรงกับตัวกรอง' : 'ไม่มีรายการอบรมที่รอตรวจสอบ'}
            </h3>
            <p className='text-muted-foreground max-w-md text-sm'>
              {hasActiveFilters
                ? 'ลองปรับตัวกรองปี บริษัท แผนก หรือคำค้นหาใหม่'
                : 'รายการอบรมที่ส่งเข้ามาทั้งหมดถูกตรวจสอบแล้ว'}
            </p>
          </div>
          <Link
            href='/dashboard/training-records'
            className={cn(buttonVariants({ variant: 'outline' }), 'text-sm')}
          >
            <Icons.calendar className='mr-2 h-4 w-4' />
            ดูรายการอบรมทั้งหมด
          </Link>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className='w-full min-w-0 max-w-full'>
      <DataTable table={table}>
        <DataTableToolbar table={table} />
      </DataTable>
    </div>
  );
}
