"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useTranslations } from "next-intl";
import { Fragment, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Badge } from "../../ui/badge.js";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "../../ui/table.js";
import { Button } from "../../ui/button.js";
import { ChevronDownIcon, ChevronRightIcon, RotateCcwIcon, PlayIcon } from "lucide-react";
import { sel } from "../../../lib/test/index.js";
import { toast } from "sonner";
async function retryAction(actionId) {
  const response = await fetch("/api/v1/devtools/scheduled-actions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ actionId })
  });
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || "Failed to retry action");
  }
  const data = await response.json();
  return data.data;
}
async function runAction(actionId) {
  const response = await fetch("/api/v1/devtools/scheduled-actions/run", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ actionId })
  });
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || "Failed to run action");
  }
  const data = await response.json();
  return data.data;
}
function ActionsTable({ actions }) {
  const t = useTranslations("devtools.scheduledActions");
  const [expandedRows, setExpandedRows] = useState(/* @__PURE__ */ new Set());
  const queryClient = useQueryClient();
  const retryMutation = useMutation({
    mutationFn: retryAction,
    onSuccess: () => {
      toast.success(t("retry.success"));
      queryClient.invalidateQueries({ queryKey: ["scheduled-actions"] });
    },
    onError: (error) => {
      toast.error(t("retry.error", { message: error.message }));
    }
  });
  const runMutation = useMutation({
    mutationFn: runAction,
    onSuccess: () => {
      toast.success(t("run.success"));
      queryClient.invalidateQueries({ queryKey: ["scheduled-actions"] });
    },
    onError: (error) => {
      toast.error(t("run.error", { message: error.message }));
    }
  });
  const toggleRow = (id) => {
    setExpandedRows((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };
  const getStatusBadge = (status) => {
    const variants = {
      pending: { variant: "secondary", cy: sel("devtools.scheduledActions.statusPending") },
      running: { variant: "default", cy: sel("devtools.scheduledActions.statusRunning") },
      completed: { variant: "outline", cy: sel("devtools.scheduledActions.statusCompleted") },
      failed: { variant: "destructive", cy: sel("devtools.scheduledActions.statusFailed") }
    };
    const config = variants[status];
    return /* @__PURE__ */ jsx(Badge, { variant: config.variant, "data-cy": config.cy, className: "font-medium", children: t(`status.${status}`) });
  };
  const formatDate = (date) => {
    return new Date(date).toLocaleString("es-ES", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit"
    });
  };
  const calculateDuration = (startedAt, completedAt) => {
    if (!startedAt || !completedAt) return null;
    const diff = new Date(completedAt).getTime() - new Date(startedAt).getTime();
    const seconds = Math.floor(diff / 1e3);
    if (seconds < 60) return `${seconds}s`;
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}m ${remainingSeconds}s`;
  };
  if (actions.length === 0) {
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: "text-center py-16 text-muted-foreground",
        "data-cy": sel("devtools.scheduledActions.emptyState"),
        children: [
          /* @__PURE__ */ jsx("p", { className: "text-lg font-medium", children: t("empty") }),
          /* @__PURE__ */ jsx("p", { className: "text-sm mt-2", children: t("emptyDescription") })
        ]
      }
    );
  }
  return /* @__PURE__ */ jsx("div", { className: "border rounded-lg overflow-hidden", "data-cy": sel("devtools.scheduledActions.table"), children: /* @__PURE__ */ jsxs(Table, { children: [
    /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { className: "bg-muted/50", children: [
      /* @__PURE__ */ jsx(TableHead, { className: "w-[50px]" }),
      /* @__PURE__ */ jsx(TableHead, { className: "font-semibold", "data-cy": sel("devtools.scheduledActions.cellType"), children: t("table.type") }),
      /* @__PURE__ */ jsx(TableHead, { className: "font-semibold", "data-cy": sel("devtools.scheduledActions.cellStatus"), children: t("table.status") }),
      /* @__PURE__ */ jsx(TableHead, { className: "font-semibold", "data-cy": sel("devtools.scheduledActions.cellAttempts"), children: t("table.attempts") }),
      /* @__PURE__ */ jsx(TableHead, { className: "font-semibold", "data-cy": sel("devtools.scheduledActions.cellScheduledAt"), children: t("table.scheduledAt") }),
      /* @__PURE__ */ jsx(TableHead, { className: "font-semibold", "data-cy": sel("devtools.scheduledActions.cellStartedAt"), children: t("table.startedAt") }),
      /* @__PURE__ */ jsx(TableHead, { className: "font-semibold", "data-cy": sel("devtools.scheduledActions.cellCompletedAt"), children: t("table.completedAt") }),
      /* @__PURE__ */ jsx(TableHead, { className: "font-semibold", "data-cy": sel("devtools.scheduledActions.cellTeam"), children: t("table.team") }),
      /* @__PURE__ */ jsx(TableHead, { className: "font-semibold text-right", "data-cy": sel("devtools.scheduledActions.cellActions"), children: t("table.actions") })
    ] }) }),
    /* @__PURE__ */ jsx(TableBody, { children: actions.map((action) => {
      const isExpanded = expandedRows.has(action.id);
      const duration = calculateDuration(action.startedAt, action.completedAt);
      return /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs(
          TableRow,
          {
            className: "hover:bg-muted/50 transition-colors",
            "data-cy": sel("devtools.scheduledActions.row", { id: action.id }),
            children: [
              /* @__PURE__ */ jsx(TableCell, { className: "py-4", children: /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  className: "h-8 w-8 p-0",
                  onClick: () => toggleRow(action.id),
                  children: isExpanded ? /* @__PURE__ */ jsx(ChevronDownIcon, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronRightIcon, { className: "h-4 w-4" })
                }
              ) }),
              /* @__PURE__ */ jsx(TableCell, { className: "font-mono text-sm py-4", children: action.actionType }),
              /* @__PURE__ */ jsx(TableCell, { className: "py-4", children: getStatusBadge(action.status) }),
              /* @__PURE__ */ jsx(TableCell, { className: "text-sm font-medium py-4", children: action.status === "failed" ? /* @__PURE__ */ jsxs("span", { className: "text-destructive", children: [
                action.attempts,
                "/",
                action.maxRetries
              ] }) : action.status === "completed" && action.attempts > 1 ? /* @__PURE__ */ jsxs("span", { className: "text-green-600 dark:text-green-500", children: [
                action.attempts,
                "/",
                action.maxRetries
              ] }) : action.status === "running" ? /* @__PURE__ */ jsxs("span", { className: "text-blue-600 dark:text-blue-500", children: [
                action.attempts,
                "/",
                action.maxRetries
              ] }) : action.status === "pending" && action.attempts > 0 ? /* @__PURE__ */ jsxs("span", { className: "text-amber-600 dark:text-amber-500", children: [
                action.attempts,
                "/",
                action.maxRetries
              ] }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "-" }) }),
              /* @__PURE__ */ jsx(TableCell, { className: "text-sm py-4 whitespace-nowrap", children: formatDate(action.scheduledAt) }),
              /* @__PURE__ */ jsx(TableCell, { className: "text-sm py-4 whitespace-nowrap", children: action.startedAt ? formatDate(action.startedAt) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "-" }) }),
              /* @__PURE__ */ jsx(TableCell, { className: "text-sm py-4 whitespace-nowrap", children: action.completedAt ? /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
                /* @__PURE__ */ jsx("div", { children: formatDate(action.completedAt) }),
                duration && /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
                  "(",
                  duration,
                  ")"
                ] })
              ] }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "-" }) }),
              /* @__PURE__ */ jsx(TableCell, { className: "text-sm py-4", children: action.teamId ? /* @__PURE__ */ jsx("code", { className: "text-xs bg-muted px-2 py-1 rounded", children: action.teamId.slice(0, 8) }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("table.noTeam") }) }),
              /* @__PURE__ */ jsx(TableCell, { className: "text-right py-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2", children: [
                action.status === "failed" && /* @__PURE__ */ jsxs(
                  Button,
                  {
                    variant: "outline",
                    size: "sm",
                    onClick: () => retryMutation.mutate(action.id),
                    disabled: retryMutation.isPending,
                    "data-cy": sel("devtools.scheduledActions.retryBtn", { id: action.id }),
                    children: [
                      /* @__PURE__ */ jsx(RotateCcwIcon, { className: "h-3.5 w-3.5 mr-1.5" }),
                      t("retry.button")
                    ]
                  }
                ),
                action.status === "pending" && /* @__PURE__ */ jsxs(
                  Button,
                  {
                    variant: "default",
                    size: "sm",
                    onClick: () => runMutation.mutate(action.id),
                    disabled: runMutation.isPending,
                    "data-cy": sel("devtools.scheduledActions.runBtn", { id: action.id }),
                    children: [
                      /* @__PURE__ */ jsx(PlayIcon, { className: "h-3.5 w-3.5 mr-1.5" }),
                      t("run.button")
                    ]
                  }
                )
              ] }) })
            ]
          }
        ),
        isExpanded && /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 9, className: "bg-muted/30 py-6", children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 max-w-5xl", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold text-muted-foreground mb-1", children: "ID" }),
            /* @__PURE__ */ jsx("code", { className: "text-xs font-mono bg-background px-2 py-1 rounded border", children: action.id })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold text-muted-foreground mb-2", children: t("table.payload") }),
            /* @__PURE__ */ jsx("pre", { className: "text-xs bg-background p-4 rounded border overflow-auto max-h-64 font-mono", children: JSON.stringify(action.payload, null, 2) })
          ] }),
          action.errorMessage && /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold text-destructive mb-2", children: t("table.error") }),
            /* @__PURE__ */ jsx("div", { className: "bg-destructive/10 border border-destructive/20 rounded p-4", children: /* @__PURE__ */ jsx("code", { className: "text-sm text-destructive font-mono break-all", children: action.errorMessage }) })
          ] })
        ] }) }) })
      ] }, action.id);
    }) })
  ] }) });
}
export {
  ActionsTable
};
