"use client";

import { useState, useEffect, useCallback } from "react";
import { useSettings } from "@/app/lib/settings";
import { useAppStore } from "@/app/lib/store";
import { fetchClients, pingServer, ApiError } from "@/app/lib/api";
import { bootstrapLocalApiKey, isDesktopRuntime } from "@/app/lib/desktop";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { toast } from "sonner";
import { Bot, Globe, Settings, SlidersHorizontal } from "lucide-react";
import { ConnectionSettingsTab } from "./settings/ConnectionSettingsTab";
import { PreferencesSettingsTab } from "./settings/PreferencesSettingsTab";
import { AiSettingsTab } from "./settings/AiSettingsTab";

type ConnectionStatus = {
  testing: boolean;
  ok: boolean | null;
  latencyMs: number | null;
  version: string | null;
  error: string | null;
};

export default function SettingsPage() {
  const {
    baseUrl,
    apiKey,
    localBackupApiKey,
    pgDumpPath,
    pgRestorePath,
    openRouterUrl,
    openRouterApiKey,
    openRouterModel,
    openRouterSiteUrl,
    openRouterAppName,
    openRouterSystemPrompt,
    openRouterTemperature,
    openRouterMaxTokens,
    setBaseUrl,
    setApiKey,
    setLocalBackupApiKey,
    setPgDumpPath,
    setPgRestorePath,
    setOpenRouterUrl,
    setOpenRouterApiKey,
    setOpenRouterModel,
    setOpenRouterSiteUrl,
    setOpenRouterAppName,
    setOpenRouterSystemPrompt,
    setOpenRouterTemperature,
    setOpenRouterMaxTokens,
    isLocalBuild,
  } = useSettings();

  const { preferences, setPreferences } = useAppStore();
  const [localUrl, setLocalUrl] = useState(baseUrl);
  const [localKey, setLocalKey] = useState(apiKey);
  const [localPgDumpPath, setLocalPgDumpPath] = useState(pgDumpPath);
  const [localPgRestorePath, setLocalPgRestorePath] = useState(pgRestorePath);
  const [showKey, setShowKey] = useState(false);
  const [showOpenRouterKey, setShowOpenRouterKey] = useState(false);
  const [localOpenRouterUrl, setLocalOpenRouterUrl] = useState(openRouterUrl);
  const [localOpenRouterKey, setLocalOpenRouterKey] =
    useState(openRouterApiKey);
  const [localOpenRouterModel, setLocalOpenRouterModel] =
    useState(openRouterModel);
  const [localOpenRouterSiteUrl, setLocalOpenRouterSiteUrl] =
    useState(openRouterSiteUrl);
  const [localOpenRouterAppName, setLocalOpenRouterAppName] =
    useState(openRouterAppName);
  const [localOpenRouterSystemPrompt, setLocalOpenRouterSystemPrompt] =
    useState(openRouterSystemPrompt);
  const [localOpenRouterTemperature, setLocalOpenRouterTemperature] = useState(
    String(openRouterTemperature),
  );
  const [localOpenRouterMaxTokens, setLocalOpenRouterMaxTokens] = useState(
    String(openRouterMaxTokens),
  );
  const [connStatus, setConnStatus] = useState<ConnectionStatus>({
    testing: false,
    ok: null,
    latencyMs: null,
    version: null,
    error: null,
  });
  const [clients, setClients] = useState<string[]>([]);
  const [clientsLoading, setClientsLoading] = useState(false);
  const [clientsError, setClientsError] = useState<string | null>(null);
  const [bootstrappingKey, setBootstrappingKey] = useState(false);

  const effectiveApiKey = apiKey || localBackupApiKey;

  const isDesktop = isDesktopRuntime();
  const isDesktopLocalTarget =
    isDesktop &&
    (baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1"));

  const testConnection = useCallback(async (url: string) => {
    setConnStatus({
      testing: true,
      ok: null,
      latencyMs: null,
      version: null,
      error: null,
    });

    const result = await pingServer(url);
    setConnStatus({
      testing: false,
      ok: result.ok,
      latencyMs: Math.round(result.latencyMs),
      version: result.version ?? null,
      error: result.ok ? null : "Server unreachable",
    });

    if (result.ok) {
      toast.success(`Connected to ${url}`, {
        description: `v${result.version ?? "?"} - ${Math.round(result.latencyMs)}ms`,
      });
    } else {
      toast.error("Connection failed", {
        description: `Could not reach ${url}`,
      });
    }
  }, []);

  const loadClients = useCallback(
    async (key?: string) => {
      const resolvedKey = key ?? effectiveApiKey;
      if (!resolvedKey) return;

      setClientsLoading(true);
      setClientsError(null);
      try {
        const result = await fetchClients({
          baseUrl,
          apiKey,
          localBackupApiKey: resolvedKey,
        });
        setClients(result);
      } catch (err) {
        const msg =
          err instanceof ApiError ? err.message : "Failed to load clients";
        setClientsError(msg);
      } finally {
        setClientsLoading(false);
      }
    },
    [baseUrl, apiKey, effectiveApiKey],
  );

  useEffect(() => {
    if (baseUrl) testConnection(baseUrl);
  }, [baseUrl, testConnection]);

  useEffect(() => {
    if (effectiveApiKey && baseUrl) loadClients();
  }, [effectiveApiKey, baseUrl, loadClients]);

  const handleSaveUrl = () => {
    setBaseUrl(localUrl);
    testConnection(localUrl);
  };

  const handleSaveKey = () => {
    setApiKey(localKey);
    toast.success("API key saved", {
      description: "Stored securely in your browser",
    });
  };

  const handleClearKey = () => {
    setLocalKey("");
    setApiKey("");
    setClients([]);
    toast.info("API key cleared");
  };

  const handleBootstrapLocalKey = async () => {
    setBootstrappingKey(true);
    try {
      const generated = await bootstrapLocalApiKey("Athena Desktop Local Key");
      if (!generated) {
        throw new Error("Unable to bootstrap local API key");
      }

      setLocalBackupApiKey(generated);

      // If currently pointed at local API only, mirror it as the active key.
      if (isDesktopLocalTarget && !apiKey) {
        setLocalKey(generated);
        setApiKey(generated);
        await loadClients(generated);
      }

      toast.success("Local API key created", {
        description:
          "Saved as local backup key for desktop proxy backup/restore calls.",
      });
    } catch (err) {
      toast.error("Failed to create local API key", {
        description:
          err instanceof Error ? err.message : "Unknown bootstrap error",
      });
    } finally {
      setBootstrappingKey(false);
    }
  };

  const handleSavePgTools = () => {
    setPgDumpPath(localPgDumpPath);
    setPgRestorePath(localPgRestorePath);
    toast.success("PostgreSQL tool paths saved", {
      description: "These values are sent as backup request overrides.",
    });
  };

  const handleSaveOpenRouter = () => {
    const parsedTemperature = Number(localOpenRouterTemperature);
    const parsedMaxTokens = Number(localOpenRouterMaxTokens);

    setOpenRouterUrl(localOpenRouterUrl);
    setOpenRouterApiKey(localOpenRouterKey);
    setOpenRouterModel(localOpenRouterModel);
    setOpenRouterSiteUrl(localOpenRouterSiteUrl);
    setOpenRouterAppName(localOpenRouterAppName);
    setOpenRouterSystemPrompt(localOpenRouterSystemPrompt);
    if (Number.isFinite(parsedTemperature)) {
      setOpenRouterTemperature(parsedTemperature);
    }
    if (Number.isFinite(parsedMaxTokens)) {
      setOpenRouterMaxTokens(parsedMaxTokens);
    }

    toast.success("AI settings saved", {
      description: "OpenRouter settings are stored in your browser.",
    });
  };

  const handleClearOpenRouterKey = () => {
    setLocalOpenRouterKey("");
    setOpenRouterApiKey("");
    toast.info("OpenRouter key cleared");
  };

  const openRouterConfigured = Boolean(openRouterApiKey && openRouterModel);

  return (
    <div className="flex flex-1 flex-col min-h-0">
      <div className="flex items-center gap-4 border-b border-border px-6 py-4">
        <Settings className="h-5 w-5 text-primary" />
        <div>
          <h2 className="text-sm font-semibold text-foreground">Settings</h2>
          <p className="text-body-sm text-muted-foreground mt-0.5">
            Configure connection, authentication, and preferences
          </p>
        </div>
      </div>

      <Tabs defaultValue="connection" className="flex flex-col flex-1 min-h-0">
        <div className="border-b border-border px-6">
          <TabsList className="h-9">
            <TabsTrigger value="connection">
              <Globe className="mr-1 h-3 w-3" /> Connection
            </TabsTrigger>
            <TabsTrigger value="preferences">
              <SlidersHorizontal className="mr-1 h-3 w-3" /> Preferences
            </TabsTrigger>
            <TabsTrigger value="ai">
              <Bot className="mr-1 h-3 w-3" /> AI
            </TabsTrigger>
          </TabsList>
        </div>

        <TabsContent value="connection" className="flex-1 m-0 overflow-hidden">
          <ConnectionSettingsTab
            baseUrl={baseUrl}
            apiKey={apiKey}
            localBackupApiKey={localBackupApiKey}
            pgDumpPath={pgDumpPath}
            pgRestorePath={pgRestorePath}
            isLocalBuild={isLocalBuild}
            isDesktopRuntime={isDesktop}
            isDesktopLocalTarget={isDesktopLocalTarget}
            localUrl={localUrl}
            setLocalUrl={setLocalUrl}
            localKey={localKey}
            setLocalKey={setLocalKey}
            localPgDumpPath={localPgDumpPath}
            setLocalPgDumpPath={setLocalPgDumpPath}
            localPgRestorePath={localPgRestorePath}
            setLocalPgRestorePath={setLocalPgRestorePath}
            showKey={showKey}
            setShowKey={setShowKey}
            connStatus={connStatus}
            clients={clients}
            clientsLoading={clientsLoading}
            clientsError={clientsError}
            bootstrappingKey={bootstrappingKey}
            onSaveUrl={handleSaveUrl}
            onSaveKey={handleSaveKey}
            onClearKey={handleClearKey}
            onBootstrapLocalKey={handleBootstrapLocalKey}
            onSavePgTools={handleSavePgTools}
            onTestConnection={testConnection}
            onSetBaseUrl={setBaseUrl}
          />
        </TabsContent>

        <TabsContent value="preferences" className="flex-1 m-0 overflow-hidden">
          <PreferencesSettingsTab
            preferences={preferences}
            setPreferences={setPreferences}
          />
        </TabsContent>

        <TabsContent value="ai" className="flex-1 m-0 overflow-hidden">
          <AiSettingsTab
            localOpenRouterUrl={localOpenRouterUrl}
            setLocalOpenRouterUrl={setLocalOpenRouterUrl}
            localOpenRouterKey={localOpenRouterKey}
            setLocalOpenRouterKey={setLocalOpenRouterKey}
            localOpenRouterModel={localOpenRouterModel}
            setLocalOpenRouterModel={setLocalOpenRouterModel}
            localOpenRouterSiteUrl={localOpenRouterSiteUrl}
            setLocalOpenRouterSiteUrl={setLocalOpenRouterSiteUrl}
            localOpenRouterAppName={localOpenRouterAppName}
            setLocalOpenRouterAppName={setLocalOpenRouterAppName}
            localOpenRouterSystemPrompt={localOpenRouterSystemPrompt}
            setLocalOpenRouterSystemPrompt={setLocalOpenRouterSystemPrompt}
            localOpenRouterTemperature={localOpenRouterTemperature}
            setLocalOpenRouterTemperature={setLocalOpenRouterTemperature}
            localOpenRouterMaxTokens={localOpenRouterMaxTokens}
            setLocalOpenRouterMaxTokens={setLocalOpenRouterMaxTokens}
            showOpenRouterKey={showOpenRouterKey}
            setShowOpenRouterKey={setShowOpenRouterKey}
            onSave={handleSaveOpenRouter}
            onClearKey={handleClearOpenRouterKey}
            openRouterConfigured={openRouterConfigured}
          />
        </TabsContent>
      </Tabs>
    </div>
  );
}
