'use client';

import { useSuspenseQuery } from '@tanstack/react-query';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { DataTable } from '@/components/ui/table/data-table';
import { useDataTable } from '@/hooks/use-data-table';
import { getSortingStateParser } from '@/lib/parsers';
import { employeeDirectoryQueryOptions } from '../api/queries';
import { getEmployeeDirectoryColumns } from './employee-directory-columns';
import { EmployeeDirectoryToolbar } from './employee-directory-toolbar';

const columnIds = [
  'employee_code',
  'search',
  'company',
  'position',
  'department',
  'status',
  'actions'
];

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

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

  const { data, isFetching } = useSuspenseQuery(employeeDirectoryQueryOptions(filters));
  const hasActiveFilters = Boolean(
    (params.search && params.search.trim()) ||
      params.company ||
      params.department ||
      params.position ||
      params.status
  );
  const pageCount = Math.max(1, Math.ceil(data.total_employees / params.perPage));
  const columns = getEmployeeDirectoryColumns(data.options);

  const { table } = useDataTable({
    data: data.employees,
    columns,
    pageCount,
    shallow: true,
    debounceMs: 500,
    initialState: {
      columnVisibility: {
        company: false,
        status: false
      },
      columnPinning: { right: ['actions'] }
    }
  });

  return (
    <div className='w-full min-w-0 max-w-full space-y-4 overflow-hidden'>
      <EmployeeDirectoryToolbar
        table={table}
        companies={data.options.companies}
        departments={data.options.departments}
        positions={data.options.positions}
        statuses={data.options.statuses}
        isFetching={isFetching}
      />

      {data.employees.length === 0 && hasActiveFilters ? (
        <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.teams className='text-muted-foreground h-6 w-6' />
            </div>
            <div className='space-y-1'>
              <h3 className='text-lg font-semibold'>ไม่พบข้อมูลที่ตรงกับตัวกรอง</h3>
              <p className='text-muted-foreground max-w-md text-sm'>
                ลองปรับคำค้นหาหรือเปลี่ยนตัวกรอง แล้วค้นหาอีกครั้ง
              </p>
            </div>
            <Button
              variant='outline'
              onClick={() =>
                void setParams({
                  page: 1,
                  search: null,
                  company: null,
                  department: null,
                  position: null,
                  status: null
                })
              }
            >
              ล้างตัวกรอง
            </Button>
          </CardContent>
        </Card>
      ) : (
        <DataTable
          table={table}
          tableClassName='w-full min-w-[900px] table-fixed'
          headerClassName='bg-muted/60'
          headClassName='h-12 px-4 py-2 align-middle text-sm font-medium'
          bodyRowClassName='h-16 hover:bg-muted/30'
          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: 'เธซเธเนเธฒเธชเธธเธ”เธ—เนเธฒเธข'
            }
          }}
        />
      )}
    </div>
  );
}
