'use client';

import { Check, ChevronsUpDown, X } from 'lucide-react';
import { useMemo, useState } from 'react';
import { useTranslations } from '@/components/locale-provider';
import { Button } from '@/components/ui/button';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';

export interface ResourceOption {
  id: string;
  name: string;
  /** Optional prefix shown before the name (e.g. # for channels). */
  prefix?: string;
}

interface DiscordResourceMultiSelectProps {
  options: ResourceOption[];
  value: string[];
  onChange: (next: string[]) => void;
  placeholder?: string;
  disabled?: boolean;
  emptyLabel?: string;
  /** Show a truncated id hint in the dropdown (useful for Discord snowflakes). */
  showIdHint?: boolean;
}

export function DiscordResourceMultiSelect({
  options,
  value,
  onChange,
  placeholder,
  disabled = false,
  emptyLabel,
  showIdHint = true
}: DiscordResourceMultiSelectProps) {
  const t = useTranslations();
  const [open, setOpen] = useState(false);

  const selected = useMemo(() => {
    const byId = new Map(options.map((option) => [option.id, option]));
    return value.map((id) => byId.get(id) ?? { id, name: id, prefix: '' });
  }, [options, value]);

  function toggle(id: string) {
    if (value.includes(id)) {
      onChange(value.filter((entry) => entry !== id));
    } else {
      onChange([...value, id]);
    }
  }

  function remove(id: string) {
    onChange(value.filter((entry) => entry !== id));
  }

  return (
    <div className="space-y-2">
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            type="button"
            variant="outline"
            role="combobox"
            aria-expanded={open}
            disabled={disabled}
            className="h-auto min-h-9 w-full justify-between px-3 py-2 font-normal"
          >
            <span className="truncate text-left text-muted-foreground">
              {placeholder ?? t('common.searchSelect')}
            </span>
            <ChevronsUpDown className="ml-2 size-4 shrink-0 opacity-50" />
          </Button>
        </PopoverTrigger>
        <PopoverContent className="p-0" align="start">
          <Command>
            <CommandInput placeholder={placeholder ?? t('common.searchSelect')} />
            <CommandList>
              <CommandEmpty>{emptyLabel ?? t('common.noResults')}</CommandEmpty>
              <CommandGroup>
                {options.map((option) => {
                  const isSelected = value.includes(option.id);
                  return (
                    <CommandItem
                      key={option.id}
                      value={`${option.prefix ?? ''}${option.name} ${option.id}`}
                      onSelect={() => toggle(option.id)}
                    >
                      <Check className={cn('size-4', isSelected ? 'opacity-100' : 'opacity-0')} />
                      <span className="truncate">
                        {option.prefix ?? ''}
                        {option.name}
                      </span>
                      {showIdHint ? (
                        <span className="ml-auto font-mono text-[10px] text-muted-foreground">
                          {option.id.slice(-6)}
                        </span>
                      ) : null}
                    </CommandItem>
                  );
                })}
              </CommandGroup>
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>

      {selected.length > 0 ? (
        <div className="flex flex-wrap gap-1.5">
          {selected.map((option) => (
            <button
              key={option.id}
              type="button"
              disabled={disabled}
              onClick={() => remove(option.id)}
              className="inline-flex items-center gap-1 rounded-md border border-border bg-secondary px-2 py-0.5 text-xs hover:bg-accent"
            >
              <span className="max-w-40 truncate">
                {option.prefix ?? ''}
                {option.name}
              </span>
              <X className="size-3 opacity-60" />
            </button>
          ))}
        </div>
      ) : null}
    </div>
  );
}
