"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { StatusBadge } from "@open-mercato/ui/primitives/status-badge";
import { Card, CardContent, CardHeader, CardTitle } from "@open-mercato/ui/primitives/card";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Label } from "@open-mercato/ui/primitives/label";
import { Alert, AlertDescription } from "@open-mercato/ui/primitives/alert";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Separator } from "@open-mercato/ui/primitives/separator";
import { Switch } from "@open-mercato/ui/primitives/switch";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  ArrowRightLeft,
  Boxes,
  CalendarClock,
  Clock3,
  Gauge,
  Play,
  PlugZap,
  Repeat,
  Settings2,
  ShieldCheck
} from "lucide-react";
import { getSyncRunStatusVariant, getSyncSummaryVariant } from "../../lib/syncRunStatus.js";
const DEFAULT_TIMEZONE = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
function formatEntityTypeLabel(entityType) {
  return entityType.replace(/[_-]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
}
function buildDefaultScheduleState(entityType) {
  const normalized = entityType.trim().toLowerCase();
  const longerInterval = normalized === "categories" || normalized === "attributes";
  return {
    scheduleType: "interval",
    scheduleValue: longerInterval ? "6h" : "1h",
    timezone: DEFAULT_TIMEZONE,
    fullSync: normalized !== "products",
    isEnabled: true,
    lastRunAt: null,
    updatedAt: null
  };
}
function SyncRunsDashboardPage() {
  const router = useRouter();
  const [rows, setRows] = React.useState([]);
  const [options, setOptions] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const [search, setSearch] = React.useState("");
  const [filterValues, setFilterValues] = React.useState({});
  const [isLoading, setIsLoading] = React.useState(true);
  const [isLoadingOptions, setIsLoadingOptions] = React.useState(true);
  const [selectedIntegrationId, setSelectedIntegrationId] = React.useState("");
  const [selectedEntityType, setSelectedEntityType] = React.useState("");
  const [selectedDirection, setSelectedDirection] = React.useState("import");
  const [batchSize, setBatchSize] = React.useState("100");
  const [fullSync, setFullSync] = React.useState(false);
  const [scheduleEditor, setScheduleEditor] = React.useState(() => buildDefaultScheduleState(""));
  const [isLoadingSchedule, setIsLoadingSchedule] = React.useState(false);
  const [isSavingSchedule, setIsSavingSchedule] = React.useState(false);
  const [isDeletingSchedule, setIsDeletingSchedule] = React.useState(false);
  const [reloadToken, setReloadToken] = React.useState(0);
  const scopeVersion = useOrganizationScopeVersion();
  const t = useT();
  const { runMutation } = useGuardedMutation({
    contextId: "data_sync.dashboard"
  });
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      setIsLoading(true);
      const params = new URLSearchParams();
      params.set("page", String(page));
      params.set("pageSize", "20");
      if (filterValues.status) params.set("status", filterValues.status);
      if (filterValues.direction) params.set("direction", filterValues.direction);
      if (search.trim()) params.set("search", search.trim());
      const fallback = { items: [], total: 0, page, totalPages: 1 };
      const call = await apiCall(
        `/api/data_sync/runs?${params.toString()}`,
        void 0,
        { fallback }
      );
      if (!call.ok) {
        flash(t("data_sync.dashboard.loadError"), "error");
        if (!cancelled) setIsLoading(false);
        return;
      }
      const payload = call.result ?? fallback;
      if (!cancelled) {
        setRows(Array.isArray(payload.items) ? payload.items : []);
        setTotal(payload.total || 0);
        setTotalPages(payload.totalPages || 1);
        setIsLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [page, filterValues, search, reloadToken, scopeVersion, t]);
  React.useEffect(() => {
    let cancelled = false;
    async function loadOptions() {
      setIsLoadingOptions(true);
      const fallback = { items: [] };
      const call = await apiCall("/api/data_sync/options", void 0, { fallback });
      if (!cancelled) {
        if (!call.ok) {
          flash(t("data_sync.dashboard.loadError"), "error");
          setOptions([]);
          setIsLoadingOptions(false);
          return;
        }
        const nextItems = Array.isArray(call.result?.items) ? call.result.items : [];
        setOptions(nextItems);
        setSelectedIntegrationId((current) => {
          if (current && nextItems.some((item) => item.integrationId === current)) return current;
          return nextItems[0]?.integrationId ?? "";
        });
        setIsLoadingOptions(false);
      }
    }
    void loadOptions();
    return () => {
      cancelled = true;
    };
  }, [scopeVersion, t]);
  const selectedIntegration = React.useMemo(
    () => options.find((item) => item.integrationId === selectedIntegrationId) ?? null,
    [options, selectedIntegrationId]
  );
  const entityOptions = React.useMemo(
    () => selectedIntegration?.supportedEntities ?? [],
    [selectedIntegration]
  );
  React.useEffect(() => {
    if (!selectedIntegration) {
      setSelectedEntityType("");
      return;
    }
    setSelectedEntityType((current) => current && selectedIntegration.supportedEntities.includes(current) ? current : selectedIntegration.supportedEntities[0] ?? "");
    setSelectedDirection(selectedIntegration.direction === "export" ? "export" : "import");
  }, [selectedIntegration]);
  React.useEffect(() => {
    if (!selectedIntegration || !selectedEntityType) {
      setScheduleEditor(buildDefaultScheduleState(selectedEntityType));
      return;
    }
    const currentIntegration = selectedIntegration;
    let cancelled = false;
    async function loadSchedule() {
      setIsLoadingSchedule(true);
      const integrationId = currentIntegration.integrationId;
      const params = new URLSearchParams({
        integrationId,
        entityType: selectedEntityType,
        direction: selectedDirection,
        page: "1",
        pageSize: "1"
      });
      const fallback = { items: [] };
      const call = await apiCall(`/api/data_sync/schedules?${params.toString()}`, void 0, { fallback });
      if (cancelled) return;
      if (!call.ok) {
        setScheduleEditor(buildDefaultScheduleState(selectedEntityType));
        setIsLoadingSchedule(false);
        return;
      }
      const record = Array.isArray(call.result?.items) ? call.result?.items[0] : void 0;
      if (!record) {
        setScheduleEditor(buildDefaultScheduleState(selectedEntityType));
        setIsLoadingSchedule(false);
        return;
      }
      setScheduleEditor({
        id: record.id,
        scheduleType: record.scheduleType,
        scheduleValue: record.scheduleValue,
        timezone: record.timezone,
        fullSync: record.fullSync,
        isEnabled: record.isEnabled,
        lastRunAt: record.lastRunAt,
        updatedAt: record.updatedAt ?? null
      });
      setIsLoadingSchedule(false);
    }
    void loadSchedule();
    return () => {
      cancelled = true;
    };
  }, [selectedDirection, selectedEntityType, selectedIntegration, scopeVersion]);
  const updateScheduleEditor = React.useCallback((changes) => {
    setScheduleEditor((current) => ({ ...current, ...changes }));
  }, []);
  const handleCancel = React.useCallback(async (row) => {
    const call = await apiCall(`/api/data_sync/runs/${encodeURIComponent(row.id)}/cancel`, {
      method: "POST"
    }, { fallback: null });
    if (call.ok) {
      flash(t("data_sync.runs.detail.cancelSuccess"), "success");
      setReloadToken((token) => token + 1);
    } else {
      flash(t("data_sync.runs.detail.cancelError"), "error");
    }
  }, [t]);
  const handleRetry = React.useCallback(async (row) => {
    const call = await apiCall(`/api/data_sync/runs/${encodeURIComponent(row.id)}/retry`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ fromBeginning: false })
    }, { fallback: null });
    if (call.ok) {
      flash(t("data_sync.runs.detail.retrySuccess"), "success");
      setReloadToken((token) => token + 1);
    } else {
      flash(t("data_sync.runs.detail.retryError"), "error");
    }
  }, [t]);
  const handleFiltersApply = React.useCallback((values) => {
    const next = {};
    Object.entries(values).forEach(([key, value]) => {
      if (value !== void 0 && value !== "") next[key] = value;
    });
    setFilterValues(next);
    setPage(1);
  }, []);
  const handleFiltersClear = React.useCallback(() => {
    setFilterValues({});
    setPage(1);
  }, []);
  const handleStartSync = React.useCallback(async () => {
    if (!selectedIntegration || !selectedEntityType) return;
    const parsedBatchSize = Number.parseInt(batchSize, 10);
    if (!Number.isFinite(parsedBatchSize) || parsedBatchSize < 1 || parsedBatchSize > 1e3) {
      flash(t("data_sync.dashboard.start.invalidBatchSize", "Batch size must be between 1 and 1000."), "error");
      return;
    }
    try {
      const call = await runMutation({
        // optimistic-lock-exempt: starts a new sync run (create), not a concurrent record edit
        operation: () => apiCall("/api/data_sync/run", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            integrationId: selectedIntegration.integrationId,
            entityType: selectedEntityType,
            direction: selectedDirection,
            batchSize: parsedBatchSize,
            fullSync
          })
        }, { fallback: null }),
        mutationPayload: {
          integrationId: selectedIntegration.integrationId,
          entityType: selectedEntityType,
          direction: selectedDirection,
          batchSize: parsedBatchSize,
          fullSync
        },
        context: {
          operation: "create",
          actionId: "start-sync-run",
          integrationId: selectedIntegration.integrationId
        }
      });
      if (!call.ok || !call.result?.id) {
        flash(call.result?.error ?? t("data_sync.dashboard.start.error", "Failed to start sync run"), "error");
        return;
      }
      flash(t("data_sync.dashboard.start.success", "Sync run started"), "success");
      setReloadToken((token) => token + 1);
      router.push(`/backend/data-sync/runs/${encodeURIComponent(call.result.id)}`);
    } catch (error) {
      const message = error instanceof Error ? error.message : t("data_sync.dashboard.start.error", "Failed to start sync run");
      flash(message, "error");
    }
  }, [batchSize, fullSync, router, runMutation, selectedDirection, selectedEntityType, selectedIntegration, t]);
  const handleSaveSchedule = React.useCallback(async () => {
    if (!selectedIntegration || !selectedEntityType) return;
    if (scheduleEditor.scheduleValue.trim().length === 0) {
      flash(t("data_sync.dashboard.schedule.invalidValue", "Provide a schedule value before saving."), "error");
      return;
    }
    setIsSavingSchedule(true);
    try {
      const call = await runMutation({
        // Keyed upsert (POST). When the editor holds an existing schedule's
        // `updatedAt`, the lock header version-checks the resolved row on the
        // server; a brand-new schedule has a null `updatedAt`, so the header is
        // empty and the create path stays unaffected.
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(scheduleEditor.updatedAt),
          () => apiCall("/api/data_sync/schedules", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              integrationId: selectedIntegration.integrationId,
              entityType: selectedEntityType,
              direction: selectedDirection,
              scheduleType: scheduleEditor.scheduleType,
              scheduleValue: scheduleEditor.scheduleValue.trim(),
              timezone: scheduleEditor.timezone.trim() || DEFAULT_TIMEZONE,
              fullSync: scheduleEditor.fullSync,
              isEnabled: scheduleEditor.isEnabled
            })
          }, { fallback: null })
        ),
        mutationPayload: {
          integrationId: selectedIntegration.integrationId,
          entityType: selectedEntityType,
          direction: selectedDirection,
          scheduleType: scheduleEditor.scheduleType,
          scheduleValue: scheduleEditor.scheduleValue.trim(),
          timezone: scheduleEditor.timezone.trim() || DEFAULT_TIMEZONE,
          fullSync: scheduleEditor.fullSync,
          isEnabled: scheduleEditor.isEnabled
        },
        context: {
          operation: "update",
          actionId: "save-sync-schedule",
          integrationId: selectedIntegration.integrationId
        }
      });
      if (!call.ok || !call.result) {
        const conflictError = Object.assign(
          new Error(call.result?.error ?? t("data_sync.dashboard.schedule.error", "Failed to save recurring schedule")),
          {
            status: call.status,
            ...call.result && typeof call.result === "object" ? call.result : {}
          }
        );
        if (surfaceRecordConflict(conflictError, t)) {
          return;
        }
        flash(call.result?.error ?? t("data_sync.dashboard.schedule.error", "Failed to save recurring schedule"), "error");
        return;
      }
      setScheduleEditor({
        id: call.result.id,
        scheduleType: call.result.scheduleType,
        scheduleValue: call.result.scheduleValue,
        timezone: call.result.timezone,
        fullSync: call.result.fullSync,
        isEnabled: call.result.isEnabled,
        lastRunAt: call.result.lastRunAt,
        updatedAt: call.result.updatedAt ?? null
      });
      flash(t("data_sync.dashboard.schedule.success", "Recurring schedule saved"), "success");
    } catch (error) {
      const message = error instanceof Error ? error.message : t("data_sync.dashboard.schedule.error", "Failed to save recurring schedule");
      flash(message, "error");
    } finally {
      setIsSavingSchedule(false);
    }
  }, [runMutation, scheduleEditor, selectedDirection, selectedEntityType, selectedIntegration, t]);
  const handleDeleteSchedule = React.useCallback(async () => {
    if (!scheduleEditor.id) return;
    setIsDeletingSchedule(true);
    try {
      const call = await runMutation({
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(scheduleEditor.updatedAt),
          () => apiCall(`/api/data_sync/schedules/${encodeURIComponent(scheduleEditor.id)}`, {
            method: "DELETE"
          }, { fallback: null })
        ),
        mutationPayload: {
          scheduleId: scheduleEditor.id
        },
        context: {
          operation: "delete",
          actionId: "delete-sync-schedule"
        }
      });
      if (!call.ok) {
        flash(call.result?.error ?? t("data_sync.dashboard.schedule.deleteError", "Failed to remove recurring schedule"), "error");
        return;
      }
      setScheduleEditor(buildDefaultScheduleState(selectedEntityType));
      flash(t("data_sync.dashboard.schedule.deleteSuccess", "Recurring schedule removed"), "success");
    } catch (error) {
      const message = error instanceof Error ? error.message : t("data_sync.dashboard.schedule.deleteError", "Failed to remove recurring schedule");
      flash(message, "error");
    } finally {
      setIsDeletingSchedule(false);
    }
  }, [runMutation, scheduleEditor.id, scheduleEditor.updatedAt, selectedEntityType, t]);
  const filters = [
    {
      id: "status",
      type: "select",
      label: t("data_sync.dashboard.filters.status"),
      options: [
        { label: t("data_sync.dashboard.filters.allStatuses"), value: "" },
        { label: t("data_sync.dashboard.status.pending"), value: "pending" },
        { label: t("data_sync.dashboard.status.running"), value: "running" },
        { label: t("data_sync.dashboard.status.completed"), value: "completed" },
        { label: t("data_sync.dashboard.status.failed"), value: "failed" },
        { label: t("data_sync.dashboard.status.cancelled"), value: "cancelled" }
      ]
    },
    {
      id: "direction",
      type: "select",
      label: t("data_sync.dashboard.columns.direction"),
      options: [
        { label: t("data_sync.dashboard.filters.allDirections"), value: "" },
        { label: t("data_sync.dashboard.direction.import"), value: "import" },
        { label: t("data_sync.dashboard.direction.export"), value: "export" }
      ]
    }
  ];
  const columns = React.useMemo(() => [
    {
      accessorKey: "integrationId",
      header: t("data_sync.dashboard.columns.integration"),
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "font-medium text-sm", children: row.original.integrationId })
    },
    {
      accessorKey: "entityType",
      header: t("data_sync.dashboard.columns.entityType")
    },
    {
      accessorKey: "direction",
      header: t("data_sync.dashboard.columns.direction"),
      cell: ({ row }) => /* @__PURE__ */ jsx(Badge, { variant: "outline", children: t(`data_sync.dashboard.direction.${row.original.direction}`) })
    },
    {
      accessorKey: "status",
      header: t("data_sync.dashboard.columns.status"),
      cell: ({ row }) => /* @__PURE__ */ jsx(StatusBadge, { variant: getSyncRunStatusVariant(row.original.status), children: t(`data_sync.dashboard.status.${row.original.status}`) })
    },
    {
      accessorKey: "createdCount",
      header: t("data_sync.dashboard.columns.created")
    },
    {
      accessorKey: "updatedCount",
      header: t("data_sync.dashboard.columns.updated")
    },
    {
      accessorKey: "failedCount",
      header: t("data_sync.dashboard.columns.failed")
    },
    {
      accessorKey: "createdAt",
      header: t("data_sync.dashboard.columns.createdAt"),
      cell: ({ row }) => new Date(row.original.createdAt).toLocaleString()
    }
  ], [t]);
  const canStartSelectedIntegration = Boolean(
    selectedIntegration && selectedEntityType && selectedIntegration.isEnabled && selectedIntegration.canStartRun !== false && selectedIntegration.hasCredentials
  );
  const hasSavedSchedule = Boolean(scheduleEditor.id);
  const selectedEntityLabel = selectedEntityType ? formatEntityTypeLabel(selectedEntityType) : t("data_sync.dashboard.columns.entityType");
  const integrationStateVariant = getSyncSummaryVariant(selectedIntegration?.isEnabled ? "enabled" : "disabled");
  const credentialsVariant = getSyncSummaryVariant(selectedIntegration?.hasCredentials ? "ready" : "missing");
  const scheduleVariant = getSyncSummaryVariant(
    hasSavedSchedule ? scheduleEditor.isEnabled ? "scheduled" : "paused" : "none"
  );
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { className: "space-y-6", children: [
    /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsxs(CardHeader, { className: "space-y-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs font-medium uppercase tracking-widest text-muted-foreground", children: [
              /* @__PURE__ */ jsx(Repeat, { className: "size-4" }),
              /* @__PURE__ */ jsx("span", { children: t("data_sync.dashboard.start.eyebrow", "Run once or keep it recurring") })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsx(CardTitle, { children: t("data_sync.dashboard.start.title", "Start or schedule a sync") }),
              /* @__PURE__ */ jsx("p", { className: "max-w-3xl text-sm text-muted-foreground", children: t("data_sync.dashboard.start.description", "Pick a sync target, launch an ad-hoc run, or save a recurring schedule for the same entity and direction from this page.") })
            ] })
          ] }),
          selectedIntegration ? /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", children: /* @__PURE__ */ jsxs(Link, { href: selectedIntegration.settingsPath, children: [
            /* @__PURE__ */ jsx(Settings2, { className: "mr-2 size-4" }),
            t("integrations.marketplace.configure")
          ] }) }) : null
        ] }),
        selectedIntegration ? /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2", children: [
          /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "gap-1.5", children: [
            /* @__PURE__ */ jsx(PlugZap, { className: "size-3.5" }),
            selectedIntegration.title
          ] }),
          /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "gap-1.5", children: [
            /* @__PURE__ */ jsx(ArrowRightLeft, { className: "size-3.5" }),
            t(`data_sync.dashboard.direction.${selectedDirection}`)
          ] }),
          /* @__PURE__ */ jsxs(Badge, { variant: integrationStateVariant, className: "gap-1.5", children: [
            /* @__PURE__ */ jsx(ShieldCheck, { className: "size-3.5" }),
            selectedIntegration.isEnabled ? t("data_sync.dashboard.start.status.enabled", "Integration enabled") : t("data_sync.dashboard.start.status.disabled", "Integration disabled")
          ] }),
          /* @__PURE__ */ jsxs(Badge, { variant: credentialsVariant, className: "gap-1.5", children: [
            /* @__PURE__ */ jsx(PlugZap, { className: "size-3.5" }),
            selectedIntegration.hasCredentials ? t("data_sync.dashboard.start.status.credentialsReady", "Credentials ready") : t("data_sync.dashboard.start.status.credentialsMissing", "Credentials missing")
          ] }),
          /* @__PURE__ */ jsxs(Badge, { variant: scheduleVariant, className: "gap-1.5", children: [
            /* @__PURE__ */ jsx(CalendarClock, { className: "size-3.5" }),
            hasSavedSchedule ? scheduleEditor.isEnabled ? t("data_sync.dashboard.schedule.status.enabled", "Recurring schedule active") : t("data_sync.dashboard.schedule.status.disabled", "Recurring schedule paused") : t("data_sync.dashboard.schedule.status.none", "No recurring schedule")
          ] })
        ] }) : null
      ] }),
      /* @__PURE__ */ jsxs(CardContent, { className: "space-y-6", children: [
        /* @__PURE__ */ jsxs("div", { className: "grid gap-4 xl:grid-cols-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-2 xl:col-span-1", children: [
            /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-2 text-sm font-medium", children: [
              /* @__PURE__ */ jsx(PlugZap, { className: "size-4 text-muted-foreground" }),
              /* @__PURE__ */ jsx("span", { children: t("data_sync.dashboard.columns.integration") })
            ] }),
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: selectedIntegrationId || void 0,
                onValueChange: (value) => setSelectedIntegrationId(value ?? ""),
                disabled: isLoadingOptions || options.length === 0,
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { size: "lg", children: /* @__PURE__ */ jsx(
                    SelectValue,
                    {
                      placeholder: options.length === 0 ? t("integrations.marketplace.noResults", "No integrations found") : void 0
                    }
                  ) }),
                  /* @__PURE__ */ jsx(SelectContent, { children: options.map((item) => /* @__PURE__ */ jsx(SelectItem, { value: item.integrationId, children: item.title }, item.integrationId)) })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-2 text-sm font-medium", children: [
              /* @__PURE__ */ jsx(Boxes, { className: "size-4 text-muted-foreground" }),
              /* @__PURE__ */ jsx("span", { children: t("data_sync.dashboard.columns.entityType") })
            ] }),
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: selectedEntityType || void 0,
                onValueChange: (value) => setSelectedEntityType(value ?? ""),
                disabled: entityOptions.length === 0,
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { size: "lg", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                  /* @__PURE__ */ jsx(SelectContent, { children: entityOptions.map((entityType) => /* @__PURE__ */ jsx(SelectItem, { value: entityType, children: formatEntityTypeLabel(entityType) }, entityType)) })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-2 text-sm font-medium", children: [
              /* @__PURE__ */ jsx(ArrowRightLeft, { className: "size-4 text-muted-foreground" }),
              /* @__PURE__ */ jsx("span", { children: t("data_sync.dashboard.columns.direction") })
            ] }),
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: selectedDirection,
                onValueChange: (value) => setSelectedDirection(value === "export" ? "export" : "import"),
                disabled: selectedIntegration?.direction !== "bidirectional",
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { size: "lg", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                  /* @__PURE__ */ jsxs(SelectContent, { children: [
                    /* @__PURE__ */ jsx(SelectItem, { value: "import", children: t("data_sync.dashboard.direction.import") }),
                    selectedIntegration?.direction === "bidirectional" || selectedIntegration?.direction === "export" ? /* @__PURE__ */ jsx(SelectItem, { value: "export", children: t("data_sync.dashboard.direction.export") }) : null
                  ] })
                ]
              }
            )
          ] })
        ] }),
        selectedIntegration?.description ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: selectedIntegration.description }) : null,
        /* @__PURE__ */ jsxs("div", { className: "grid gap-4 xl:grid-cols-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "rounded-xl border bg-muted/30 p-4", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
              /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx(Play, { className: "size-4 text-primary" }),
                  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("data_sync.dashboard.start.runNowTitle", "Run once now") })
                ] }),
                /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("data_sync.dashboard.start.runNowDescription", "Use this for the next immediate sync. Batch size and full-sync mode apply only to this manual run.") })
              ] }),
              /* @__PURE__ */ jsx(Badge, { variant: "outline", children: selectedEntityLabel })
            ] }),
            /* @__PURE__ */ jsx(Separator, { className: "my-4" }),
            /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-[minmax(0,180px)_1fr]", children: [
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-2 text-sm font-medium", children: [
                  /* @__PURE__ */ jsx(Gauge, { className: "size-4 text-muted-foreground" }),
                  /* @__PURE__ */ jsx("span", { children: t("data_sync.dashboard.start.batchSize", "Batch size") })
                ] }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    value: batchSize,
                    onChange: (event) => setBatchSize(event.target.value),
                    inputMode: "numeric"
                  }
                )
              ] }),
              /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-background p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
                /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
                  /* @__PURE__ */ jsx(Label, { className: "text-sm font-medium", children: t("data_sync.dashboard.start.fullSync", "Run as full sync") }),
                  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("data_sync.dashboard.start.fullSyncHelp", "Ignore the saved cursor and process the entire source again for this run.") })
                ] }),
                /* @__PURE__ */ jsx(Switch, { checked: fullSync, onCheckedChange: setFullSync })
              ] }) })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "mt-4 flex flex-wrap items-center justify-between gap-3", children: [
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("data_sync.dashboard.start.runNowFootnote", "Manual runs show progress immediately and land on the run detail page after launch.") }),
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  onClick: () => void handleStartSync(),
                  disabled: !canStartSelectedIntegration,
                  children: [
                    /* @__PURE__ */ jsx(Play, { className: "mr-2 size-4" }),
                    t("data_sync.dashboard.start.submit", "Start sync")
                  ]
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "rounded-xl border bg-muted/30 p-4", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
              /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx(CalendarClock, { className: "size-4 text-primary" }),
                  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("data_sync.dashboard.schedule.title", "Recurring schedule") })
                ] }),
                /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("data_sync.dashboard.schedule.description", "Save a repeating schedule for the selected integration, entity, and direction without leaving this dashboard.") })
              ] }),
              /* @__PURE__ */ jsx(Badge, { variant: "outline", children: hasSavedSchedule ? scheduleEditor.isEnabled ? t("data_sync.dashboard.schedule.status.shortEnabled", "Scheduled") : t("data_sync.dashboard.schedule.status.shortDisabled", "Paused") : t("data_sync.dashboard.schedule.status.shortNone", "One-time only") })
            ] }),
            /* @__PURE__ */ jsx(Separator, { className: "my-4" }),
            /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-2 text-sm font-medium", children: [
                  /* @__PURE__ */ jsx(Clock3, { className: "size-4 text-muted-foreground" }),
                  /* @__PURE__ */ jsx("span", { children: t("data_sync.dashboard.schedule.type", "Schedule type") })
                ] }),
                /* @__PURE__ */ jsxs(
                  Select,
                  {
                    value: scheduleEditor.scheduleType,
                    onValueChange: (value) => updateScheduleEditor({
                      scheduleType: value === "cron" ? "cron" : "interval"
                    }),
                    disabled: isLoadingSchedule || isSavingSchedule || isDeletingSchedule || !selectedIntegration || !selectedEntityType,
                    children: [
                      /* @__PURE__ */ jsx(SelectTrigger, { size: "lg", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                      /* @__PURE__ */ jsxs(SelectContent, { children: [
                        /* @__PURE__ */ jsx(SelectItem, { value: "interval", children: t("data_sync.dashboard.schedule.interval", "Interval") }),
                        /* @__PURE__ */ jsx(SelectItem, { value: "cron", children: t("data_sync.dashboard.schedule.cron", "Cron") })
                      ] })
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-2 text-sm font-medium", children: [
                  /* @__PURE__ */ jsx(CalendarClock, { className: "size-4 text-muted-foreground" }),
                  /* @__PURE__ */ jsx("span", { children: scheduleEditor.scheduleType === "cron" ? t("data_sync.dashboard.schedule.cronValue", "Cron expression") : t("data_sync.dashboard.schedule.intervalValue", "Interval") })
                ] }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    value: scheduleEditor.scheduleValue,
                    onChange: (event) => updateScheduleEditor({ scheduleValue: event.target.value }),
                    disabled: isLoadingSchedule || isSavingSchedule || isDeletingSchedule || !selectedIntegration || !selectedEntityType,
                    placeholder: scheduleEditor.scheduleType === "cron" ? "0 * * * *" : "1h"
                  }
                ),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: scheduleEditor.scheduleType === "cron" ? t("data_sync.dashboard.schedule.cronHelp", "Example: `0 * * * *` runs at the start of every hour.") : t("data_sync.dashboard.schedule.intervalHelp", "Example: `1h`, `6h`, or `24h` for repeating intervals.") })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2 sm:col-span-2", children: [
                /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-2 text-sm font-medium", children: [
                  /* @__PURE__ */ jsx(Clock3, { className: "size-4 text-muted-foreground" }),
                  /* @__PURE__ */ jsx("span", { children: t("data_sync.dashboard.schedule.timezone", "Timezone") })
                ] }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    value: scheduleEditor.timezone,
                    onChange: (event) => updateScheduleEditor({ timezone: event.target.value }),
                    disabled: isLoadingSchedule || isSavingSchedule || isDeletingSchedule || !selectedIntegration || !selectedEntityType
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "mt-4 grid gap-3", children: [
              /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-background p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
                /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
                  /* @__PURE__ */ jsx(Label, { className: "text-sm font-medium", children: t("data_sync.dashboard.schedule.fullSync", "Run scheduled jobs as full sync") }),
                  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("data_sync.dashboard.schedule.fullSyncHelp", "When enabled, every recurring run starts from the beginning instead of the saved cursor.") })
                ] }),
                /* @__PURE__ */ jsx(
                  Switch,
                  {
                    checked: scheduleEditor.fullSync,
                    onCheckedChange: (checked) => updateScheduleEditor({ fullSync: checked }),
                    disabled: isLoadingSchedule || isSavingSchedule || isDeletingSchedule || !selectedIntegration || !selectedEntityType
                  }
                )
              ] }) }),
              /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-background p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
                /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
                  /* @__PURE__ */ jsx(Label, { className: "text-sm font-medium", children: t("data_sync.dashboard.schedule.enabled", "Schedule enabled") }),
                  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("data_sync.dashboard.schedule.enabledHelp", "Pause the recurring job without deleting the schedule definition.") })
                ] }),
                /* @__PURE__ */ jsx(
                  Switch,
                  {
                    checked: scheduleEditor.isEnabled,
                    onCheckedChange: (checked) => updateScheduleEditor({ isEnabled: checked }),
                    disabled: isLoadingSchedule || isSavingSchedule || isDeletingSchedule || !selectedIntegration || !selectedEntityType
                  }
                )
              ] }) })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "mt-4 flex flex-wrap items-center justify-between gap-3", children: [
              /* @__PURE__ */ jsx("div", { className: "space-y-1 text-xs text-muted-foreground", children: /* @__PURE__ */ jsx("div", { children: hasSavedSchedule ? scheduleEditor.lastRunAt ? t("data_sync.dashboard.schedule.lastRun", "Last scheduled run: {value}", {
                value: new Date(scheduleEditor.lastRunAt).toLocaleString()
              }) : t("data_sync.dashboard.schedule.neverRun", "Saved, but no scheduled execution has completed yet.") : t("data_sync.dashboard.schedule.none", "No recurring schedule saved for this target yet.") }) }),
              /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2", children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    variant: "outline",
                    onClick: () => void handleDeleteSchedule(),
                    disabled: !hasSavedSchedule || isDeletingSchedule,
                    children: isDeletingSchedule ? t("data_sync.dashboard.schedule.deleting", "Removing...") : t("data_sync.dashboard.schedule.delete", "Remove schedule")
                  }
                ),
                /* @__PURE__ */ jsxs(
                  Button,
                  {
                    type: "button",
                    variant: "outline",
                    onClick: () => void handleSaveSchedule(),
                    disabled: isSavingSchedule || !selectedIntegration || !selectedEntityType,
                    children: [
                      /* @__PURE__ */ jsx(CalendarClock, { className: "mr-2 size-4" }),
                      isSavingSchedule ? t("data_sync.dashboard.schedule.saving", "Saving...") : t("data_sync.dashboard.schedule.save", "Save recurring schedule")
                    ]
                  }
                )
              ] })
            ] })
          ] })
        ] }),
        selectedIntegration && !selectedIntegration.isEnabled ? /* @__PURE__ */ jsx(Alert, { variant: "warning", children: /* @__PURE__ */ jsx(AlertDescription, { children: t("integrations.detail.state.disabled", "This integration is disabled. Enable it on the integration settings page before starting a sync.") }) }) : null,
        selectedIntegration && !selectedIntegration.hasCredentials ? /* @__PURE__ */ jsx(Alert, { variant: "warning", children: /* @__PURE__ */ jsx(AlertDescription, { children: t("integrations.detail.credentials.notConfigured", "Credentials are not configured yet. Save the integration credentials before starting a sync.") }) }) : null,
        selectedIntegration && selectedIntegration.canStartRun === false ? /* @__PURE__ */ jsx(Alert, { variant: "info", children: /* @__PURE__ */ jsx(AlertDescription, { children: t("data_sync.dashboard.start.providerManaged", "This integration starts sync runs from its own setup flow. Open the integration settings page to continue.") }) }) : null
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      DataTable,
      {
        stickyActionsColumn: true,
        title: t("data_sync.dashboard.title"),
        columns,
        data: rows,
        filters,
        filterValues,
        onFiltersApply: handleFiltersApply,
        onFiltersClear: handleFiltersClear,
        searchValue: search,
        onSearchChange: (value) => {
          setSearch(value);
          setPage(1);
        },
        searchPlaceholder: t("data_sync.dashboard.searchPlaceholder"),
        perspective: { tableId: "data_sync.runs" },
        onRowClick: (row) => {
          router.push(`/backend/data-sync/runs/${encodeURIComponent(row.id)}`);
        },
        rowActions: (row) => /* @__PURE__ */ jsx(RowActions, { items: [
          {
            id: "view",
            label: t("data_sync.dashboard.actions.view"),
            onSelect: () => {
              router.push(`/backend/data-sync/runs/${encodeURIComponent(row.id)}`);
            }
          },
          ...row.status === "running" ? [{
            id: "cancel",
            label: t("data_sync.runs.detail.cancel"),
            destructive: true,
            onSelect: () => {
              void handleCancel(row);
            }
          }] : [],
          ...row.status === "failed" ? [{
            id: "retry",
            label: t("data_sync.runs.detail.retry"),
            onSelect: () => {
              void handleRetry(row);
            }
          }] : []
        ] }),
        pagination: { page, pageSize: 20, total, totalPages, onPageChange: setPage },
        isLoading
      }
    )
  ] }) });
}
export {
  SyncRunsDashboardPage as default
};
//# sourceMappingURL=page.js.map
