import { useTranslation } from '@/hooks/use-translation';
import { Search } from 'lucide-react';
import { useMemo, useState } from 'react';
import type { OwnerOption } from '../types';

/** Rows shown at once. The list is bounded by COUNT, never by a pixel height. */
const MAX_VISIBLE = 6;

/**
 * Existing-propriétaire picker for the onboarding wizard.
 *
 * Deliberately NOT a combobox/popover: the wizard already lives in a scrolling
 * dialog, and an overlay list with its own `overflow-y` produced a scrollbar
 * inside a scrollbar. Here the search field and the results sit in the normal
 * document flow and the result list is capped at MAX_VISIBLE rows — long lists
 * are narrowed by typing, not by scrolling. The dialog stays the only scroller.
 */
export const OwnerPicker = ({ owners, onSelect }: { owners: OwnerOption[]; onSelect: (owner: OwnerOption) => void }) => {
    const { t } = useTranslation();
    const [query, setQuery] = useState('');

    const filtered = useMemo(() => {
        const q = query.trim().toLowerCase();
        if (!q) return owners;
        return owners.filter((o) => `${o.name} ${o.last_name ?? ''} ${o.email} ${o.phone ?? ''}`.toLowerCase().includes(q));
    }, [owners, query]);

    const visible = filtered.slice(0, MAX_VISIBLE);
    const hiddenCount = filtered.length - visible.length;

    return (
        <div>
            <div className="focus-within:border-secondary flex items-center gap-2 rounded-md border px-3 py-2 transition-colors">
                <Search className="text-muted-foreground h-4 w-4 shrink-0" />
                <input
                    type="text"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    placeholder={t('crm', 'owner_combobox_search_placeholder')}
                    className="placeholder:text-muted-foreground h-6 flex-1 bg-transparent text-sm outline-none"
                    autoComplete="off"
                    // Enter must not bubble up and make the wizard jump to step 2.
                    onKeyDown={(e) => {
                        if (e.key !== 'Enter') return;
                        e.preventDefault();
                        if (filtered.length === 1) onSelect(filtered[0]);
                    }}
                />
            </div>

            {visible.length === 0 ? (
                <p className="text-muted-foreground mt-2 px-1 py-4 text-center text-sm">{t('crm', 'owner_combobox_empty')}</p>
            ) : (
                <div className="mt-2 divide-y rounded-md border">
                    {visible.map((owner) => (
                        <button
                            key={owner.id}
                            type="button"
                            onClick={() => onSelect(owner)}
                            className="hover:bg-accent hover:text-accent-foreground flex w-full cursor-pointer flex-col items-start px-3 py-2 text-left transition-colors first:rounded-t-md last:rounded-b-md"
                        >
                            <span className="text-sm font-medium">
                                {owner.name} {owner.last_name ?? ''}
                            </span>
                            <span className="text-muted-foreground text-xs">{owner.email}</span>
                        </button>
                    ))}
                </div>
            )}

            {hiddenCount > 0 && (
                <p className="text-muted-foreground mt-2 px-1 text-xs">
                    {hiddenCount} {t('crm', 'owner_picker_more')}
                </p>
            )}
        </div>
    );
};
