'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 { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useDebounce } from '@/hooks/use-debounce';
import { apiFetch } from '@/lib/api/client';
import { stageLabel } from '@/lib/constants';
import { deriveInterestBerthLabel } from '@/lib/templates/interest-berth-label';
import { cn } from '@/lib/utils';

interface InterestOption {
  id: string;
  clientName: string | null;
  berthMooringNumber: string | null;
  /** Every linked berth's mooring (sorted). Drives the multi-berth label
   *  rendered in the picker option row. */
  berthMoorings?: string[];
  pipelineStage: string;
}

interface InterestPickerProps {
  value: string | null;
  onChange: (interestId: string | null) => void;
  /** When set, only this client's interests are listed. */
  clientId?: string | null;
  placeholder?: string;
  disabled?: boolean;
}

/**
 * Searchable interest picker. Mirrors ClientPicker. When `clientId` is
 * provided the dropdown scopes to that client - so picking the client
 * first naturally narrows the interest options.
 */
export function InterestPicker({
  value,
  onChange,
  clientId,
  placeholder = 'Select interest...',
  disabled,
}: InterestPickerProps) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState('');
  const debounced = useDebounce(search, 300);

  const { data } = useQuery<{ data: InterestOption[] }>({
    queryKey: ['interest-picker', clientId ?? null, debounced],
    queryFn: () => {
      const params = new URLSearchParams({
        page: '1',
        limit: '10',
        order: 'desc',
        includeArchived: 'false',
      });
      if (debounced) params.set('search', debounced);
      if (clientId) params.set('clientId', clientId);
      return apiFetch(`/api/v1/interests?${params.toString()}`);
    },
    enabled: open,
  });

  const options = data?.data ?? [];

  const labelFor = (o: InterestOption) => {
    const parts = [o.clientName ?? 'Unknown client'];
    const berthLabel = deriveInterestBerthLabel(o.berthMoorings) ?? o.berthMooringNumber;
    if (berthLabel) parts.push(`Berth ${berthLabel}`);
    parts.push(stageLabel(o.pipelineStage));
    return parts.join(' · ');
  };

  const selectedLabel = (() => {
    if (!value) return placeholder;
    const match = options.find((o) => o.id === value);
    return match ? labelFor(match) : `Interest ${value.slice(0, 8)}`;
  })();

  return (
    // `modal` is required when this picker is rendered inside a Sheet /
    // Dialog - without it the CommandInput stays focus-blocked by the
    // outer Sheet's focus trap and clicks/typing are silently dropped.
    <Popover open={open} onOpenChange={setOpen} modal>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          disabled={disabled}
          className={cn('w-full justify-between', !value && 'text-muted-foreground')}
        >
          <span className="truncate">{selectedLabel}</span>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" aria-hidden />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[320px] p-0" align="start">
        <Command shouldFilter={false}>
          <CommandInput
            placeholder={clientId ? "Search this client's interests…" : 'Search interests…'}
            value={search}
            onValueChange={setSearch}
          />
          <CommandList>
            <CommandEmpty>No interests found.</CommandEmpty>
            <CommandGroup>
              {value ? (
                <CommandItem
                  value="__clear__"
                  onSelect={() => {
                    onChange(null);
                    setOpen(false);
                  }}
                  className="text-muted-foreground"
                >
                  Clear selection
                </CommandItem>
              ) : null}
              {options.map((o) => (
                <CommandItem
                  key={o.id}
                  value={o.id}
                  onSelect={() => {
                    onChange(o.id);
                    setOpen(false);
                  }}
                >
                  <Check
                    className={cn('mr-2 h-4 w-4', value === o.id ? 'opacity-100' : 'opacity-0')}
                  />
                  <span className="truncate">{labelFor(o)}</span>
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
