import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Loader2, AlertCircle } from "lucide-react";
import { useCentralChartOfAccounts } from "@/hooks/useCentralChartOfAccounts";
import { cn } from "@/lib/utils";

interface AccountDropdownProps {
  value?: string | null;
  onChange?: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  required?: boolean;
  /** Filters accounts to the association's accounting system (zoho vs buildium). */
  associationId?: string | null;
}

export default function AccountDropdown({
  value,
  onChange,
  placeholder = "Select account...",
  disabled = false,
  className,
  required = false,
  associationId,
}: AccountDropdownProps) {
  const { accounts, loading, error } = useCentralChartOfAccounts(associationId);

  const safeValue = !value ? undefined : String(value);

  return (
    <Select
      value={safeValue}
      onValueChange={(v) => onChange?.(v)}
      disabled={disabled || loading}
      required={required}
    >
      <SelectTrigger className={cn("w-full", className)}>
        <div className="flex items-center gap-2 truncate">
          {loading && <Loader2 className="w-3.5 h-3.5 animate-spin text-muted-foreground shrink-0" />}
          {error && <AlertCircle className="w-3.5 h-3.5 text-destructive shrink-0" />}
          <SelectValue
            placeholder={
              error ? "Error loading accounts" : loading ? "Loading..." : placeholder
            }
          />
        </div>
      </SelectTrigger>

      <SelectContent className="max-h-[300px] z-[9999]">
        {accounts.map((acc) => (
          <SelectItem key={acc.id} value={String(acc.id)} className="cursor-pointer">
            <div className="flex items-center w-full">
              {acc.account_number && (
                <span className="font-mono text-muted-foreground mr-2 shrink-0 text-xs">
                  {acc.account_number}
                </span>
              )}
              <span className="truncate">{acc.account_name}</span>
              <span className="ml-auto text-xs text-muted-foreground pl-2 shrink-0">
                {acc.account_type}
              </span>
            </div>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
