import { Table } from "@tanstack/react-table";

import { ButtonGroup } from "@/components";
import { DataTableFilterField, useDataTableContext } from "@/lib/hooks";
import { Badge, Button, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/ui";
import { t } from "i18next";
import { PlusIcon, SearchIcon, XIcon } from "lucide-react";
import React from "react";

interface CatalogDataTableFilterProps<TData> extends React.HTMLAttributes<HTMLDivElement> {
  table: Table<TData>;
  filterFields?: DataTableFilterField<TData>[];
}

export function CatalogDataTableFilter<TData>({
  table,
  className,
  children,
  ...props
}: CatalogDataTableFilterProps<TData>) {
  const { globalFilter, isFiltered, setGlobalFilter, resetGlobalFilter } = useDataTableContext();

  const inputRef = React.useRef<HTMLInputElement>(null);
  const [inputValue, setInputValue] = React.useState("");

  const handleKeyDown = React.useCallback(
    (e: React.KeyboardEvent<HTMLInputElement>) => {
      if (e.key === "Enter" && inputValue.trim()) {
        e.preventDefault();
        setGlobalFilter((prev) => [...prev, inputValue.trim()]);
        setInputValue("");
      }
      if (e.key === "Backspace" && !inputValue && globalFilter.length > 0) {
        e.preventDefault();
        setGlobalFilter((prev) => prev.slice(0, -1));
      }
    },
    [globalFilter, inputValue]
  );

  const removeFilterTerm = React.useCallback((filterTerm: string) => {
    setGlobalFilter((prev) => prev.filter((f) => f !== filterTerm));
  }, []);

  const addFilterTerm = React.useCallback(() => {
    if (inputValue.trim()) {
      setGlobalFilter((prev) => [...prev, inputValue.trim()]);
      setInputValue("");
      inputRef.current?.focus();
    }
  }, [inputValue]);

  return (
    <TooltipProvider>
      <div className='w-full space-y-2' {...props}>
        <div className='relative flex items-center flex-1 p-2 space-x-2 border rounded-md border-input'>
          <SearchIcon className='w-4 h-4 text-gray-500' />
          <div className='flex flex-wrap items-center flex-1 gap-2'>
            {globalFilter &&
              globalFilter.map((filterTerm) => (
                <Badge
                  key={filterTerm}
                  variant='default'
                  className='px-1 text-base font-normal rounded-sm'
                >
                  {filterTerm}
                  <Button
                    variant='ghost'
                    onClick={() => removeFilterTerm(filterTerm)}
                    className='h-auto p-0 px-1 ml-1 hover:bg-transparent'
                  >
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <XIcon className='w-4 h-4' />
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>{t("catalog.filter.badget_remove_tooltip")}</p>
                      </TooltipContent>
                    </Tooltip>
                    <span className='sr-only'>{t("catalog.filter.badget_remove_tooltip")}</span>
                  </Button>
                </Badge>
              ))}
            <div className='flex-1 flex items-center min-w-[300px]'>
              <input
                ref={inputRef}
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder={t("common.filter.input_placeholder")}
                className='flex-1 w-full h-8 bg-transparent outline-none placeholder:text-muted-foreground'
              />
              <ButtonGroup>
                {isFiltered && (
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        variant='outline'
                        onClick={() => resetGlobalFilter()}
                        className='h-8 px-2 transition-all lg:px-3'
                      >
                        <XIcon className='w-4 h-4 mr-2' />
                        {t("common.filter.reset_filter")}
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>{t("common.filter.reset_filter")}</p>
                    </TooltipContent>
                  </Tooltip>
                )}
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant='outline'
                      size='icon'
                      onClick={addFilterTerm}
                      className='w-8 h-8 p-0 hover:bg-muted'
                    >
                      <PlusIcon className='w-4 h-4' />
                      <span className='sr-only'>{t("common.filter.button_add_term")}</span>
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>{t("common.filter.button_add_term_tooltip")}</p>
                  </TooltipContent>
                </Tooltip>
              </ButtonGroup>
            </div>
          </div>
        </div>
        <p className='text-sm text-muted-foreground'>{t("common.filter.help_text")}</p>
      </div>
    </TooltipProvider>
  );
}
