import React from 'react';
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Sparkles, ChevronDown, Check } from 'lucide-react';
import { cn } from '@/utils';
import type { ModelConfig } from '@/types/model';

const capitalize = (s: string) => s ? s.charAt(0).toUpperCase() + s.slice(1) : '';

export function ModelSelector({
    selectedModelId,
    models,
    onSelect
}: {
    selectedModelId: string,
    models: Record<string, ModelConfig>,
    onSelect: (id: string) => void
}) {
    React.useEffect(() => {
        console.log('[ModelSelector] models:', models, 'count:', Object.keys(models).length);
    }, [models]);

    const selectedModel = models[selectedModelId];
    const SelectedIcon = selectedModel?.icon || Sparkles;

    const sortedModels = React.useMemo(() => {
        const values = Object.values(models);
        console.log('[ModelSelector] sortedModels values:', values.length);
        return values.sort((a, b) => {
            if (a.is_default && !b.is_default) return -1;
            if (!a.is_default && b.is_default) return 1;
            return a.name.localeCompare(b.name);
        });
    }, [models]);

    if (!sortedModels.length) {
        console.log('[ModelSelector] No models available, rendering placeholder');
        return (
            <div className="flex items-center gap-1.5 px-2 py-1 rounded-full text-[10px] font-bold text-muted-foreground">
                <Sparkles className="w-3 h-3" />
                <span>加载中...</span>
            </div>
        );
    }

    return (
        <Popover>
            <PopoverTrigger asChild>
                <div className="flex items-center gap-1.5 px-2 py-1 rounded-full hover:bg-white/5 cursor-pointer transition-colors text-[10px] font-bold text-muted-foreground hover:text-cyan-400 group">
                    <SelectedIcon className="w-3 h-3 group-hover:text-cyan-400 transition-colors" />
                    <span className="truncate max-w-[100px]">
                        {selectedModel?.name || "Select Model"}
                    </span>
                    <ChevronDown size={10} className="opacity-50 group-hover:opacity-100 transition-opacity" />
                </div>
            </PopoverTrigger>
            <PopoverContent
                className="w-56 p-1 bg-black/40 backdrop-blur-xl border-white/10 z-[1000] shadow-2xl rounded-xl interaction-model-popover"
                side="top"
                align="start"
                sideOffset={10}
            >
                <div className="max-h-[280px] overflow-y-auto custom-scrollbar flex flex-col gap-0.5">
                    {sortedModels.map((m: ModelConfig) => {
                         const isSelected = selectedModelId === m.id;
                         const Icon = m.icon;

                         return (
                            <div
                                key={m.id}
                                onClick={() => onSelect(m.id)}
                                className={cn(
                                    "px-3 py-2 rounded-lg text-[11px] font-medium cursor-pointer transition-all flex items-center justify-between group",
                                    isSelected
                                        ? "bg-blue-500/10 text-blue-400"
                                        : "text-foreground/70 hover:bg-white/5 hover:text-foreground"
                                )}
                            >
                                <div className="flex items-center gap-2.5 overflow-hidden">
                                    <div className={cn(
                                        "w-5 h-5 rounded-md flex items-center justify-center transition-colors",
                                        isSelected ? "bg-blue-500/20" : "bg-white/5 group-hover:bg-white/10"
                                    )}>
                                        {Icon ? <Icon size={12} /> : <Sparkles size={12} />}
                                    </div>
                                    <div className="flex flex-col truncate">
                                        <span className="truncate">{m.name}</span>
                                        <div className="flex items-center gap-1">
                                            <span className="text-[9px] text-foreground/30 font-normal truncate">
                                                {m.provider_name || capitalize(m.provider)}
                                            </span>
                                            <span className="text-[9px] px-1 py-0.5 rounded bg-white/10 text-foreground/50 uppercase">
                                                {m.type}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                {isSelected && <Check size={12} className="text-blue-400 shrink-0 ml-2" />}
                            </div>
                        );
                    })}
                </div>
            </PopoverContent>
        </Popover>
    );
}
