'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Check, ChevronsUpDown, Plus } from 'lucide-react';

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 { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';

interface TripLabelComboboxProps {
  value: string | null | undefined;
  onChange: (label: string | null) => void;
  placeholder?: string;
  disabled?: boolean;
  id?: string;
}

/**
 * Trip label picker. Free-text on first entry, dropdown of past labels
 * on subsequent ones. The "Create '<typed value>'" item lets reps
 * commit a brand-new label without leaving the keyboard. Past labels
 * come from /api/v1/expenses/trip-labels (distinct values for the
 * port, ordered by most-recent expense date).
 */
export function TripLabelCombobox({
  value,
  onChange,
  placeholder = 'Select or create a trip…',
  disabled,
  id,
}: TripLabelComboboxProps) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState('');

  const labelsQuery = useQuery<{ data: string[] }>({
    queryKey: ['expenses', 'trip-labels'],
    queryFn: () => apiFetch('/api/v1/expenses/trip-labels'),
    enabled: open,
    staleTime: 60_000,
  });

  const labels = labelsQuery.data?.data ?? [];
  const trimmed = search.trim();
  const showCreate =
    trimmed.length > 0 && !labels.some((l) => l.toLowerCase() === trimmed.toLowerCase());

  const commit = (label: string | null) => {
    onChange(label);
    setOpen(false);
    setSearch('');
  };

  return (
    <Popover open={open} onOpenChange={setOpen} modal>
      <PopoverTrigger asChild>
        <Button
          id={id}
          type="button"
          variant="outline"
          role="combobox"
          aria-expanded={open}
          disabled={disabled}
          className={cn('w-full justify-between font-normal', !value && 'text-muted-foreground')}
        >
          <span className="truncate">{value || placeholder}</span>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" aria-hidden />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-(--radix-popper-anchor-width) min-w-[260px] p-0">
        <Command shouldFilter={true}>
          <CommandInput
            placeholder="Type a trip name…"
            value={search}
            onValueChange={setSearch}
            maxLength={120}
          />
          <CommandList>
            <CommandEmpty>
              {trimmed ? `No matches for "${trimmed}"` : 'No past trips yet'}
            </CommandEmpty>
            {value ? (
              <CommandGroup>
                <CommandItem
                  value="__clear__"
                  onSelect={() => commit(null)}
                  className="text-muted-foreground"
                >
                  Clear selection
                </CommandItem>
              </CommandGroup>
            ) : null}
            {showCreate ? (
              <CommandGroup heading="New">
                <CommandItem value={`__create__${trimmed}`} onSelect={() => commit(trimmed)}>
                  <Plus className="mr-2 h-4 w-4" aria-hidden />
                  <span className="truncate">Create &ldquo;{trimmed}&rdquo;</span>
                </CommandItem>
              </CommandGroup>
            ) : null}
            {labels.length > 0 ? (
              <CommandGroup heading="Past trips">
                {labels.map((label) => (
                  <CommandItem key={label} value={label} onSelect={() => commit(label)}>
                    <Check
                      className={cn('mr-2 h-4 w-4', value === label ? 'opacity-100' : 'opacity-0')}
                    />
                    <span className="truncate">{label}</span>
                  </CommandItem>
                ))}
              </CommandGroup>
            ) : null}
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
