import { router, usePage } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import { ChevronDown, Check, Search } from 'lucide-react';

type Account = { id: number; name: string };

/** Admin-only portfolio switcher. Renders nothing when the list is empty. */
export function AccountSelector() {
    const { rentec } = usePage().props as unknown as {
        rentec?: { accounts: Account[]; activeId: number | null };
    };

    const [open, setOpen] = useState(false);
    const [q, setQ] = useState('');

    const accounts = rentec?.accounts ?? [];
    const activeId = rentec?.activeId ?? null;

    const active = useMemo(
        () => accounts.find((a) => a.id === activeId) ?? null,
        [accounts, activeId],
    );

    const filtered = useMemo(() => {
        const needle = q.trim().toLowerCase();
        return needle ? accounts.filter((a) => a.name.toLowerCase().includes(needle)) : accounts;
    }, [accounts, q]);

    if (accounts.length === 0) return null;

    function choose(id: number) {
        setOpen(false);
        setQ('');
        router.post('/portfolio/account', { account_id: id }, { preserveScroll: true });
    }

    return (
        <div className="relative">
            <button
                type="button"
                onClick={() => setOpen((v) => !v)}
                className="flex items-center gap-2 rounded-md border border-border bg-background px-3 py-1.5 text-sm"
            >
                <span className="text-xs uppercase tracking-wide text-muted-foreground">Account</span>
                <span className="font-medium">{active?.name ?? 'Select'}</span>
                <ChevronDown className="size-4 text-muted-foreground" />
            </button>

            {open && (
                <div className="absolute right-0 z-50 mt-1 w-72 rounded-md border border-border bg-background shadow-lg">
                    <div className="flex items-center gap-2 border-b border-border px-3 py-2">
                        <Search className="size-4 text-muted-foreground" />
                        <input
                            autoFocus
                            value={q}
                            onChange={(e) => setQ(e.target.value)}
                            placeholder="Search accounts"
                            className="w-full bg-transparent text-sm outline-none"
                        />
                    </div>
                    <ul className="max-h-80 overflow-y-auto py-1">
                        {filtered.map((a) => (
                            <li key={a.id}>
                                <button
                                    type="button"
                                    onClick={() => choose(a.id)}
                                    className="flex w-full items-center justify-between px-3 py-1.5 text-left text-sm hover:bg-muted"
                                >
                                    <span>{a.name}</span>
                                    {a.id === activeId && <Check className="size-4 text-primary" />}
                                </button>
                            </li>
                        ))}
                        {filtered.length === 0 && (
                            <li className="px-3 py-2 text-sm text-muted-foreground">No matches</li>
                        )}
                    </ul>
                </div>
            )}
        </div>
    );
}
