import { useState, useEffect } from "react";
import { Cpu, ChevronDown, User, Globe } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { getProviders, stripThinkingBlocks, type ProvidersResponse } from "@/api";
import { useLoopRuntimeExtra } from "@/useLoopRuntime";

export default function ModelSelector() {
  const { provider, selectProvider, thinkingBlockCount, loopId } = useLoopRuntimeExtra();
  const [providers, setProviders] = useState<ProvidersResponse | null>(null);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    getProviders().then(setProviders);
  }, []);

  const currentName = provider?.name || "default";
  const currentModel = provider?.model || "";
  const entries = providers ? Object.entries(providers.providers) : [];

  // Thinking blocks are cryptographically signed by the provider that
  // generated them. Switching between Claude and non-Claude models makes
  // those signatures invalid → API 400 on the next turn. We pre-empt that
  // by offering to strip them.
  const isClaudeModel = (model: string) => model.toLowerCase().startsWith("claude");
  const onPickProvider = async (name: string, source?: "personal" | "workspace") => {
    setOpen(false);
    if (name === currentName) return;
    const currentModel = providers?.providers?.[currentName]?.model || "";
    const newModel = providers?.providers?.[name]?.model || "";
    const crossClaudeBoundary = isClaudeModel(currentModel) !== isClaudeModel(newModel);
    if (crossClaudeBoundary && thinkingBlockCount > 0 && loopId) {
      const msg =
        `Switching between Claude and non-Claude models makes the ${thinkingBlockCount} ` +
        `existing thinking block${thinkingBlockCount === 1 ? "" : "s"} in this conversation ` +
        `fail signature validation.\n\n` +
        `Click OK to remove them from the AI's context (chat history stays). ` +
        `Cancel to keep the current provider.`;
      if (!window.confirm(msg)) return;
      await stripThinkingBlocks(loopId);
    }
    selectProvider(name, source);
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <button
          type="button"
          className="flex items-center gap-1 rounded-md border border-gray-200 bg-gray-50 px-1.5 py-0.5 text-[10px] text-gray-500 hover:bg-gray-100 transition-colors"
          title="Select model"
          aria-label="Select model"
        >
          <Cpu className="h-3 w-3" />
          <span className="font-medium text-gray-700 truncate max-w-16 md:max-w-24">{currentName}</span>
          {currentModel && (
            <>
              <span className="hidden md:inline text-gray-400">·</span>
              <span className="hidden md:inline font-mono truncate max-w-20">{currentModel}</span>
            </>
          )}
          <ChevronDown className="h-2.5 w-2.5 text-gray-400" />
        </button>
      </PopoverTrigger>

      <PopoverContent className="w-80">
        <div className="border-b border-gray-200 p-3">
          <h3 className="text-sm font-semibold text-gray-900">Model</h3>
          <p className="mt-0.5 text-xs text-gray-500">
            Select provider and model (only before first message)
          </p>
        </div>

        <div className="max-h-64 overflow-y-auto py-1">
          {entries.map(([name, info]) => {
            const isActive = name === currentName;
            const isPersonal = info.source === "personal";
            return (
              <button
                key={name}
                type="button"
                onClick={() => onPickProvider(name, info.source)}
                className={`w-full px-4 py-2.5 text-left transition-colors hover:bg-gray-50 ${
                  isActive ? "bg-blue-50" : ""
                }`}
              >
                <div className="flex items-center justify-between">
                  <span
                    className={`text-sm font-medium ${
                      isActive ? "text-blue-700" : "text-gray-700"
                    }`}
                  >
                    {name}
                  </span>
                  <span
                    className={`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[9px] font-medium ${
                      isPersonal
                        ? "bg-violet-100 text-violet-700"
                        : "bg-gray-100 text-gray-500"
                    }`}
                  >
                    {isPersonal ? (
                      <User className="h-2.5 w-2.5" />
                    ) : (
                      <Globe className="h-2.5 w-2.5" />
                    )}
                    {isPersonal ? "personal" : "workspace"}
                  </span>
                </div>
                <div className="mt-0.5 font-mono text-[11px] text-gray-500">
                  {info.model}
                </div>
              </button>
            );
          })}
        </div>
      </PopoverContent>
    </Popover>
  );
}
