"use client";

import { useState } from 'react';
import { Tag as TagIcon } from 'lucide-react';
import { Input } from '@alga-psa/ui/components/Input';
import * as Popover from '@radix-ui/react-popover';
import { TagGrid } from './TagGrid';
import { filterTagsByText } from '../../lib/utils';
import { ITag } from '@alga-psa/types';
import { Button } from '../Button';
import { useTranslation } from '../../lib/i18n/client';

interface TagFilterProps {
  id?: string;
  tags: ITag[];
  selectedTags: string[];
  onToggleTag: (tagText: string) => void;
  onClearTags: () => void;
  placeholder?: string;
  triggerLabel?: string;
  selectedLabel?: string;
  triggerClassName?: string;
}

export function TagFilter({
  id = 'tag-filter',
  tags,
  selectedTags,
  onToggleTag,
  onClearTags,
  placeholder,
  triggerLabel,
  selectedLabel,
  triggerClassName = '',
}: TagFilterProps) {
  const { t } = useTranslation();
  const resolvedPlaceholder = placeholder ?? t('tagFilter.placeholder', { defaultValue: 'Filter by tags...' });
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  const filteredTags = filterTagsByText(tags, searchQuery);

  return (
    <Popover.Root open={isOpen} onOpenChange={setIsOpen}>
      <Popover.Trigger asChild>
        <Button id={`${id}-trigger`} variant="outline" className={`h-9 gap-2 whitespace-nowrap ${triggerClassName}`}>
          <TagIcon className="h-4 w-4" />
          <span>
            {selectedTags.length > 0
              ? selectedLabel ?? t('tagFilter.selectedCount', { count: selectedTags.length, defaultValue: '{{count}} selected' })
              : triggerLabel ?? t('tagFilter.filter', { defaultValue: 'Filter' })}
          </span>
        </Button>
      </Popover.Trigger>
      <Popover.Portal>
        <Popover.Content
          className="w-[300px] p-4 bg-white rounded-lg shadow-lg border border-gray-200 z-50"
          sideOffset={5}
        >
          <div className="space-y-4">
            <Input
              placeholder={resolvedPlaceholder}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              autoFocus
            />
            <TagGrid
              tags={filteredTags}
              selectedTags={selectedTags}
              onTagSelect={onToggleTag}
            />
            {selectedTags.length > 0 && (
              <div className="pt-2 border-t flex justify-end">
                <Button id={`${id}-clear`} variant="ghost" size="sm" onClick={onClearTags}>
                  {t('tagFilter.clearAll', { defaultValue: 'Clear all' })}
                </Button>
              </div>
            )}
          </div>
        </Popover.Content>
      </Popover.Portal>
    </Popover.Root>
  );
}