"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useMemo } from "react";
import { Send, X } from "lucide-react";
import { Button } from "../../ui/button.js";
import { Badge } from "../../ui/badge.js";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../ui/tabs.js";
import { ScrollArea } from "../../ui/scroll-area.js";
import { useTranslations } from "next-intl";
import { cn } from "../../../lib/utils/index.js";
import { sel } from "../../../lib/test/index.js";
import { MethodSelector } from "../api-tester/MethodSelector.js";
import { PathParamsEditor } from "../api-tester/PathParamsEditor.js";
import { KeyValueEditor } from "../api-tester/KeyValueEditor.js";
import { AuthSelector } from "../api-tester/AuthSelector.js";
import { PayloadEditor } from "../api-tester/PayloadEditor.js";
import { buildUrl, validatePathParams, validateJsonBody } from "../api-tester/utils/url-builder.js";
import { PresetsTab } from "./PresetsTab.js";
import { ApiDocsModal } from "./ApiDocsModal.js";
const methodColors = {
  GET: "bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 border-emerald-500/30",
  POST: "bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/30",
  PATCH: "bg-amber-500/20 text-amber-600 dark:text-amber-400 border-amber-500/30",
  PUT: "bg-orange-500/20 text-orange-600 dark:text-orange-400 border-orange-500/30",
  DELETE: "bg-red-500/20 text-red-600 dark:text-red-400 border-red-500/30",
  OPTIONS: "bg-gray-500/20 text-gray-600 dark:text-gray-400 border-gray-500/30"
};
function ApiRequestPanel({
  route,
  basePath,
  method,
  pathParams,
  queryParams,
  headers,
  authType,
  apiKey,
  bypassMode,
  selectedTeamId,
  body,
  status,
  onMethodChange,
  onPathParamsChange,
  onQueryParamsChange,
  onHeadersChange,
  onAuthTypeChange,
  onApiKeyChange,
  onBypassModeChange,
  onTeamChange,
  onBodyChange,
  onSend,
  onCancel,
  endpointPresets,
  endpointDoc,
  onApplyPreset,
  tabsModifiedByPreset,
  onClearPresetIndicator
}) {
  const t = useTranslations("devtools.apiTester");
  const previewUrl = useMemo(() => {
    const origin = typeof window !== "undefined" ? window.location.origin : "";
    return origin + buildUrl(basePath, pathParams, queryParams);
  }, [basePath, pathParams, queryParams]);
  const canSend = useMemo(() => {
    const pathErrors = validatePathParams(pathParams);
    const bodyError = ["POST", "PATCH", "PUT"].includes(method) ? validateJsonBody(body) : null;
    return pathErrors.length === 0 && !bodyError;
  }, [pathParams, method, body]);
  const showPayloadEditor = ["POST", "PATCH", "PUT"].includes(method);
  const handlePathParamsChange = (params) => {
    onPathParamsChange(params);
    onClearPresetIndicator == null ? void 0 : onClearPresetIndicator("params");
  };
  const handleQueryParamsChange = (params) => {
    onQueryParamsChange(params);
    onClearPresetIndicator == null ? void 0 : onClearPresetIndicator("params");
  };
  const handleHeadersChange = (newHeaders) => {
    onHeadersChange(newHeaders);
    onClearPresetIndicator == null ? void 0 : onClearPresetIndicator("headers");
  };
  const handleBodyChange = (newBody) => {
    onBodyChange(newBody);
    onClearPresetIndicator == null ? void 0 : onClearPresetIndicator("body");
  };
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full", "data-cy": sel("devtools.apiExplorer.request.panel"), children: [
    /* @__PURE__ */ jsxs("div", { className: "p-4 border-b space-y-3 bg-muted/30", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsx(
          Badge,
          {
            variant: "outline",
            className: cn("font-mono text-sm px-2 py-1 border", methodColors[method]),
            children: method
          }
        ),
        /* @__PURE__ */ jsx("code", { className: "font-mono text-sm font-medium flex-1 truncate", children: basePath }),
        route.source && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs shrink-0", children: route.source }),
        endpointDoc && /* @__PURE__ */ jsx(ApiDocsModal, { docPath: endpointDoc.path, title: endpointDoc.title }),
        /* @__PURE__ */ jsxs("div", { className: "flex gap-2 shrink-0", children: [
          /* @__PURE__ */ jsxs(
            Button,
            {
              onClick: onSend,
              disabled: !canSend || status === "loading",
              size: "sm",
              "data-cy": sel("devtools.apiExplorer.request.sendBtn"),
              children: [
                /* @__PURE__ */ jsx(Send, { className: "h-4 w-4 mr-2" }),
                status === "loading" ? t("sending") : t("sendRequest")
              ]
            }
          ),
          status === "loading" && /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: onCancel, "data-cy": sel("devtools.apiExplorer.request.cancelBtn"), children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }) })
        ] })
      ] }),
      /* @__PURE__ */ jsx(
        MethodSelector,
        {
          methods: route.methods,
          selected: method,
          onSelect: onMethodChange
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "bg-background rounded-md border p-2", children: [
        /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground uppercase tracking-wide mb-1", children: t("urlPreview") }),
        /* @__PURE__ */ jsx("code", { className: "font-mono text-xs break-all text-foreground", children: previewUrl })
      ] }),
      /* @__PURE__ */ jsx(
        AuthSelector,
        {
          authType,
          apiKey,
          bypassMode,
          selectedTeamId,
          onAuthTypeChange,
          onApiKeyChange,
          onBypassModeChange,
          onTeamChange
        }
      )
    ] }),
    /* @__PURE__ */ jsx("div", { className: "flex-1 min-h-0 flex flex-col", children: /* @__PURE__ */ jsxs(Tabs, { defaultValue: "params", className: "flex-1 flex flex-col", children: [
      /* @__PURE__ */ jsx("div", { className: "border-b px-4", children: /* @__PURE__ */ jsxs(TabsList, { className: "h-9 bg-transparent p-0 border-0", children: [
        /* @__PURE__ */ jsxs(
          TabsTrigger,
          {
            value: "params",
            className: "data-[state=active]:bg-transparent data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-3 pb-2",
            "data-cy": sel("devtools.apiExplorer.request.tabParams"),
            children: [
              (tabsModifiedByPreset == null ? void 0 : tabsModifiedByPreset.has("params")) && /* @__PURE__ */ jsx("span", { className: "w-2 h-2 rounded-full bg-primary mr-1.5", title: "Modified by preset" }),
              "Params",
              (pathParams.length > 0 || queryParams.length > 0) && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "ml-1.5 text-[10px] px-1.5", children: pathParams.length + queryParams.length })
            ]
          }
        ),
        /* @__PURE__ */ jsxs(
          TabsTrigger,
          {
            value: "headers",
            className: "data-[state=active]:bg-transparent data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-3 pb-2",
            "data-cy": sel("devtools.apiExplorer.request.tabHeaders"),
            children: [
              (tabsModifiedByPreset == null ? void 0 : tabsModifiedByPreset.has("headers")) && /* @__PURE__ */ jsx("span", { className: "w-2 h-2 rounded-full bg-primary mr-1.5", title: "Modified by preset" }),
              "Headers",
              headers.length > 0 && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "ml-1.5 text-[10px] px-1.5", children: headers.length })
            ]
          }
        ),
        showPayloadEditor && /* @__PURE__ */ jsxs(
          TabsTrigger,
          {
            value: "body",
            className: "data-[state=active]:bg-transparent data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-3 pb-2",
            "data-cy": sel("devtools.apiExplorer.request.tabBody"),
            children: [
              (tabsModifiedByPreset == null ? void 0 : tabsModifiedByPreset.has("body")) && /* @__PURE__ */ jsx("span", { className: "w-2 h-2 rounded-full bg-primary mr-1.5", title: "Modified by preset" }),
              "Body"
            ]
          }
        ),
        endpointPresets && endpointPresets.presets.length > 0 && /* @__PURE__ */ jsxs(
          TabsTrigger,
          {
            value: "presets",
            className: "data-[state=active]:bg-transparent data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none px-3 pb-2",
            "data-cy": sel("devtools.apiExplorer.request.tabPresets"),
            children: [
              "Presets",
              /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "ml-1.5 text-[10px] px-1.5", children: endpointPresets.presets.length })
            ]
          }
        )
      ] }) }),
      /* @__PURE__ */ jsxs(ScrollArea, { className: "flex-1", children: [
        /* @__PURE__ */ jsxs(TabsContent, { value: "params", className: "m-0 p-4 space-y-4", children: [
          pathParams.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("h4", { className: "text-sm font-medium mb-2", children: "Path Parameters" }),
            /* @__PURE__ */ jsx(PathParamsEditor, { params: pathParams, onChange: handlePathParamsChange })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("h4", { className: "text-sm font-medium mb-2", children: "Query Parameters" }),
            /* @__PURE__ */ jsx(
              KeyValueEditor,
              {
                items: queryParams,
                onChange: handleQueryParamsChange,
                dataCyPrefix: "api-request-query"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxs(TabsContent, { value: "headers", className: "m-0 p-4", children: [
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mb-3", children: t("headersInfo") }),
          /* @__PURE__ */ jsx(
            KeyValueEditor,
            {
              items: headers,
              onChange: handleHeadersChange,
              dataCyPrefix: "api-request-headers"
            }
          )
        ] }),
        showPayloadEditor && /* @__PURE__ */ jsx(TabsContent, { value: "body", className: "m-0 p-4", children: /* @__PURE__ */ jsx(PayloadEditor, { value: body, onChange: handleBodyChange }) }),
        endpointPresets && endpointPresets.presets.length > 0 && onApplyPreset && /* @__PURE__ */ jsx(TabsContent, { value: "presets", className: "m-0", children: /* @__PURE__ */ jsx(
          PresetsTab,
          {
            endpointPresets,
            currentMethod: method,
            onApplyPreset
          }
        ) })
      ] })
    ] }) })
  ] });
}
export {
  ApiRequestPanel
};
