"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 { RowActions } from "@open-mercato/ui/backend/RowActions";
import { Button } from "@open-mercato/ui/primitives/button";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { ErrorMessage } from "@open-mercato/ui/backend/detail";
import { Settings, Inbox, Copy } from "lucide-react";
import { CategoryBadge, useCategoryLabels } from "../../components/proposals/CategoryBadge.js";
const STATUS_COLORS = {
  pending: "bg-yellow-100 text-yellow-800",
  partial: "bg-blue-100 text-blue-800",
  accepted: "bg-green-100 text-green-800",
  rejected: "bg-red-100 text-red-800",
  processing: "bg-purple-100 text-purple-800"
};
function ConfidenceBadge({ value }) {
  const num = parseFloat(value);
  const pct = Math.round(num * 100);
  const color = num >= 0.8 ? "bg-green-100 text-green-800" : num >= 0.6 ? "bg-yellow-100 text-yellow-800" : "bg-red-100 text-red-800";
  return /* @__PURE__ */ jsxs("span", { className: `inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${color}`, children: [
    pct,
    "%"
  ] });
}
function StatusBadge({ status }) {
  const t = useT();
  const statusLabels = {
    pending: t("inbox_ops.status.pending", "Pending"),
    partial: t("inbox_ops.status.partial", "Partial"),
    accepted: t("inbox_ops.status.accepted", "Accepted"),
    rejected: t("inbox_ops.status.rejected", "Rejected"),
    processing: t("inbox_ops.status.processing", "Processing")
  };
  const color = STATUS_COLORS[status] || "bg-gray-100 text-gray-800";
  return /* @__PURE__ */ jsx("span", { className: `inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${color}`, children: statusLabels[status] || status });
}
function InboxOpsProposalsPage() {
  const t = useT();
  const router = useRouter();
  const scopeVersion = useOrganizationScopeVersion();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const { runMutation } = useGuardedMutation({
    contextId: "inbox-ops-proposals"
  });
  const [items, setItems] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(25);
  const [filterValues, setFilterValues] = React.useState({});
  const [search, setSearch] = React.useState("");
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [initialLoadComplete, setInitialLoadComplete] = React.useState(false);
  const [counts, setCounts] = React.useState({ pending: 0, partial: 0, accepted: 0, rejected: 0 });
  const [settings, setSettings] = React.useState(null);
  const [copied, setCopied] = React.useState(false);
  const statusFilter = typeof filterValues.status === "string" ? filterValues.status : void 0;
  const categoryFilter = typeof filterValues.category === "string" ? filterValues.category : void 0;
  const loadProposals = React.useCallback(async () => {
    setIsLoading(true);
    setError(null);
    const params = new URLSearchParams();
    params.set("page", String(page));
    params.set("pageSize", String(pageSize));
    if (statusFilter) params.set("status", statusFilter);
    if (categoryFilter) params.set("category", categoryFilter);
    if (search.trim()) params.set("search", search.trim());
    try {
      const result = await apiCall(`/api/inbox_ops/proposals?${params}`);
      if (result?.ok && result.result?.items) {
        setItems(result.result.items);
        setTotal(result.result.total || 0);
      } else {
        setError(t("inbox_ops.flash.load_failed", "Failed to load proposals"));
      }
    } catch {
      setError(t("inbox_ops.flash.load_failed", "Failed to load proposals"));
    }
    setIsLoading(false);
  }, [page, pageSize, statusFilter, categoryFilter, search, scopeVersion, t]);
  const loadCounts = React.useCallback(async () => {
    const result = await apiCall("/api/inbox_ops/proposals/counts");
    if (result?.ok && result.result) setCounts(result.result);
  }, [scopeVersion]);
  const loadSettings = React.useCallback(async () => {
    const result = await apiCall("/api/inbox_ops/settings");
    if (result?.ok && result.result?.settings) setSettings(result.result.settings);
  }, [scopeVersion]);
  React.useEffect(() => {
    Promise.all([loadProposals(), loadCounts(), loadSettings()]).then(() => {
      setInitialLoadComplete(true);
    });
  }, []);
  React.useEffect(() => {
    if (initialLoadComplete) loadProposals();
  }, [page, statusFilter, categoryFilter, search, scopeVersion]);
  React.useEffect(() => {
    if (initialLoadComplete) {
      loadCounts();
      loadSettings();
    }
  }, [scopeVersion]);
  const handleCopyAddress = React.useCallback(() => {
    if (settings?.inboxAddress) {
      navigator.clipboard.writeText(settings.inboxAddress);
      setCopied(true);
      setTimeout(() => setCopied(false), 2e3);
    }
  }, [settings]);
  const handleRefresh = React.useCallback(() => {
    loadProposals();
    loadCounts();
  }, [loadProposals, loadCounts]);
  const handleFiltersApply = React.useCallback((values) => {
    setFilterValues(values);
    setPage(1);
  }, []);
  const handleFiltersClear = React.useCallback(() => {
    setFilterValues({});
    setPage(1);
  }, []);
  const handleRejectProposal = React.useCallback(async (proposalId) => {
    const confirmed = await confirm({
      title: t("inbox_ops.action.reject_all", "Reject Proposal"),
      text: t("inbox_ops.action.reject_all_confirm", "Reject all pending actions in this proposal?")
    });
    if (!confirmed) return;
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/proposals/${proposalId}/reject`,
        { method: "POST" }
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      flash(t("inbox_ops.action.proposal_rejected", "Proposal rejected"), "success");
      loadProposals();
      loadCounts();
    } else {
      flash(t("inbox_ops.flash.action_reject_failed", "Failed to reject"), "error");
    }
  }, [confirm, t, loadProposals, loadCounts, runMutation]);
  const categoryLabels = useCategoryLabels();
  const byCategory = counts.byCategory || {};
  const filters = React.useMemo(() => [
    {
      id: "status",
      label: t("inbox_ops.list.filters.status", "Status"),
      type: "select",
      options: [
        { value: "pending", label: `${t("inbox_ops.status.pending", "Pending")} (${counts.pending})` },
        { value: "partial", label: `${t("inbox_ops.status.partial", "Partial")} (${counts.partial})` },
        { value: "accepted", label: `${t("inbox_ops.status.accepted", "Accepted")} (${counts.accepted})` },
        { value: "rejected", label: `${t("inbox_ops.status.rejected", "Rejected")} (${counts.rejected})` }
      ]
    },
    {
      id: "category",
      label: t("inbox_ops.category", "Category"),
      type: "select",
      options: [
        { value: "rfq", label: `${categoryLabels.rfq} (${byCategory.rfq || 0})` },
        { value: "order", label: `${categoryLabels.order} (${byCategory.order || 0})` },
        { value: "order_update", label: `${categoryLabels.order_update} (${byCategory.order_update || 0})` },
        { value: "complaint", label: `${categoryLabels.complaint} (${byCategory.complaint || 0})` },
        { value: "shipping_update", label: `${categoryLabels.shipping_update} (${byCategory.shipping_update || 0})` },
        { value: "inquiry", label: `${categoryLabels.inquiry} (${byCategory.inquiry || 0})` },
        { value: "payment", label: `${categoryLabels.payment} (${byCategory.payment || 0})` },
        { value: "other", label: `${categoryLabels.other} (${byCategory.other || 0})` }
      ]
    }
  ], [t, counts, categoryLabels, byCategory]);
  const columns = React.useMemo(() => [
    {
      accessorKey: "summary",
      header: t("inbox_ops.summary", "Summary"),
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
        /* @__PURE__ */ jsx(
          Link,
          {
            href: `/backend/inbox-ops/proposals/${row.original.id}`,
            className: "text-sm font-medium text-primary hover:underline truncate max-w-[300px] block",
            children: row.original.emailSubject || row.original.summary?.slice(0, 80) || t("inbox_ops.untitled_proposal", "Untitled proposal")
          }
        ),
        row.original.emailFrom && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground truncate block", children: row.original.emailFrom })
      ] })
    },
    {
      accessorKey: "status",
      header: t("inbox_ops.list.status", "Status"),
      cell: ({ row }) => /* @__PURE__ */ jsx(StatusBadge, { status: row.original.status })
    },
    {
      accessorKey: "category",
      header: t("inbox_ops.category", "Category"),
      cell: ({ row }) => /* @__PURE__ */ jsx(CategoryBadge, { category: row.original.category })
    },
    {
      id: "actions_count",
      header: t("inbox_ops.list.progress", "Progress"),
      cell: ({ row }) => {
        const pending = row.original.pendingActionCount ?? 0;
        const total2 = row.original.actionCount ?? 0;
        if (total2 === 0) return /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: "\u2014" });
        return /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: t("inbox_ops.list.action_summary", "{pending}/{total} actions").replace("{pending}", String(pending)).replace("{total}", String(total2)) });
      }
    },
    {
      accessorKey: "confidence",
      header: t("inbox_ops.confidence", "Confidence"),
      cell: ({ row }) => /* @__PURE__ */ jsx(ConfidenceBadge, { value: row.original.confidence })
    },
    {
      accessorKey: "receivedAt",
      header: t("inbox_ops.received_at", "Received"),
      cell: ({ row }) => {
        const dateStr = row.original.receivedAt || row.original.createdAt;
        const d = new Date(dateStr);
        return /* @__PURE__ */ jsxs("span", { className: "text-sm text-muted-foreground", children: [
          d.toLocaleDateString(),
          " ",
          d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
        ] });
      }
    }
  ], [t]);
  const totalCount = counts.pending + counts.partial + counts.accepted + counts.rejected;
  const emptyStateContent = initialLoadComplete && totalCount === 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-16 text-center", children: [
    /* @__PURE__ */ jsx(Inbox, { className: "h-12 w-12 text-muted-foreground mb-4" }),
    /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold mb-2", children: t("inbox_ops.empty.title", "Forward emails to start") }),
    settings?.inboxAddress && /* @__PURE__ */ jsxs("div", { className: "mt-4 flex items-center gap-2 bg-muted rounded-lg px-4 py-3", children: [
      /* @__PURE__ */ jsx("code", { className: "text-sm font-mono", children: settings.inboxAddress }),
      /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: handleCopyAddress, children: [
        /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" }),
        copied ? t("inbox_ops.settings.copied", "Copied") : t("inbox_ops.settings.copy", "Copy")
      ] })
    ] }),
    /* @__PURE__ */ jsxs("ol", { className: "mt-6 text-sm text-muted-foreground text-left space-y-2", children: [
      /* @__PURE__ */ jsxs("li", { children: [
        "1. ",
        t("inbox_ops.empty.step1", "Forward any email thread to this address")
      ] }),
      /* @__PURE__ */ jsxs("li", { children: [
        "2. ",
        t("inbox_ops.empty.step2", "We'll analyze it and propose actions")
      ] }),
      /* @__PURE__ */ jsxs("li", { children: [
        "3. ",
        t("inbox_ops.empty.step3", "Review and accept with one click")
      ] })
    ] })
  ] }) : void 0;
  if (error && !initialLoadComplete) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error }) }) });
  }
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      DataTable,
      {
        stickyActionsColumn: true,
        title: t("inbox_ops.title", "AI Inbox Actions"),
        refreshButton: {
          label: t("inbox_ops.list.actions.refresh", "Refresh"),
          onRefresh: handleRefresh
        },
        actions: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          settings?.inboxAddress && /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: handleCopyAddress, children: [
            /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" }),
            /* @__PURE__ */ jsx("span", { className: "hidden md:inline ml-1", children: copied ? t("inbox_ops.settings.copied", "Copied") : t("inbox_ops.settings.copy", "Copy") })
          ] }),
          /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", asChild: true, children: /* @__PURE__ */ jsxs(Link, { href: "/backend/inbox-ops/settings", children: [
            /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" }),
            /* @__PURE__ */ jsx("span", { className: "hidden md:inline ml-1", children: t("inbox_ops.list.actions.settings", "Settings") })
          ] }) })
        ] }),
        columns,
        data: items,
        searchValue: search,
        onSearchChange: (value) => {
          setSearch(value);
          setPage(1);
        },
        searchPlaceholder: t("inbox_ops.list.searchPlaceholder", "Search proposals..."),
        filters,
        filterValues,
        onFiltersApply: handleFiltersApply,
        onFiltersClear: handleFiltersClear,
        onRowClick: (row) => router.push(`/backend/inbox-ops/proposals/${row.id}`),
        rowActions: (row) => /* @__PURE__ */ jsx(RowActions, { items: [
          {
            id: "view",
            label: t("inbox_ops.list.actions.view", "View"),
            onSelect: () => router.push(`/backend/inbox-ops/proposals/${row.id}`)
          },
          ...row.status === "pending" || row.status === "partial" ? [{
            id: "reject",
            label: t("inbox_ops.list.actions.reject", "Reject"),
            destructive: true,
            onSelect: () => handleRejectProposal(row.id)
          }] : []
        ] }),
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize),
          onPageChange: setPage
        },
        isLoading,
        emptyState: emptyStateContent
      }
    ) }),
    ConfirmDialogElement
  ] });
}
export {
  InboxOpsProposalsPage as default
};
//# sourceMappingURL=page.js.map
