"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Building2, Hash, Users, BarChart3, StickyNote } from "lucide-react";
import { updateCrud, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { AttachmentsSection, ErrorMessage, LoadingMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { InjectionSpot, useInjectionWidgets } from "@open-mercato/ui/backend/injection/InjectionSpot";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { createTranslatorWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { CollapsibleZoneLayout } from "@open-mercato/ui/backend/crud/CollapsibleZoneLayout";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { E } from "../../../../../../generated/entities.ids.generated.js";
import { useOrganizationScopeDetail } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { DealsSection } from "../../../../components/detail/DealsSection.js";
import { ActivityLogTab } from "../../../../components/detail/ActivityLogTab.js";
import { CompanyPeopleSection } from "../../../../components/detail/CompanyPeopleSection.js";
import { coerceDisplayName } from "../../../../lib/displayName.js";
import { CompanyDetailHeader } from "../../../../components/detail/CompanyDetailHeader.js";
import { CompanyDetailTabs, resolveLegacyTab } from "../../../../components/detail/CompanyDetailTabs.js";
import { CompanyKpiBar } from "../../../../components/detail/CompanyKpiBar.js";
import { ScheduleActivityDialog } from "../../../../components/detail/ScheduleActivityDialog.js";
import { ChangelogTab } from "../../../../components/detail/ChangelogTab.js";
import { useInteractionMutations } from "../../../../components/detail/hooks/useInteractionMutations.js";
import {
  buildCompanyEditPayload,
  createCompanyEditFields,
  createCompanyDaneFiremyGroups,
  createCompanyEditSchema,
  mapCompanyOverviewToFormValues
} from "../../../../components/formConfig.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
function CompanyDetailV2Page({ params }) {
  const id = params?.id;
  const t = useT();
  const router = useRouter();
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const detailTranslator = React.useMemo(() => createTranslatorWithFallback(t), [t]);
  const [data, setData] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const initialTab = React.useMemo(() => {
    return resolveLegacyTab(searchParams?.get("tab"));
  }, [searchParams]);
  const [activeTab, setActiveTab] = React.useState(initialTab);
  const [sectionAction, setSectionAction] = React.useState(null);
  const [isDirty, setIsDirty] = React.useState(false);
  const [isSaving, setIsSaving] = React.useState(false);
  const formWrapperRef = React.useRef(null);
  const { organizationId } = useOrganizationScopeDetail();
  const formSchema = React.useMemo(() => createCompanyEditSchema(), []);
  const formFields = React.useMemo(() => createCompanyEditFields(t), [t]);
  const formGroups = React.useMemo(() => createCompanyDaneFiremyGroups(t), [t]);
  const initialValues = React.useMemo(
    () => data ? mapCompanyOverviewToFormValues(data) : void 0,
    [data]
  );
  const zoneSections = React.useMemo(() => [
    { id: "identity", icon: Building2, label: t("customers.companies.form.sections.identity", "Identity") },
    { id: "contact", icon: Hash, label: t("customers.companies.form.sections.contact", "Contact") },
    { id: "classification", icon: Users, label: t("customers.companies.form.sections.classification", "Classification") },
    { id: "businessProfile", icon: BarChart3, label: t("customers.companies.form.sections.businessProfile", "Business profile") },
    { id: "notes", icon: StickyNote, label: t("customers.companies.form.groups.notes", "Notes") },
    { id: "customFields", icon: Hash, label: t("customers.companies.form.groups.customAttributes", "Custom attributes") }
  ], [t]);
  const [scheduleDialogOpen, setScheduleDialogOpen] = React.useState(false);
  const [scheduleEditData, setScheduleEditData] = React.useState(null);
  const [activityRefreshKey, setActivityRefreshKey] = React.useState(0);
  const [dealCount, setDealCount] = React.useState(0);
  const currentCompanyId = data?.company?.id ?? null;
  const mutationContextId = React.useMemo(
    () => currentCompanyId ? `customer-company:${currentCompanyId}` : `customer-company:${id ?? "pending"}`,
    [currentCompanyId, id]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const companyDisplayName = coerceDisplayName(data?.company?.displayName);
  const companyName = companyDisplayName.trim().length ? companyDisplayName : t("customers.companies.list.deleteFallbackName", "this company");
  const initialLoadDoneRef = React.useRef(false);
  const loadData = React.useCallback(async () => {
    if (!id) {
      setIsNotFound(true);
      setIsLoading(false);
      return;
    }
    if (!initialLoadDoneRef.current) {
      setIsLoading(true);
    }
    setError(null);
    setIsNotFound(false);
    try {
      const payload = await readApiResultOrThrow(
        `/api/customers/companies/${encodeURIComponent(id)}`,
        void 0,
        { errorMessage: t("customers.companies.detail.error.load", "Failed to load company.") }
      );
      setData(payload);
    } catch (err) {
      if (err.status === 404) {
        setIsNotFound(true);
      } else {
        const message = err instanceof Error ? err.message : t("customers.companies.detail.error.load", "Failed to load company.");
        setError(message);
      }
      if (!initialLoadDoneRef.current) setData(null);
    } finally {
      setIsLoading(false);
      initialLoadDoneRef.current = true;
    }
  }, [id, t]);
  React.useEffect(() => {
    loadData().catch((err) => logger.warn("loadData failed", { component: "companies-v2", err }));
  }, [loadData]);
  React.useEffect(() => {
    setDealCount(data?.counts?.deals ?? 0);
  }, [data?.counts?.deals]);
  const handleActivityCreated = React.useCallback(() => {
    setActivityRefreshKey((k) => k + 1);
    loadData().catch((err) => logger.warn("reload after activity failed", { component: "companies-v2", err }));
  }, [loadData]);
  const plannedActivities = React.useMemo(() => {
    return data?.plannedActivitiesPreview ?? [];
  }, [data?.plannedActivitiesPreview]);
  const injectionContext = React.useMemo(
    () => ({
      formId: mutationContextId,
      companyId: currentCompanyId,
      resourceKind: "customers.company",
      resourceId: currentCompanyId ?? (id ?? void 0),
      data,
      retryLastMutation
    }),
    [currentCompanyId, data, id, mutationContextId, retryLastMutation]
  );
  const runMutationWithContext = React.useCallback(
    async (operation, mutationPayload) => {
      return runMutation({
        operation,
        mutationPayload,
        context: injectionContext
      });
    },
    [injectionContext, runMutation]
  );
  const { completeInteraction: handleMarkDone, cancelInteraction: handleCancelActivity } = useInteractionMutations({
    runMutationWithContext,
    onAfterChange: handleActivityCreated,
    logContext: "customers.companies-v2"
  });
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "customers.company",
      resourceId: currentCompanyId,
      updatedAt: data?.company?.updatedAt ?? data?.company?.updated_at ?? null,
      data,
      path: pathname
    })
  );
  const handleEditActivity = React.useCallback((activity) => {
    const raw = activity;
    const durationValue = typeof raw.duration === "number" ? raw.duration : typeof raw.durationMinutes === "number" ? raw.durationMinutes : null;
    const editPayload = {
      id: activity.id,
      updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : typeof raw.updated_at === "string" ? raw.updated_at : null,
      interactionType: typeof activity.interactionType === "string" ? activity.interactionType : void 0,
      title: typeof activity.title === "string" ? activity.title : null,
      body: typeof activity.body === "string" ? activity.body : null,
      scheduledAt: typeof activity.scheduledAt === "string" ? activity.scheduledAt : null,
      occurredAt: typeof activity.occurredAt === "string" ? activity.occurredAt : null,
      durationMinutes: durationValue,
      location: typeof raw.location === "string" ? raw.location : null,
      allDay: typeof raw.allDay === "boolean" ? raw.allDay : null,
      recurrenceRule: typeof raw.recurrenceRule === "string" ? raw.recurrenceRule : null,
      recurrenceEnd: typeof raw.recurrenceEnd === "string" ? raw.recurrenceEnd : null,
      participants: Array.isArray(raw.participants) ? raw.participants : null,
      reminderMinutes: typeof raw.reminderMinutes === "number" ? raw.reminderMinutes : null,
      visibility: typeof raw.visibility === "string" ? raw.visibility : null,
      linkedEntities: Array.isArray(raw.linkedEntities) ? raw.linkedEntities : null,
      guestPermissions: raw.guestPermissions && typeof raw.guestPermissions === "object" ? raw.guestPermissions : null,
      customValues: raw.customValues && typeof raw.customValues === "object" ? raw.customValues : null,
      phoneNumber: typeof raw.phoneNumber === "string" ? raw.phoneNumber : null
    };
    setScheduleEditData(editPayload);
    setScheduleDialogOpen(true);
  }, []);
  const openNewScheduleDialog = React.useCallback(() => {
    setScheduleEditData(null);
    setScheduleDialogOpen(true);
  }, []);
  const handleAddActivity = React.useCallback((kind) => {
    setScheduleEditData({
      id: "",
      interactionType: kind,
      title: null,
      body: null,
      scheduledAt: null,
      durationMinutes: null,
      location: null,
      allDay: null,
      recurrenceRule: null,
      recurrenceEnd: null,
      participants: null,
      reminderMinutes: null,
      visibility: null,
      linkedEntities: null,
      guestPermissions: null
    });
    setScheduleDialogOpen(true);
  }, []);
  const { widgets: injectedTabWidgets } = useInjectionWidgets("detail:customers.company:tabs", {
    context: injectionContext,
    triggerOnLoad: true
  });
  const injectedTabs = React.useMemo(
    () => (injectedTabWidgets ?? []).filter((widget) => (widget.placement?.kind ?? "tab") === "tab").map((widget) => {
      const tabId = widget.placement?.groupId ?? widget.widgetId;
      const label = widget.placement?.groupLabel ?? widget.module.metadata.title ?? tabId;
      const priority = typeof widget.placement?.priority === "number" ? widget.placement.priority : 0;
      const render = () => /* @__PURE__ */ jsx(
        widget.module.Widget,
        {
          context: injectionContext,
          data,
          onDataChange: (next) => setData(next)
        }
      );
      return { id: tabId, label, priority, render };
    }).sort((a, b) => b.priority - a.priority),
    [data, injectedTabWidgets, injectionContext]
  );
  const injectedTabMap = React.useMemo(() => new Map(injectedTabs.map((tab) => [tab.id, tab.render])), [injectedTabs]);
  const handleTagsChange = React.useCallback((nextTags) => {
    setData((prev) => prev ? { ...prev, tags: nextTags } : prev);
  }, []);
  const tagsSectionControllerRef = React.useRef(null);
  const handleSectionActionChange = React.useCallback((action) => {
    setSectionAction((prev) => action !== null ? action : prev);
  }, []);
  const handleSectionAction = React.useCallback(() => {
    if (!sectionAction || sectionAction.disabled) return;
    sectionAction.onClick();
  }, [sectionAction]);
  React.useEffect(() => {
    setSectionAction(null);
  }, [activeTab]);
  const dealsScope = React.useMemo(
    () => currentCompanyId ? { kind: "company", entityId: currentCompanyId } : null,
    [currentCompanyId]
  );
  const handleDelete = React.useCallback(async () => {
    const companyId2 = data?.company?.id ?? "";
    if (!companyId2) return;
    const approved = await confirm({
      title: t("customers.companies.detail.deleteConfirmTitle", "Delete company?"),
      description: t("customers.companies.detail.deleteConfirmDescription", "This action cannot be undone."),
      confirmText: t("customers.companies.detail.actions.delete", "Delete company"),
      cancelText: t("customers.companies.detail.actions.cancel", "Cancel"),
      variant: "destructive"
    });
    if (!approved) return;
    try {
      await runMutationWithContext(
        () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(data?.company?.updatedAt),
          () => deleteCrud("customers/companies", { id: companyId2 })
        ),
        { id: companyId2, operation: "deleteCompany" }
      );
    } catch (err) {
      if (!surfaceRecordConflict(err, t)) {
        flash(
          err instanceof Error && err.message.trim().length > 0 ? err.message : t("customers.companies.detail.deleteError", "Failed to delete company."),
          "error"
        );
      }
      return;
    }
    flash(t("customers.companies.list.deleteSuccess", "Company deleted."), "success");
    router.push("/backend/customers/companies");
  }, [confirm, data?.company?.id, router, runMutationWithContext, t]);
  const handleFormSubmit = React.useCallback(
    async (values) => {
      setIsSaving(true);
      try {
        let payload;
        try {
          payload = buildCompanyEditPayload(values, organizationId);
        } catch (err) {
          if (err instanceof Error) {
            if (err.message === "DISPLAY_NAME_REQUIRED") {
              const message = t("customers.companies.form.displayName.error");
              throw createCrudFormError(message, { displayName: message });
            }
            if (err.message === "ANNUAL_REVENUE_INVALID") {
              const message = t("customers.companies.form.annualRevenue.error");
              throw createCrudFormError(message, { annualRevenue: message });
            }
          }
          throw err;
        }
        await updateCrud("customers/companies", payload);
        flash(t("customers.companies.form.updateSuccess", "Company updated."), "success");
        await loadData();
      } finally {
        setIsSaving(false);
      }
    },
    [loadData, organizationId, t]
  );
  const handleHeaderSave = React.useCallback(() => {
    const form = formWrapperRef.current?.querySelector("form");
    if (form) form.requestSubmit();
  }, []);
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("customers.companies.detail.loading", "Loading company\u2026") }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("customers.companies.detail.error.notFound", "Company not found."),
        backHref: "/backend/customers/companies",
        backLabel: t("customers.companies.detail.actions.backToList", "Back to companies")
      }
    ) }) });
  }
  if (error || !data?.company?.id) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: error ?? t("customers.companies.detail.error.load", "Failed to load company."),
        action: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", children: /* @__PURE__ */ jsx(Link, { href: "/backend/customers/companies", children: t("customers.companies.detail.actions.backToList", "Back to companies") }) })
      }
    ) }) });
  }
  const companyId = data.company.id;
  const useCanonicalInteractions = data.interactionMode === "canonical";
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: "detail:customers.company:header", context: injectionContext, data }),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: "detail:customers.company:status-badges", context: injectionContext, data }),
    /* @__PURE__ */ jsx(
      CompanyDetailHeader,
      {
        data,
        onTagsChange: handleTagsChange,
        tagsSectionControllerRef,
        onSave: handleHeaderSave,
        onDelete: handleDelete,
        isDirty,
        isSaving,
        onDataReload: () => {
          loadData().catch((err) => logger.warn("onDataReload failed", { component: "companies-v2", err }));
        }
      }
    ),
    /* @__PURE__ */ jsx(CompanyKpiBar, { data }),
    /* @__PURE__ */ jsx(
      CollapsibleZoneLayout,
      {
        pageType: "company-v2",
        entityName: companyName,
        isDirty,
        sections: zoneSections,
        zone1: /* @__PURE__ */ jsx("div", { ref: formWrapperRef, children: /* @__PURE__ */ jsx(
          CrudForm,
          {
            embedded: true,
            trackDirtyWhenEmbedded: true,
            injectionSpotId: "crud-form:customers.company",
            entityIds: [E.customers.customer_entity, E.customers.customer_company_profile],
            schema: formSchema,
            fields: formFields,
            groups: formGroups,
            initialValues,
            onSubmit: handleFormSubmit,
            onDelete: handleDelete,
            optimisticLockUpdatedAt: data?.company?.updatedAt,
            hideFooterActions: true,
            collapsibleGroups: { pageType: "company-v2", chevronPosition: "right" },
            sortableGroups: { pageType: "company-v2" },
            onDirtyChange: setIsDirty
          }
        ) }),
        zone2: /* @__PURE__ */ jsxs(
          CompanyDetailTabs,
          {
            activeTab,
            onTabChange: setActiveTab,
            injectedTabs: injectedTabs.map((tab) => ({ id: tab.id, label: tab.label })),
            peopleCount: data.counts?.people ?? 0,
            dealsCount: dealCount,
            activitiesCount: data.counts?.activities ?? 0,
            sectionAction,
            children: [
              activeTab === "people" && /* @__PURE__ */ jsx(
                CompanyPeopleSection,
                {
                  companyId,
                  companyName: companyDisplayName,
                  initialPeople: [],
                  addActionLabel: t("customers.companies.detail.people.add", "Add person"),
                  emptyLabel: t("customers.companies.detail.people.empty", "No people linked to this company yet."),
                  emptyState: {
                    title: t("customers.companies.detail.emptyState.people.title", "Build the account team"),
                    actionLabel: t("customers.companies.detail.emptyState.people.action", "Create person")
                  },
                  onActionChange: handleSectionActionChange,
                  translator: detailTranslator,
                  runGuardedMutation: runMutationWithContext,
                  onPeopleChange: (next) => {
                    setData((prev) => {
                      if (!prev) return prev;
                      const nextCount = next.length;
                      return {
                        ...prev,
                        people: next,
                        counts: prev.counts ? { ...prev.counts, people: nextCount } : prev.counts
                      };
                    });
                  }
                }
              ),
              activeTab === "deals" && /* @__PURE__ */ jsx(
                DealsSection,
                {
                  scope: dealsScope,
                  emptyLabel: t("customers.companies.detail.empty.deals", "No deals linked to this company."),
                  addActionLabel: t("customers.companies.detail.actions.addDeal", "Add deal"),
                  emptyState: {
                    title: t("customers.companies.detail.emptyState.deals.title", "No deals yet"),
                    actionLabel: t("customers.companies.detail.emptyState.deals.action", "Create a deal")
                  },
                  onActionChange: handleSectionActionChange,
                  translator: detailTranslator,
                  runGuardedMutation: runMutationWithContext,
                  onCountDelta: (delta) => setDealCount((current) => Math.max(0, current + delta))
                }
              ),
              activeTab === "activity-log" && /* @__PURE__ */ jsx(
                ActivityLogTab,
                {
                  entityId: companyId,
                  plannedActivities,
                  onActivityCreated: handleActivityCreated,
                  onScheduleRequested: openNewScheduleDialog,
                  onAddActivity: handleAddActivity,
                  onMarkDone: handleMarkDone,
                  onEditActivity: handleEditActivity,
                  onCancelActivity: handleCancelActivity,
                  runGuardedMutation: runMutationWithContext,
                  refreshKey: activityRefreshKey,
                  useCanonicalInteractions
                }
              ),
              activeTab === "changelog" && companyId && /* @__PURE__ */ jsx(ChangelogTab, { entityId: companyId, entityType: "company" }),
              activeTab === "files" && /* @__PURE__ */ jsx(
                AttachmentsSection,
                {
                  entityId: E.customers.customer_entity,
                  recordId: companyId,
                  title: t("customers.companies.detail.tabs.files", "Files"),
                  description: t("customers.companies.detail.files.subtitle", "Upload and manage files linked to this company.")
                }
              ),
              injectedTabMap.has(activeTab) && injectedTabMap.get(activeTab)()
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: "detail:customers.company:footer", context: injectionContext, data }),
    /* @__PURE__ */ jsx(
      ScheduleActivityDialog,
      {
        open: scheduleDialogOpen,
        onClose: () => {
          setScheduleDialogOpen(false);
          setScheduleEditData(null);
        },
        entityId: companyId,
        entityName: companyName,
        entityType: "company",
        onActivityCreated: handleActivityCreated,
        editData: scheduleEditData
      }
    ),
    ConfirmDialogElement
  ] }) }) });
}
export {
  CompanyDetailV2Page as default
};
//# sourceMappingURL=page.js.map
