'use client';

import { useState } from 'react';
import { Check, ChevronsUpDown, X } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { Badge } from '@/components/ui/badge';
import { useEntityOptions } from '@/hooks/use-entity-options';

interface TagPickerProps {
  selectedIds: string[];
  onChange: (ids: string[]) => void;
  placeholder?: string;
}

export function TagPicker({
  selectedIds,
  onChange,
  placeholder = 'Select tags...',
}: TagPickerProps) {
  const [open, setOpen] = useState(false);
  const { options, isLoading } = useEntityOptions({
    endpoint: '/api/v1/tags/options',
    labelKey: 'name',
    valueKey: 'id',
  });

  // Extend options to include color
  const tagOptions = options as Array<{ value: string; label: string; color?: string }>;

  // If the port has no tags configured AND the rep also hasn't selected any
  // (e.g. a tag was deleted after selection), don't render the picker at all -
  // the affordance is noise until tags are set up under Admin → Tags.
  if (!isLoading && tagOptions.length === 0 && selectedIds.length === 0) {
    return null;
  }

  function toggleTag(tagId: string) {
    if (selectedIds.includes(tagId)) {
      onChange(selectedIds.filter((id) => id !== tagId));
    } else {
      onChange([...selectedIds, tagId]);
    }
  }

  function removeTag(tagId: string) {
    onChange(selectedIds.filter((id) => id !== tagId));
  }

  const selectedTags = tagOptions.filter((t) => selectedIds.includes(t.value));

  return (
    <div className="space-y-2">
      <Popover open={open} onOpenChange={setOpen} modal>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            role="combobox"
            size="sm"
            aria-expanded={open}
            className="w-full justify-between font-normal h-8"
          >
            <span className="text-muted-foreground">
              {selectedIds.length > 0
                ? `${selectedIds.length} tag${selectedIds.length > 1 ? 's' : ''} selected`
                : placeholder}
            </span>
            <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" aria-hidden />
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-(--radix-popover-trigger-width) p-0" align="start">
          <Command>
            <CommandInput placeholder="Search tags..." />
            <CommandList>
              <CommandEmpty>{isLoading ? 'Loading...' : 'No tags found.'}</CommandEmpty>
              <CommandGroup>
                {tagOptions.map((tag) => (
                  <CommandItem key={tag.value} onSelect={() => toggleTag(tag.value)}>
                    <Check
                      className={`mr-2 h-4 w-4 ${
                        selectedIds.includes(tag.value) ? 'opacity-100' : 'opacity-0'
                      }`}
                    />
                    <span
                      className="mr-2 h-3 w-3 rounded-full shrink-0"
                      style={{ backgroundColor: tag.color ?? '#6B7280' }}
                    />
                    {tag.label}
                  </CommandItem>
                ))}
              </CommandGroup>
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>

      {/* Selected tags display */}
      {selectedTags.length > 0 && (
        <div className="flex flex-wrap gap-1">
          {selectedTags.map((tag) => (
            <Badge key={tag.value} variant="secondary" className="gap-1 pr-1">
              <span
                className="h-2 w-2 rounded-full shrink-0"
                style={{ backgroundColor: tag.color ?? '#6B7280' }}
              />
              {tag.label}
              <button
                className="ml-0.5 rounded-full hover:bg-muted-foreground/20 p-0.5"
                onClick={() => removeTag(tag.value)}
              >
                <X className="h-3 w-3" />
              </button>
            </Badge>
          ))}
        </div>
      )}
    </div>
  );
}
