'use client';

import { useState } from 'react';
import { Tag } from '@prisma/client';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Button } from '@/components/ui/button';
import { Search, X } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

interface TagFilterProps {
  tags: Tag[];
  selected: number[];
  mode: 'any' | 'all';
  onSelectionChange: (selected: number[]) => void;
  onModeChange: (mode: 'any' | 'all') => void;
}

export function TagFilter({ tags, selected, mode, onSelectionChange, onModeChange }: TagFilterProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [open, setOpen] = useState(false);

  // Helper to safely get tag name, handling potential type mismatches
  const getTagName = (tag: Tag | any): string => {
    // Try multiple possible field names
    return tag.tag_name || tag.tagName || tag.name || '';
  };

  const filteredTags = tags.filter((tag) => {
    const tagName = getTagName(tag);
    return tagName.toLowerCase().includes(searchQuery.toLowerCase());
  });

  const toggleTag = (tagId: number) => {
    if (selected.includes(tagId)) {
      onSelectionChange(selected.filter((id) => id !== tagId));
    } else {
      onSelectionChange([...selected, tagId]);
    }
  };

  const selectedTags = tags.filter((t) => selected.includes(t.id));

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <label className="text-sm font-medium text-secondary">Tags</label>
        {selected.length > 1 && (
          <Select value={mode} onValueChange={(value) => onModeChange(value as 'any' | 'all')}>
            <SelectTrigger className="h-7 w-20 text-xs">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="any">Any</SelectItem>
              <SelectItem value="all">All</SelectItem>
            </SelectContent>
          </Select>
        )}
      </div>
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            className="w-full justify-start text-left font-normal"
          >
            <Search className="mr-2 h-4 w-4" />
            {selected.length === 0 ? 'Select tags...' : `${selected.length} selected`}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-[300px] p-0" align="start">
          <div className="p-2">
            <Input
              placeholder="Search tags..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="mb-2"
            />
            <div className="max-h-[300px] overflow-y-auto">
              {filteredTags.length === 0 ? (
                <p className="p-2 text-sm text-gray-500">No tags found</p>
              ) : (
                <div className="space-y-1">
                  {filteredTags.map((tag) => {
                    const isSelected = selected.includes(tag.id);
                    return (
                      <div
                        key={tag.id}
                        className="flex items-center space-x-2 rounded-md p-2 hover:bg-gray-100 dark:hover:bg-gray-800 cursor-pointer"
                        onClick={() => toggleTag(tag.id)}
                      >
                        <span onClick={(e) => e.stopPropagation()}>
                          <Checkbox
                            checked={isSelected}
                            onCheckedChange={() => toggleTag(tag.id)}
                          />
                        </span>
                        <label className="flex-1 cursor-pointer text-sm">
                          {getTagName(tag) || 'Unnamed Tag'}
                        </label>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </PopoverContent>
      </Popover>
      {selectedTags.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {selectedTags.map((tag) => (
            <Badge
              key={tag.id}
              variant="secondary"
              className="flex items-center gap-1"
            >
              {getTagName(tag) || 'Unnamed Tag'}
              <button
                onClick={() => toggleTag(tag.id)}
                className="ml-1 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700"
              >
                <X className="h-3 w-3" />
              </button>
            </Badge>
          ))}
        </div>
      )}
    </div>
  );
}

