"use client";

import type { Table } from "@tanstack/react-table";
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 { buildEmployeeSearchPlaceholder } from "@/lib/employee-information";
import type { Option } from "@/types/data-table";

interface EmployeeDirectoryToolbarProps<TData> {
  table: Table<TData>;
  companies: Option[];
  departments: Option[];
  positions: Option[];
  statuses: Option[];
  isFetching?: boolean;
}

const ALL_FILTER_VALUE = "all";

function renderSelectItems(options: Option[]) {
  return options.map((option) => (
    <SelectItem key={option.value} value={option.value}>
      {option.label}
    </SelectItem>
  ));
}

export function EmployeeDirectoryToolbar<TData>({
  table,
  companies,
  departments,
  positions,
  statuses,
  isFetching = false,
}: EmployeeDirectoryToolbarProps<TData>) {
  const [params, setParams] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    search: parseAsString,
    company: parseAsString.withDefault(ALL_FILTER_VALUE),
    department: parseAsString.withDefault(ALL_FILTER_VALUE),
    position: parseAsString.withDefault(ALL_FILTER_VALUE),
    status: parseAsString.withDefault(ALL_FILTER_VALUE),
  });

  const hasActiveFilters = Boolean(
    (params.search && params.search.trim()) ||
    params.company !== ALL_FILTER_VALUE ||
    params.department !== ALL_FILTER_VALUE ||
    params.position !== ALL_FILTER_VALUE ||
    params.status !== ALL_FILTER_VALUE,
  );

  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 xl:flex-row xl:items-start xl:justify-between">
        <Input
          aria-label="ค้นหารหัสพนักงานหรือชื่อพนักงาน"
          placeholder={buildEmployeeSearchPlaceholder()}
          value={params.search ?? ""}
          onChange={(event) =>
            void setParams({
              page: 1,
              search: event.target.value || null,
            })
          }
          className="h-10 w-full xl:max-w-[460px]"
        />

        <div className="flex w-full flex-wrap items-center justify-end gap-2 xl:w-auto xl:shrink-0">
          {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}
          <div className="hidden xl:flex">
            <DataTableViewOptions
              table={table}
              triggerLabel="แสดงคอลัมน์"
              searchPlaceholder="ค้นหาคอลัมน์..."
              emptyLabel="ไม่พบคอลัมน์"
            />
          </div>
        </div>
      </div>

      <div className="flex w-full min-w-0 flex-wrap items-center gap-2">
        {/* <Select
          value={params.company}
          onValueChange={(value) => void setParams({ page: 1, company: value })}
        >
          <SelectTrigger aria-label='เลือกบริษัท' className='h-10 w-full sm:w-[180px]'>
            <SelectValue placeholder='เลือกบริษัท' />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={ALL_FILTER_VALUE}>ทั้งหมด</SelectItem>
            {renderSelectItems(companies)}
          </SelectContent>
        </Select> */}

        <Select
          value={params.department}
          onValueChange={(value) =>
            void setParams({ page: 1, department: value })
          }
        >
          <SelectTrigger
            aria-label="เลือกฝ่าย"
            className="h-10 w-full sm:w-[180px]"
          >
            <SelectValue placeholder="เลือกฝ่าย" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={ALL_FILTER_VALUE}>เลือกฝ่าย</SelectItem>
            {renderSelectItems(departments)}
          </SelectContent>
        </Select>

        <Select
          value={params.position}
          onValueChange={(value) =>
            void setParams({ page: 1, position: value })
          }
        >
          <SelectTrigger
            aria-label="เลือกตำแหน่ง"
            className="h-10 w-full sm:w-[180px]"
          >
            <SelectValue placeholder="เลือกตำแหน่ง" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={ALL_FILTER_VALUE}>เลือกตำแหน่ง</SelectItem>
            {renderSelectItems(positions)}
          </SelectContent>
        </Select>

        <Select
          value={params.status}
          onValueChange={(value) => void setParams({ page: 1, status: value })}
        >
          <SelectTrigger
            aria-label="เลือกสถานะ"
            className="h-10 w-full sm:w-[180px]"
          >
            <SelectValue placeholder="เลือกสถานะ" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={ALL_FILTER_VALUE}>เลือกสถานะ</SelectItem>
            {renderSelectItems(statuses)}
          </SelectContent>
        </Select>

        {hasActiveFilters ? (
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="h-10 w-full sm:ml-auto sm:w-auto"
            onClick={() =>
              void setParams({
                page: 1,
                search: null,
                company: ALL_FILTER_VALUE,
                department: ALL_FILTER_VALUE,
                position: ALL_FILTER_VALUE,
                status: ALL_FILTER_VALUE,
              })
            }
          >
            ล้างตัวกรอง
          </Button>
        ) : null}
      </div>
    </div>
  );
}
