'use client';

import type { Table } from '@tanstack/react-table';
import Link from 'next/link';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { DataTableViewOptions } from '@/components/ui/table/data-table-view-options';
import { buildAuditLogSearchParams } from '../api/service';
import { AUDIT_ACTION_OPTIONS, AUDIT_MODULE_OPTIONS } from '../constants/audit-log-options';
import type { AuditLogFilters } from '../api/types';

export function AuditLogToolbar<TData>({
  table,
  isFetching
}: {
  table: Table<TData>;
  isFetching: boolean;
}) {
  const [params, setParams] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    search: parseAsString,
    user: parseAsString,
    module: parseAsString,
    action: parseAsString,
    dateFrom: parseAsString,
    dateTo: parseAsString
  });

  const exportFilters: AuditLogFilters = {
    ...(params.search && { search: params.search }),
    ...(params.user && { user: params.user }),
    ...(params.module && { module: params.module }),
    ...(params.action && { action: params.action }),
    ...(params.dateFrom && { dateFrom: params.dateFrom }),
    ...(params.dateTo && { dateTo: params.dateTo })
  };

  const exportHref = `/api/audit-logs/export?${buildAuditLogSearchParams(exportFilters).toString()}`;
  const hasActiveFilters = Boolean(
    params.search || params.user || params.module || params.action || params.dateFrom || params.dateTo
  );

  const updateFilter = (updates: Partial<typeof params>) => {
    void setParams({
      ...updates,
      page: 1
    });
  };

  return (
    <div className='flex flex-col gap-3 rounded-lg border p-3'>
      <div className='flex flex-col gap-2 xl:flex-row xl:items-center xl:justify-between'>
        <div className='flex flex-1 flex-col gap-2 md:flex-row'>
          <Input
            value={params.search ?? ''}
            onChange={(event) => updateFilter({ search: event.target.value || null })}
            placeholder='ค้นหารายการ'
            className='md:max-w-xs'
          />
          <Input
            value={params.user ?? ''}
            onChange={(event) => updateFilter({ user: event.target.value || null })}
            placeholder='ผู้ใช้งาน'
            className='md:max-w-xs'
          />
        </div>

        <div className='flex flex-wrap items-center gap-2'>
          {isFetching ? (
            <span className='text-muted-foreground inline-flex items-center gap-2 text-sm'>
              <Icons.spinner className='h-4 w-4 animate-spin' />
              กำลังโหลด
            </span>
          ) : null}

          <Link href={exportHref}>
            <Button variant='outline' size='sm'>
              <Icons.fileTypeXls className='mr-2 h-4 w-4' />
              ส่งออก CSV
            </Button>
          </Link>

          <DataTableViewOptions table={table} />
        </div>
      </div>

      <div className='flex flex-col gap-2 lg:flex-row lg:flex-wrap'>
        <Select
          value={params.module ?? 'all'}
          onValueChange={(value) => updateFilter({ module: value === 'all' ? null : value })}
        >
          <SelectTrigger className='w-full lg:w-[220px]'>
            <SelectValue placeholder='โมดูล' />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value='all'>ทุกโมดูล</SelectItem>
            {AUDIT_MODULE_OPTIONS.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Select
          value={params.action ?? 'all'}
          onValueChange={(value) => updateFilter({ action: value === 'all' ? null : value })}
        >
          <SelectTrigger className='w-full lg:w-[220px]'>
            <SelectValue placeholder='รายการ' />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value='all'>ทุกรายการ</SelectItem>
            {AUDIT_ACTION_OPTIONS.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Input
          type='date'
          value={params.dateFrom ?? ''}
          onChange={(event) => updateFilter({ dateFrom: event.target.value || null })}
          className='w-full lg:w-[180px]'
        />
        <Input
          type='date'
          value={params.dateTo ?? ''}
          onChange={(event) => updateFilter({ dateTo: event.target.value || null })}
          className='w-full lg:w-[180px]'
        />

        {hasActiveFilters ? (
          <Button
            variant='outline'
            size='sm'
            onClick={() =>
              void setParams({
                page: 1,
                search: null,
                user: null,
                module: null,
                action: null,
                dateFrom: null,
                dateTo: null
              })
            }
            className='w-full lg:w-auto'
          >
            <Icons.close className='mr-2 h-4 w-4' />
            ล้างตัวกรอง
          </Button>
        ) : null}
      </div>
    </div>
  );
}
