import { useState } from "react";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
  SheetFooter,
} from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { useAppSettings, useSaveAppSettings, useMcpStatus } from "@/hooks/use-settings";
import { useAiSettings, useSaveAiSettings } from "@/hooks/use-ai";
import { AiSettingsFields } from "@/components/ai/AiSettingsFields";
import { Loader2, Copy, Check } from "lucide-react";
import { toast } from "sonner";
import type { AiProvider, AppSettings } from "@/types";

const SUPPORTED_AI_PROVIDERS: { value: AiProvider; label: string }[] = [
  { value: "ollama", label: "Ollama (local)" },
  { value: "fireworks", label: "Fireworks AI" },
  { value: "openrouter", label: "OpenRouter" },
];

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function AppSettingsSheet({ open, onOpenChange }: Props) {
  const { data: appSettings } = useAppSettings();
  const { data: mcpStatus } = useMcpStatus();
  const saveAppMutation = useSaveAppSettings();

  const { data: aiSettings } = useAiSettings();
  const saveAiMutation = useSaveAiSettings();

  // MCP state
  const [mcpEnabled, setMcpEnabled] = useState(true);
  const [mcpPort, setMcpPort] = useState(9427);

  // AI state
  const [aiProvider, setAiProvider] = useState<AiProvider>("ollama");
  const [ollamaUrl, setOllamaUrl] = useState("http://localhost:11434");
  const [fireworksApiKey, setFireworksApiKey] = useState("");
  const [openrouterApiKey, setOpenrouterApiKey] = useState("");
  const [aiModel, setAiModel] = useState("");

  const [copied, setCopied] = useState(false);

  // Sync form with loaded settings
  const [prevAppSettings, setPrevAppSettings] = useState(appSettings);
  if (appSettings !== prevAppSettings) {
    setPrevAppSettings(appSettings);
    if (appSettings) {
      setMcpEnabled(appSettings.mcp.enabled);
      setMcpPort(appSettings.mcp.port);
    }
  }

  const [prevAiSettings, setPrevAiSettings] = useState(aiSettings);
  if (aiSettings !== prevAiSettings) {
    setPrevAiSettings(aiSettings);
    if (aiSettings) {
      // Legacy openai/anthropic values aren't user-selectable here — fall back to ollama.
      setAiProvider(
        aiSettings.provider === "fireworks" ||
          aiSettings.provider === "openrouter"
          ? aiSettings.provider
          : "ollama"
      );
      setOllamaUrl(aiSettings.ollama_url);
      setFireworksApiKey(aiSettings.fireworks_api_key ?? "");
      setOpenrouterApiKey(aiSettings.openrouter_api_key ?? "");
      setAiModel(aiSettings.model);
    }
  }

  const handleAiProviderChange = (next: AiProvider) => {
    if (next === aiProvider) return;
    setAiProvider(next);
    // Model lists differ per provider — clear stale selection.
    setAiModel("");
  };

  const mcpEndpoint = `http://127.0.0.1:${mcpPort}/mcp`;

  const handleCopy = async () => {
    await navigator.clipboard.writeText(mcpEndpoint);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const handleSave = () => {
    const settings: AppSettings = {
      mcp: { enabled: mcpEnabled, port: mcpPort },
    };

    saveAppMutation.mutate(settings, {
      onSuccess: () => {
        toast.success("Settings saved");
      },
      onError: (err) =>
        toast.error("Failed to save settings", { description: String(err) }),
    });

    // Save AI settings separately
    saveAiMutation.mutate(
      {
        provider: aiProvider,
        ollama_url: ollamaUrl,
        fireworks_api_key:
          aiProvider === "fireworks"
            ? fireworksApiKey.trim() || undefined
            : aiSettings?.fireworks_api_key,
        openrouter_api_key:
          aiProvider === "openrouter"
            ? openrouterApiKey.trim() || undefined
            : aiSettings?.openrouter_api_key,
        model: aiModel,
      },
      {
        onError: (err) =>
          toast.error("Failed to save AI settings", { description: String(err) }),
      }
    );
  };

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent side="right" className="w-[400px] sm:max-w-[400px] overflow-y-auto">
        <SheetHeader>
          <SheetTitle>Settings</SheetTitle>
          <SheetDescription>Application configuration</SheetDescription>
        </SheetHeader>

        <div className="flex flex-col gap-6 px-4">
          {/* MCP Server */}
          <section className="flex flex-col gap-3">
            <h3 className="text-sm font-medium">MCP Server</h3>

            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">Enabled</span>
              <Button
                size="sm"
                variant={mcpEnabled ? "default" : "outline"}
                className="h-6 text-xs px-3"
                onClick={() => setMcpEnabled(!mcpEnabled)}
              >
                {mcpEnabled ? "On" : "Off"}
              </Button>
            </div>

            <div className="flex flex-col gap-1.5">
              <label className="text-xs text-muted-foreground">Port</label>
              <Input
                type="number"
                value={mcpPort}
                onChange={(e) => setMcpPort(Number(e.target.value))}
                className="h-8 text-xs"
                min={1}
                max={65535}
              />
            </div>

            <div className="flex items-center gap-2">
              <span className="text-xs text-muted-foreground">Status:</span>
              <span className="flex items-center gap-1.5 text-xs">
                <span
                  className={`inline-block h-2 w-2 rounded-full ${
                    mcpStatus?.running
                      ? "bg-success ring-2 ring-success/25"
                      : "bg-muted-foreground/30"
                  }`}
                />
                {mcpStatus?.running ? "Running" : "Stopped"}
              </span>
            </div>

            <div className="flex flex-col gap-1.5">
              <label className="text-xs text-muted-foreground">Endpoint</label>
              <div className="flex items-center gap-1">
                <code className="flex-1 rounded bg-muted px-2 py-1 text-xs font-mono truncate">
                  {mcpEndpoint}
                </code>
                <Button
                  size="sm"
                  variant="ghost"
                  className="h-7 w-7 p-0"
                  onClick={handleCopy}
                  title="Copy endpoint URL"
                >
                  {copied ? (
                    <Check className="h-3 w-3 text-success" />
                  ) : (
                    <Copy className="h-3 w-3" />
                  )}
                </Button>
              </div>
            </div>
          </section>

          <Separator />

          {/* AI */}
          <section className="flex flex-col gap-3">
            <h3 className="text-sm font-medium">AI</h3>

            <div className="flex flex-col gap-1.5">
              <label className="text-xs text-muted-foreground">Provider</label>
              <Select
                value={aiProvider}
                onValueChange={(v) => handleAiProviderChange(v as AiProvider)}
              >
                <SelectTrigger className="h-8 text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {SUPPORTED_AI_PROVIDERS.map((p) => (
                    <SelectItem key={p.value} value={p.value}>
                      {p.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <AiSettingsFields
              provider={aiProvider}
              ollamaUrl={ollamaUrl}
              onOllamaUrlChange={setOllamaUrl}
              fireworksApiKey={fireworksApiKey}
              onFireworksApiKeyChange={setFireworksApiKey}
              openrouterApiKey={openrouterApiKey}
              onOpenRouterApiKeyChange={setOpenrouterApiKey}
              model={aiModel}
              onModelChange={setAiModel}
            />
          </section>
        </div>

        <SheetFooter>
          <Button
            className="w-full"
            onClick={handleSave}
            disabled={saveAppMutation.isPending}
          >
            {saveAppMutation.isPending ? (
              <Loader2 className="h-4 w-4 animate-spin mr-2" />
            ) : null}
            Save
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}
