'use client';

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

import { Button } from '@/components/ui/button';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';

interface UserOption {
  id: string;
  displayName: string | null;
}

/**
 * Picker over the current port's users. Stores either a user ID (when
 * a user is selected) or a plain string (when "Other..." is chosen and
 * a custom name is typed). Callers pass `value` as a plain string and
 * the picker maps it back to a user when one matches the id.
 *
 * Used by the expense form where the payer can be either a staff member
 * or an external party (vendor employee paying the bill, etc.).
 */
export function UserPicker({
  value,
  onChange,
  placeholder = 'Select user…',
  disabled,
  className,
}: {
  value: string | null | undefined;
  onChange: (next: string | null) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
}) {
  const [open, setOpen] = useState(false);
  const [otherMode, setOtherMode] = useState(false);
  const { data } = useQuery<{ data: UserOption[] }>({
    queryKey: ['user-options'],
    queryFn: () => apiFetch('/api/v1/admin/users/options'),
    staleTime: 5 * 60_000,
    // Don't fetch until the popover opens - keeps the page light when
    // most reps never expand this field.
    enabled: open,
  });

  const users = data?.data ?? [];
  const matched = value ? users.find((u) => u.id === value) : null;

  // When the stored value isn't one of the fetched users' ids, treat it
  // as a free-text payer name (the "Other..." path).
  const displayLabel = (() => {
    if (!value) return placeholder;
    if (matched) return matched.displayName ?? matched.id.slice(0, 8);
    return value;
  })();

  if (otherMode) {
    return (
      <div className={cn('flex gap-2', className)}>
        <Input
          autoFocus
          placeholder="Custom payer name"
          value={value ?? ''}
          onChange={(e) => onChange(e.target.value || null)}
          disabled={disabled}
        />
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={() => {
            setOtherMode(false);
            onChange(null);
          }}
        >
          Pick user
        </Button>
      </div>
    );
  }

  return (
    <Popover open={open} onOpenChange={setOpen} modal>
      <PopoverTrigger asChild>
        <Button
          type="button"
          variant="outline"
          role="combobox"
          disabled={disabled}
          className={cn('w-full justify-between', !value && 'text-muted-foreground', className)}
        >
          <span className="truncate">{displayLabel}</span>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" aria-hidden />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[280px] p-0" align="start">
        <Command>
          <CommandInput placeholder="Search users…" />
          <CommandList>
            <CommandEmpty>No users found.</CommandEmpty>
            <CommandGroup>
              {users.map((u) => (
                <CommandItem
                  key={u.id}
                  value={u.displayName ?? u.id}
                  onSelect={() => {
                    onChange(u.id);
                    setOpen(false);
                  }}
                >
                  <Check
                    className={cn('mr-2 h-4 w-4', value === u.id ? 'opacity-100' : 'opacity-0')}
                  />
                  {u.displayName ?? u.id.slice(0, 8)}
                </CommandItem>
              ))}
            </CommandGroup>
            <CommandGroup heading="Or">
              <CommandItem
                value="__other__"
                onSelect={() => {
                  setOpen(false);
                  setOtherMode(true);
                  onChange(null);
                }}
              >
                Other…
              </CommandItem>
              {value && !matched ? (
                <CommandItem
                  value="__clear__"
                  onSelect={() => {
                    onChange(null);
                    setOpen(false);
                  }}
                  className="text-muted-foreground"
                >
                  Clear (currently: {value})
                </CommandItem>
              ) : null}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
