import { useQuery } from "@tanstack/react-query";
import { cn } from "@/lib/utils";
import { api } from "@/services/api";
import { Loader2, AlertCircle } from "lucide-react";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@edr/ui-common";

export interface DynamicSelectProps {
  code: string;
  placeholder?: string;
  value?: string;
  onValueChange?: (value: string) => void;
  disabled?: boolean;
  className?: string;
}

export function DynamicSelect({
  code,
  placeholder,
  value,
  onValueChange,
  disabled,
  className,
}: DynamicSelectProps) {
  const { data, isLoading, isError } = useQuery(
    api.dropdownSettings.getByCode.queryOptions({ input: { code } }),
  );

  if (isLoading) {
    return (
      <div
        className={cn(
          "flex h-9 w-full items-center gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm text-muted-foreground",
          className,
        )}
      >
        <Loader2 className="size-4 animate-spin" />
        Loading...
      </div>
    );
  }

  if (isError || !data) {
    return (
      <div
        className={cn(
          "flex h-9 w-full items-center gap-2 rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive",
          className,
        )}
      >
        <AlertCircle className="size-4 shrink-0" />
        Failed to load options
      </div>
    );
  }

  const options = [...data.children].sort((a, b) => a.order - b.order);

  return (
    <Select value={value} onValueChange={onValueChange} disabled={disabled}>
      <SelectTrigger className={cn("w-full", className)}>
        <SelectValue placeholder={placeholder ?? `Select ${data.label}`} />
      </SelectTrigger>
      <SelectContent>
        {options.length === 0 ? (
          <div className="p-2 text-center text-sm text-muted-foreground">
            No options available
          </div>
        ) : (
          options.map((option) => (
            <SelectItem
              key={option.id}
              value={option.value}
              disabled={option.disabled}
            >
              {option.label}
              {option.note ? (
                <span className="ml-1 text-xs text-muted-foreground">
                  {option.note}
                </span>
              ) : null}
            </SelectItem>
          ))
        )}
      </SelectContent>
    </Select>
  );
}
