"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useState } from "react";
import { Copy, RefreshCw, AlertTriangle, Check, Key, Clock } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Button } from "@open-mercato/ui/primitives/button";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
function SessionKeyDialog({ open, onOpenChange }) {
  const t = useT();
  const [sessionToken, setSessionToken] = useState(null);
  const [expiresAt, setExpiresAt] = useState(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [copiedToken, setCopiedToken] = useState(false);
  const [copiedInstructions, setCopiedInstructions] = useState(false);
  const [error, setError] = useState(null);
  const generateSessionKey = async () => {
    setIsGenerating(true);
    setError(null);
    try {
      const res = await apiCall("/api/ai_assistant/session-key", {
        method: "POST"
      });
      if (res.ok && res.result?.sessionToken) {
        setSessionToken(res.result.sessionToken);
        setExpiresAt(res.result.expiresAt);
      } else {
        setError(t("ai_assistant.session.error.failed"));
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : t("ai_assistant.session.error.failed"));
    } finally {
      setIsGenerating(false);
    }
  };
  React.useEffect(() => {
    if (open && !sessionToken && !isGenerating) {
      generateSessionKey();
    }
  }, [open]);
  const llmInstructions = `You have access to Open Mercato MCP tools for managing business data (customers, orders, products, etc.).

IMPORTANT: Include "_sessionToken" in EVERY tool call:
{
  "_sessionToken": "${sessionToken || "sess_abc123..."}",
  ...other parameters
}

Workflow (use this order):
1. "discover_schema" - Understand entities, fields, and relationships first
   Examples: { "query": "customer" }, { "query": "orders" }, { "query": "products" }
2. "find_api" - Find the API endpoint for your operation (list, get, create, update, delete)
3. "call_api" - Execute the API call with proper parameters`;
  const copyToken = async () => {
    if (sessionToken) {
      await navigator.clipboard.writeText(sessionToken);
      setCopiedToken(true);
      setTimeout(() => setCopiedToken(false), 2e3);
    }
  };
  const copyInstructions = async () => {
    await navigator.clipboard.writeText(llmInstructions);
    setCopiedInstructions(true);
    setTimeout(() => setCopiedInstructions(false), 2e3);
  };
  const handleKeyDown = React.useCallback(
    (event) => {
      if (event.key === "Escape") {
        event.preventDefault();
        onOpenChange(false);
      }
    },
    [onOpenChange]
  );
  const handleClose = () => {
    setSessionToken(null);
    setExpiresAt(null);
    setError(null);
    setCopiedToken(false);
    setCopiedInstructions(false);
    onOpenChange(false);
  };
  const formatExpiry = (isoDate) => {
    if (!isoDate) return t("ai_assistant.session.expiresDefault");
    const date = new Date(isoDate);
    return date.toLocaleString();
  };
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: handleClose, children: /* @__PURE__ */ jsxs(DialogContent, { onKeyDown: handleKeyDown, className: "sm:max-w-2xl", children: [
    /* @__PURE__ */ jsxs(DialogHeader, { children: [
      /* @__PURE__ */ jsxs(DialogTitle, { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsx(Key, { className: "h-5 w-5" }),
        t("ai_assistant.session.title")
      ] }),
      /* @__PURE__ */ jsx(DialogDescription, { children: t("ai_assistant.session.description") })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      isGenerating && !sessionToken ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center py-8 text-muted-foreground", children: [
        /* @__PURE__ */ jsx(RefreshCw, { className: "h-5 w-5 animate-spin mr-2" }),
        t("ai_assistant.session.generating")
      ] }) : sessionToken ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: t("ai_assistant.session.tokenLabel") }),
            /* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: copyToken, className: "gap-1.5", children: [
              copiedToken ? /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" }) : /* @__PURE__ */ jsx(Copy, { className: "h-3.5 w-3.5" }),
              copiedToken ? t("ai_assistant.session.copied") : t("ai_assistant.session.copy")
            ] })
          ] }),
          /* @__PURE__ */ jsx("code", { className: "block text-xs bg-muted px-3 py-2 rounded font-mono break-all", children: sessionToken })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
          /* @__PURE__ */ jsx(Clock, { className: "h-4 w-4" }),
          /* @__PURE__ */ jsxs("span", { children: [
            t("ai_assistant.session.expires"),
            " ",
            formatExpiry(expiresAt)
          ] })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "border-t" }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: t("ai_assistant.session.llmInstructions") }),
            /* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: copyInstructions, className: "gap-1.5", children: [
              copiedInstructions ? /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" }) : /* @__PURE__ */ jsx(Copy, { className: "h-3.5 w-3.5" }),
              copiedInstructions ? t("ai_assistant.session.copied") : t("ai_assistant.session.copy")
            ] })
          ] }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("ai_assistant.session.copyToSystemPrompt") }),
          /* @__PURE__ */ jsx("pre", { className: "bg-muted/50 rounded-lg p-4 text-xs font-mono overflow-x-auto border whitespace-pre-wrap", children: llmInstructions })
        ] })
      ] }) : null,
      error && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-destructive", children: [
        /* @__PURE__ */ jsx(AlertTriangle, { className: "h-4 w-4" }),
        error
      ] })
    ] }),
    /* @__PURE__ */ jsxs(DialogFooter, { children: [
      sessionToken && /* @__PURE__ */ jsxs(
        Button,
        {
          variant: "outline",
          onClick: generateSessionKey,
          disabled: isGenerating,
          className: "gap-1.5",
          children: [
            /* @__PURE__ */ jsx(RefreshCw, { className: `h-4 w-4 ${isGenerating ? "animate-spin" : ""}` }),
            t("ai_assistant.session.generateNew")
          ]
        }
      ),
      /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: handleClose, children: t("ai_assistant.session.close") })
    ] })
  ] }) });
}
export {
  SessionKeyDialog as default
};
//# sourceMappingURL=SessionKeyDialog.js.map
