"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { Button } from "../../ui/button";
import { Input } from "../../ui/input";
import { Label } from "../../ui/label";
import { Checkbox } from "../../ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "../../ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../ui/select";
import { Alert, AlertDescription } from "../../ui/alert";
import { Badge } from "../../ui/badge";
import { Separator } from "../../ui/separator";
import { AlertTriangle, Info } from "lucide-react";
import { toast } from "sonner";
import { API_SCOPES, SCOPE_CATEGORIES } from "../../../lib/api/keys";
import { createCyId } from "../../../lib/test";
function CreateApiKeyDialog({ open, onClose, onSuccess }) {
  const [name, setName] = useState("");
  const [selectedScopes, setSelectedScopes] = useState([]);
  const [expiresAt, setExpiresAt] = useState("");
  const [expiryOption, setExpiryOption] = useState("never");
  const createApiKey = useMutation({
    mutationFn: async (data) => {
      const response = await fetch("/api/v1/api-keys", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to create API key");
      }
      return response.json();
    },
    onSuccess: (data) => {
      toast.success("API key created successfully");
      onSuccess(data.data);
      handleClose();
    },
    onError: (error) => {
      toast.error(`Failed to create API key: ${error.message}`);
    }
  });
  const handleClose = () => {
    setName("");
    setSelectedScopes([]);
    setExpiresAt("");
    setExpiryOption("never");
    onClose();
  };
  const handleScopeToggle = (scope, checked) => {
    if (checked) {
      setSelectedScopes((prev) => [...prev, scope]);
    } else {
      setSelectedScopes((prev) => prev.filter((s) => s !== scope));
    }
  };
  const handleCategoryToggle = (categoryScopes, checked) => {
    if (checked) {
      setSelectedScopes((prev) => [.../* @__PURE__ */ new Set([...prev, ...categoryScopes])]);
    } else {
      setSelectedScopes((prev) => prev.filter((s) => !categoryScopes.includes(s)));
    }
  };
  const calculateExpiryDate = (option) => {
    if (option === "never") return void 0;
    if (option === "custom") return expiresAt || void 0;
    const now = /* @__PURE__ */ new Date();
    switch (option) {
      case "30d":
        now.setDate(now.getDate() + 30);
        break;
      case "90d":
        now.setDate(now.getDate() + 90);
        break;
      case "1y":
        now.setFullYear(now.getFullYear() + 1);
        break;
    }
    return now.toISOString();
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    if (!name.trim()) {
      toast.error("Please enter a name for the API key");
      return;
    }
    if (selectedScopes.length === 0) {
      toast.error("Please select at least one scope");
      return;
    }
    const expiryDate = calculateExpiryDate(expiryOption);
    createApiKey.mutate({
      name: name.trim(),
      scopes: selectedScopes,
      expiresAt: expiryDate
    });
  };
  const isCategoryFullySelected = (categoryScopes) => {
    return categoryScopes.every((scope) => selectedScopes.includes(scope));
  };
  const isCategoryPartiallySelected = (categoryScopes) => {
    return categoryScopes.some((scope) => selectedScopes.includes(scope)) && !isCategoryFullySelected(categoryScopes);
  };
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: handleClose, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-2xl max-h-[90vh] overflow-y-auto", "data-cy": createCyId("api-keys", "dialog"), children: [
    /* @__PURE__ */ jsxs(DialogHeader, { children: [
      /* @__PURE__ */ jsx(DialogTitle, { "data-cy": createCyId("api-keys", "dialog-title"), children: "Crear nueva API Key" }),
      /* @__PURE__ */ jsx(DialogDescription, { children: "Crea una API key para acceder a los endpoints externos de forma segura." })
    ] }),
    /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "space-y-6", "data-cy": createCyId("api-keys", "dialog-form"), children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "name", children: "Nombre de la API Key" }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "name",
            value: name,
            onChange: (e) => setName(e.target.value),
            placeholder: "ej. Mi aplicaci\xF3n m\xF3vil",
            maxLength: 100,
            "data-cy": createCyId("api-keys", "dialog-name")
          }
        ),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Un nombre descriptivo para identificar esta API key" })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { children: "Expiraci\xF3n" }),
        /* @__PURE__ */ jsxs(Select, { value: expiryOption, onValueChange: (value) => setExpiryOption(value), children: [
          /* @__PURE__ */ jsx(SelectTrigger, { "data-cy": createCyId("api-keys", "dialog-expiration"), children: /* @__PURE__ */ jsx(SelectValue, {}) }),
          /* @__PURE__ */ jsxs(SelectContent, { "data-cy": createCyId("api-keys", "dialog-expiration-options"), children: [
            /* @__PURE__ */ jsx(SelectItem, { value: "never", "data-cy": createCyId("api-keys", "dialog-expiration-never"), children: "Nunca expira" }),
            /* @__PURE__ */ jsx(SelectItem, { value: "30d", "data-cy": createCyId("api-keys", "dialog-expiration-30d"), children: "30 d\xEDas" }),
            /* @__PURE__ */ jsx(SelectItem, { value: "90d", "data-cy": createCyId("api-keys", "dialog-expiration-90d"), children: "90 d\xEDas" }),
            /* @__PURE__ */ jsx(SelectItem, { value: "1y", "data-cy": createCyId("api-keys", "dialog-expiration-1y"), children: "1 a\xF1o" }),
            /* @__PURE__ */ jsx(SelectItem, { value: "custom", "data-cy": createCyId("api-keys", "dialog-expiration-custom"), children: "Fecha personalizada" })
          ] })
        ] }),
        expiryOption === "custom" && /* @__PURE__ */ jsx(
          Input,
          {
            type: "datetime-local",
            value: expiresAt,
            onChange: (e) => setExpiresAt(e.target.value),
            min: (/* @__PURE__ */ new Date()).toISOString().slice(0, 16),
            "data-cy": createCyId("api-keys", "dialog-expiration-date")
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-4", "data-cy": createCyId("api-keys", "dialog-scopes"), children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Permisos (Scopes)" }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Selecciona los permisos que tendr\xE1 esta API key" })
        ] }),
        /* @__PURE__ */ jsxs(Alert, { children: [
          /* @__PURE__ */ jsx(Info, { className: "h-4 w-4" }),
          /* @__PURE__ */ jsx(AlertDescription, { children: "Solo puedes asignar permisos que tu rol actual permite. Los permisos no se pueden cambiar despu\xE9s de crear la API key." })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "space-y-4", children: Object.entries(SCOPE_CATEGORIES).map(([categoryKey, category]) => {
          const isFullySelected = isCategoryFullySelected(category.scopes);
          const isPartiallySelected = isCategoryPartiallySelected(category.scopes);
          return /* @__PURE__ */ jsxs("div", { className: "space-y-3", "data-cy": createCyId("api-keys", `dialog-category-${categoryKey}`), children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
              /* @__PURE__ */ jsx(
                Checkbox,
                {
                  id: `category-${categoryKey}`,
                  checked: isFullySelected,
                  ref: (el) => {
                    if (el && "indeterminate" in el) el.indeterminate = isPartiallySelected;
                  },
                  onCheckedChange: (checked) => handleCategoryToggle(category.scopes, checked),
                  "data-cy": createCyId("api-keys", `dialog-category-checkbox-${categoryKey}`)
                }
              ),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(
                  Label,
                  {
                    htmlFor: `category-${categoryKey}`,
                    className: "font-medium",
                    children: category.name
                  }
                ),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: category.description })
              ] })
            ] }),
            /* @__PURE__ */ jsx("div", { className: "ml-6 space-y-2", children: category.scopes.map((scope) => /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
              /* @__PURE__ */ jsx(
                Checkbox,
                {
                  id: scope,
                  checked: selectedScopes.includes(scope),
                  onCheckedChange: (checked) => handleScopeToggle(scope, checked),
                  "data-cy": createCyId("api-keys", `dialog-permission-${scope}`)
                }
              ),
              /* @__PURE__ */ jsxs(Label, { htmlFor: scope, className: "text-sm", children: [
                /* @__PURE__ */ jsx("code", { className: "text-xs bg-muted px-1 py-0.5 rounded mr-2", children: scope }),
                API_SCOPES[scope]
              ] })
            ] }, scope)) }),
            categoryKey !== "system" && /* @__PURE__ */ jsx(Separator, {})
          ] }, categoryKey);
        }) }),
        selectedScopes.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", "data-cy": createCyId("api-keys", "dialog-selected-scopes"), children: [
          /* @__PURE__ */ jsxs(Label, { children: [
            "Permisos seleccionados (",
            selectedScopes.length,
            ")"
          ] }),
          /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1", children: selectedScopes.map((scope) => /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", "data-cy": createCyId("api-keys", `dialog-selected-${scope}`), children: scope }, scope)) })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-cy": createCyId("api-keys", "dialog-warning"), children: [
        /* @__PURE__ */ jsx(AlertTriangle, { className: "h-4 w-4" }),
        /* @__PURE__ */ jsxs(AlertDescription, { children: [
          /* @__PURE__ */ jsx("strong", { children: "Importante:" }),
          " La API key se mostrar\xE1 solo una vez despu\xE9s de crearla. Gu\xE1rdala en un lugar seguro ya que no podr\xE1s verla nuevamente."
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs(DialogFooter, { "data-cy": createCyId("api-keys", "dialog-footer"), children: [
      /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: handleClose, disabled: createApiKey.isPending, "data-cy": createCyId("api-keys", "dialog-cancel"), children: "Cancelar" }),
      /* @__PURE__ */ jsx(
        Button,
        {
          onClick: handleSubmit,
          disabled: createApiKey.isPending || selectedScopes.length === 0 || !name.trim(),
          "data-cy": createCyId("api-keys", "dialog-submit"),
          children: createApiKey.isPending ? "Creando..." : "Crear API Key"
        }
      )
    ] })
  ] }) });
}
export {
  CreateApiKeyDialog
};
