'use client';

import { useMemo, useState } from 'react';
import { Check, ChevronsUpDown } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';

export type AccountCodeOption = {
  code: string;
  label: string;
};

type Props = {
  value?: string;
  options: AccountCodeOption[];
  placeholder?: string;
  searchPlaceholder?: string;
  emptyLabel?: string;
  disablePortal?: boolean;
  onValueChange: (value: string) => void;
};

export default function AccountCodeSelector({
  value,
  options,
  placeholder = 'اختر الحساب',
  searchPlaceholder = 'ابحث برمز/اسم الحساب...',
  emptyLabel = 'لا توجد نتائج',
  disablePortal = false,
  onValueChange,
}: Props) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState('');

  const selected = useMemo(() => options.find((option) => option.code === value), [options, value]);
  const filtered = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    if (!normalized) return options;

    return options.filter((option) => option.label.toLowerCase().includes(normalized) || option.code.toLowerCase().includes(normalized));
  }, [options, query]);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button type="button" variant="outline" role="combobox" className={cn('w-full justify-between', !selected && 'text-muted-foreground')}>
          {selected?.label || placeholder}
          <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent disablePortal={disablePortal} className="w-[--radix-popover-trigger-width] p-0">
        <div className="p-2 border-b">
          <Input placeholder={searchPlaceholder} value={query} onChange={(event) => setQuery(event.target.value)} autoFocus />
        </div>

        <div className="max-h-60 overflow-y-auto">
          {filtered.length > 0 ? (
            filtered.map((option) => (
              <button
                key={option.code}
                type="button"
                className={cn('w-full flex items-center gap-2 text-start px-2 py-1.5 text-sm hover:bg-accent', option.code === value && 'bg-accent')}
                onClick={() => {
                  onValueChange(option.code);
                  setOpen(false);
                  setQuery('');
                }}
              >
                <Check className={cn('h-4 w-4', option.code === value ? 'opacity-100' : 'opacity-0')} />
                <span className="flex-1">{option.label}</span>
              </button>
            ))
          ) : (
            <div className="px-3 py-4 text-center text-sm text-muted-foreground">{emptyLabel}</div>
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}
