"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useMemo, useCallback } from "react";
import { ArrowLeft, Send, X, ChevronDown } from "lucide-react";
import Link from "next/link";
import { Button } from "../../ui/button.js";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "../../ui/card.js";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "../../ui/collapsible.js";
import { Badge } from "../../ui/badge.js";
import { useTranslations } from "next-intl";
import { MethodSelector } from "./MethodSelector.js";
import { PathParamsEditor } from "./PathParamsEditor.js";
import { KeyValueEditor } from "./KeyValueEditor.js";
import { AuthSelector } from "./AuthSelector.js";
import { PayloadEditor } from "./PayloadEditor.js";
import { ResponseViewer } from "./ResponseViewer.js";
import { useApiRequest } from "./hooks/useApiRequest.js";
import { extractPathParams, buildUrl, validatePathParams, validateJsonBody } from "./utils/url-builder.js";
function ApiTester({ route, basePath }) {
  const t = useTranslations("devtools.apiTester");
  const [method, setMethod] = useState(
    route.methods.includes("GET") ? "GET" : route.methods[0]
  );
  const [pathParams, setPathParams] = useState(() => extractPathParams(basePath));
  const [queryParams, setQueryParams] = useState([]);
  const [headers, setHeaders] = useState([]);
  const [authType, setAuthType] = useState("session");
  const [apiKey, setApiKey] = useState("");
  const [body, setBody] = useState("");
  const [bypassMode, setBypassMode] = useState(false);
  const [selectedTeamId, setSelectedTeamId] = useState(() => {
    if (typeof window !== "undefined") {
      return localStorage.getItem("activeTeamId");
    }
    return null;
  });
  const { status, response, error, execute, cancel } = useApiRequest();
  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 handleSend = useCallback(async () => {
    const url = buildUrl(basePath, pathParams, queryParams);
    const fullUrl = (typeof window !== "undefined" ? window.location.origin : "") + url;
    const customHeaders = {};
    if (bypassMode) {
      customHeaders["x-admin-bypass"] = "confirm-cross-team-access";
    }
    if (selectedTeamId) {
      customHeaders["x-team-id"] = selectedTeamId;
    }
    for (const h of headers) {
      if (h.enabled && h.key) {
        customHeaders[h.key] = h.value;
      }
    }
    await execute({
      url: fullUrl,
      method,
      headers: customHeaders,
      body: showPayloadEditor ? body : void 0,
      authType,
      apiKey: authType === "apiKey" ? apiKey : void 0
    });
  }, [basePath, pathParams, queryParams, headers, method, body, authType, apiKey, bypassMode, selectedTeamId, showPayloadEditor, execute]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", "data-cy": "api-tester", children: [
    /* @__PURE__ */ jsx("div", { className: "flex items-center gap-4", children: /* @__PURE__ */ jsx(Link, { href: "/devtools/api", children: /* @__PURE__ */ jsxs(Button, { variant: "ghost", size: "sm", "data-cy": "api-tester-back-btn", children: [
      /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4 mr-2" }),
      t("backToList")
    ] }) }) }),
    /* @__PURE__ */ jsx(Card, { "data-cy": "api-tester-endpoint-info", children: /* @__PURE__ */ jsxs(CardHeader, { children: [
      /* @__PURE__ */ jsx(CardTitle, { className: "font-mono text-lg", children: basePath }),
      route.source && /* @__PURE__ */ jsxs(CardDescription, { children: [
        "Source: ",
        route.source,
        route.subcategory && ` | Category: ${route.subcategory}`
      ] })
    ] }) }),
    /* @__PURE__ */ jsxs(Card, { "data-cy": "api-tester-method-card", children: [
      /* @__PURE__ */ jsx(CardHeader, { className: "pb-3", children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: t("method") }) }),
      /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(
        MethodSelector,
        {
          methods: route.methods,
          selected: method,
          onSelect: setMethod
        }
      ) })
    ] }),
    /* @__PURE__ */ jsx(Card, { "data-cy": "api-tester-url-preview", children: /* @__PURE__ */ jsxs(CardContent, { className: "pt-6", children: [
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mb-1", children: t("urlPreview") }),
      /* @__PURE__ */ jsx("code", { className: "block font-mono text-sm break-all bg-muted p-2 rounded", children: previewUrl })
    ] }) }),
    pathParams.length > 0 && /* @__PURE__ */ jsx(Collapsible, { defaultOpen: true, children: /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CollapsibleTrigger, { asChild: true, children: /* @__PURE__ */ jsx(CardHeader, { className: "cursor-pointer hover:bg-muted/50 transition-colors", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: t("pathParams") }),
        /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
      ] }) }) }),
      /* @__PURE__ */ jsx(CollapsibleContent, { children: /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(PathParamsEditor, { params: pathParams, onChange: setPathParams }) }) })
    ] }) }),
    /* @__PURE__ */ jsx(Collapsible, { children: /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CollapsibleTrigger, { asChild: true, children: /* @__PURE__ */ jsx(CardHeader, { className: "cursor-pointer hover:bg-muted/50 transition-colors", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxs(CardTitle, { className: "text-sm", children: [
          t("queryParams"),
          queryParams.length > 0 && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "ml-2", children: queryParams.length })
        ] }),
        /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
      ] }) }) }),
      /* @__PURE__ */ jsx(CollapsibleContent, { children: /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(
        KeyValueEditor,
        {
          items: queryParams,
          onChange: setQueryParams,
          dataCyPrefix: "api-tester-query"
        }
      ) }) })
    ] }) }),
    /* @__PURE__ */ jsx(Collapsible, { children: /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CollapsibleTrigger, { asChild: true, children: /* @__PURE__ */ jsx(CardHeader, { className: "cursor-pointer hover:bg-muted/50 transition-colors", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxs(CardTitle, { className: "text-sm", children: [
          t("headers"),
          headers.length > 0 && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "ml-2", children: headers.length })
        ] }),
        /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
      ] }) }) }),
      /* @__PURE__ */ jsx(CollapsibleContent, { children: /* @__PURE__ */ jsxs(CardContent, { children: [
        /* @__PURE__ */ jsx("div", { className: "mb-3 text-xs text-muted-foreground", children: t("headersInfo") }),
        /* @__PURE__ */ jsx(
          KeyValueEditor,
          {
            items: headers,
            onChange: setHeaders,
            dataCyPrefix: "api-tester-headers"
          }
        )
      ] }) })
    ] }) }),
    /* @__PURE__ */ jsx(Collapsible, { defaultOpen: true, children: /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CollapsibleTrigger, { asChild: true, children: /* @__PURE__ */ jsx(CardHeader, { className: "cursor-pointer hover:bg-muted/50 transition-colors", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: t("authentication") }),
        /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
      ] }) }) }),
      /* @__PURE__ */ jsx(CollapsibleContent, { children: /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(
        AuthSelector,
        {
          authType,
          apiKey,
          bypassMode,
          selectedTeamId,
          onAuthTypeChange: setAuthType,
          onApiKeyChange: setApiKey,
          onBypassModeChange: setBypassMode,
          onTeamChange: setSelectedTeamId
        }
      ) }) })
    ] }) }),
    showPayloadEditor && /* @__PURE__ */ jsx(Collapsible, { defaultOpen: true, children: /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CollapsibleTrigger, { asChild: true, children: /* @__PURE__ */ jsx(CardHeader, { className: "cursor-pointer hover:bg-muted/50 transition-colors", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: t("requestBody") }),
        /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
      ] }) }) }),
      /* @__PURE__ */ jsx(CollapsibleContent, { children: /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(PayloadEditor, { value: body, onChange: setBody }) }) })
    ] }) }),
    /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          onClick: handleSend,
          disabled: !canSend || status === "loading",
          className: "flex-1",
          "data-cy": "api-tester-send-btn",
          children: [
            /* @__PURE__ */ jsx(Send, { className: "h-4 w-4 mr-2" }),
            status === "loading" ? t("sending") : t("sendRequest")
          ]
        }
      ),
      status === "loading" && /* @__PURE__ */ jsxs(
        Button,
        {
          variant: "outline",
          onClick: cancel,
          "data-cy": "api-tester-cancel-btn",
          children: [
            /* @__PURE__ */ jsx(X, { className: "h-4 w-4 mr-2" }),
            t("cancel")
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsx(ResponseViewer, { status, response, error })
  ] });
}
export {
  ApiTester
};
