'use client';

import { Search } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/shared/Button';
import { Input } from '@/components/ui/shared/Input';
import type { LinkedOrganizationOption } from '@/types/treatment';

interface LinkedOrganizationSearchComboboxProps {
  search: string;
  onSearchChange: (value: string) => void;
  organizations: LinkedOrganizationOption[];
  selectedOrganizationId?: string | null;
  onSelectOrganization: (org: LinkedOrganizationOption) => void;
  disabled?: boolean;
  canInviteLab?: boolean;
  onInviteLab?: () => void;
  placeholder?: string;
  emptyResultsMessage?: string;
  noPermissionMessage?: string;
}

export function LinkedOrganizationSearchCombobox({
  search,
  onSearchChange,
  organizations,
  selectedOrganizationId,
  onSelectOrganization,
  disabled = false,
  canInviteLab = false,
  onInviteLab,
  placeholder,
  emptyResultsMessage,
  noPermissionMessage,
}: LinkedOrganizationSearchComboboxProps) {
  const t = useTranslations('treatment');
  const trimmed = search.trim();
  const showResults = !disabled && trimmed.length > 0;

  const filtered = trimmed
    ? organizations.filter((o) => o.name.toLowerCase().includes(trimmed.toLowerCase()))
    : [];

  const selectedOrg = selectedOrganizationId
    ? organizations.find((o) => o.id === selectedOrganizationId)
    : null;

  function handleSelect(org: LinkedOrganizationOption) {
    onSelectOrganization(org);
    onSearchChange('');
  }

  return (
    <div className="space-y-2">
      <Input
        placeholder={placeholder ?? t('searchOrgsPlaceholder')}
        value={search}
        onChange={(e) => onSearchChange(e.target.value)}
        disabled={disabled}
        icon={<Search className="h-4 w-4 icon-flat" />}
      />

      {selectedOrg && !trimmed ? (
        <p className="text-sm text-text-primary rounded-[var(--radius-md)] border border-border bg-background-secondary/60 px-3 py-2">
          {selectedOrg.name}
        </p>
      ) : null}

      {showResults ? (
        <div className="space-y-2 rounded-[var(--radius-md)] border border-border/60 bg-background-secondary/30 p-2">
          {filtered.length === 0 ? (
            <div className="space-y-2 px-1 py-1">
              <p className="text-sm text-text-muted">
                {emptyResultsMessage ?? t('noOrgMatch')}
              </p>
              {canInviteLab && onInviteLab ? (
                <Button type="button" variant="primary" onClick={onInviteLab} fullWidth>
                  {t('inviteLab')}
                </Button>
              ) : noPermissionMessage ? (
                <p className="text-xs text-text-muted">{noPermissionMessage}</p>
              ) : null}
            </div>
          ) : (
            <div className="max-h-48 space-y-1.5 overflow-y-auto overscroll-y-contain pr-1">
              {filtered.map((org) => {
                const isSelected = selectedOrganizationId === org.id;
                return (
                  <button
                    key={org.id}
                    type="button"
                    onClick={() => handleSelect(org)}
                    className={`w-full rounded-[var(--radius-sm)] border px-2.5 py-2 text-left text-sm transition-colors ${
                      isSelected
                        ? 'border-primary/60 bg-primary-soft'
                        : 'border-transparent hover:bg-background-card/70'
                    }`}
                  >
                    {org.name}
                  </button>
                );
              })}
            </div>
          )}
        </div>
      ) : null}
    </div>
  );
}
