
import { useState } from 'react';
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import type { LlmModel } from '@/types';

interface ModelSelectorProps {
  value: { providerId: string; modelId: string };
  onChange: (providerId: string, modelId: string) => void;
  allModels: { providerId: string; providerName: string; model: LlmModel }[];
}

export function ModelSelector({ value, onChange, allModels }: ModelSelectorProps) {
  const [open, setOpen] = useState(false);
  
  const selectedModel = allModels.find(
    (m) => m.providerId === value.providerId && m.model.model_id === value.modelId
  );

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className="w-full justify-between"
        >
          {selectedModel
            ? `${selectedModel.model.name || selectedModel.model.model_id} (${selectedModel.providerName})`
            : (value.modelId ? `${value.modelId}` : "选择模型")}
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[400px] p-0">
        <Command>
          <CommandInput placeholder="搜索模型..." />
          <CommandList>
            <CommandEmpty>未找到模型。</CommandEmpty>
            <CommandGroup>
              {allModels.map((item) => (
                <CommandItem
                  key={`${item.providerId}-${item.model.model_id}`}
                  value={`${item.model.name || item.model.model_id} ${item.providerName}`}
                  onSelect={() => {
                    onChange(item.providerId, item.model.model_id);
                    setOpen(false);
                  }}
                >
                  <Check
                    className={cn(
                      "mr-2 h-4 w-4",
                      value.modelId === item.model.model_id && value.providerId === item.providerId
                        ? "opacity-100"
                        : "opacity-0"
                    )}
                  />
                  {item.model.name || item.model.model_id}
                  <span className="ml-2 text-xs text-muted-foreground">
                    ({item.providerName})
                  </span>
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}

