'use client';

import type { Table } from '@tanstack/react-table';
import { Cross2Icon } from '@radix-ui/react-icons';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DataTableFacetedFilter } from '@/components/ui/table/data-table-faceted-filter';
import { DataTableViewOptions } from '@/components/ui/table/data-table-view-options';

interface AnnouncementToolbarProps<TData> {
  table: Table<TData>;
  showStatusFilter: boolean;
}

export function AnnouncementToolbar<TData>({
  table,
  showStatusFilter
}: AnnouncementToolbarProps<TData>) {
  const isFiltered = table.getState().columnFilters.length > 0;
  const searchColumn = table.getColumn('search');
  const statusColumn = table.getColumn('status');
  const pinColumn = table.getColumn('pin');

  return (
    <div className='flex w-full min-w-0 flex-col gap-3'>
      <div className='flex w-full min-w-0 flex-col gap-3 lg:flex-row lg:items-center lg:justify-between'>
        <Input
          aria-label='ค้นหาประกาศ'
          placeholder='ค้นหาจากหัวข้อหรือเนื้อหาประกาศ'
          value={(searchColumn?.getFilterValue() as string) ?? ''}
          onChange={(event) => searchColumn?.setFilterValue(event.target.value)}
          className='h-10 w-full lg:w-[460px] lg:max-w-[520px]'
        />
        <div className='hidden lg:flex lg:justify-end'>
          <DataTableViewOptions
            table={table}
            triggerLabel='แสดงคอลัมน์'
            searchPlaceholder='ค้นหาคอลัมน์...'
            emptyLabel='ไม่พบคอลัมน์'
          />
        </div>
      </div>

      <div className='flex w-full min-w-0 flex-wrap items-center gap-2'>
        {showStatusFilter && statusColumn ? (
          <DataTableFacetedFilter
            column={statusColumn}
            title='สถานะ'
            options={statusColumn.columnDef.meta?.options ?? []}
          />
        ) : null}
        {pinColumn ? (
          <DataTableFacetedFilter
            column={pinColumn}
            title='การปักหมุด'
            options={pinColumn.columnDef.meta?.options ?? []}
          />
        ) : null}
        {isFiltered ? (
          <Button
            type='button'
            variant='ghost'
            size='sm'
            aria-label='รีเซ็ตตัวกรอง'
            onClick={() => table.resetColumnFilters()}
          >
            <Cross2Icon className='mr-2 h-4 w-4' />
            รีเซ็ตตัวกรอง
          </Button>
        ) : null}
      </div>
    </div>
  );
}
