"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { Phone, Mail, Building2, Trash2, Pencil } from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Avatar } from "@open-mercato/ui/primitives/avatar";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
import { useQueryClient } from "@tanstack/react-query";
import { ObjectHistoryButton } from "./ObjectHistoryButton.js";
import { PersonTagsDialog } from "./PersonTagsDialog.js";
import { useCustomerDictionary, invalidateCustomerDictionary } from "./hooks/useCustomerDictionary.js";
import { renderDictionaryIcon } from "../../../dictionaries/components/dictionaryAppearance.js";
import { formatFallbackLabel } from "./utils.js";
const HEADER_ICON_BUTTON_CLASS = "size-8 rounded-md";
function DictionaryBadge({ value, map, categoryIcon, className }) {
  const entry = map?.[value];
  const color = entry?.color ?? null;
  const icon = entry?.icon ?? null;
  const label = entry?.label ?? formatFallbackLabel(value);
  const colorStyle = color ? { color, borderColor: color, backgroundColor: `${color}1A` } : void 0;
  return /* @__PURE__ */ jsxs(
    Badge,
    {
      variant: "outline",
      className: cn(
        "rounded-sm gap-1.5 text-xs font-medium",
        className
      ),
      style: colorStyle,
      children: [
        icon ? renderDictionaryIcon(icon, "size-2.5") : categoryIcon ?? null,
        label
      ]
    }
  );
}
function TagBadge({ tag }) {
  const colorStyle = tag.color ? { color: tag.color, borderColor: tag.color, backgroundColor: `${tag.color}1A` } : void 0;
  return /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "rounded-sm gap-1.5 text-xs font-medium", style: colorStyle, children: tag.label });
}
function PersonDetailHeader({
  data,
  onTagsChange,
  tagsSectionControllerRef,
  onSave,
  onDelete,
  isDirty,
  isSaving,
  onFocusField,
  onOpenCompaniesTab,
  onDataReload
}) {
  const t = useT();
  const queryClient = useQueryClient();
  const [manageTagsOpen, setManageTagsOpen] = React.useState(false);
  const person = data.person;
  const profile = data.profile;
  const displayName = person.displayName || t("customers.people.detail.untitled", "Untitled");
  const jobTitle = profile?.jobTitle ?? null;
  const linkedCompanies = React.useMemo(() => {
    const items = Array.isArray(data.companies) && data.companies.length > 0 ? data.companies : data.company ? [{ ...data.company, isPrimary: Boolean(data.isPrimary) }] : [];
    return items;
  }, [data.companies, data.company, data.isPrimary]);
  const visibleCompanies = React.useMemo(() => linkedCompanies.slice(0, 3), [linkedCompanies]);
  const hiddenCompaniesCount = Math.max(0, linkedCompanies.length - visibleCompanies.length);
  const visibleTags = React.useMemo(() => data.tags.slice(0, 6), [data.tags]);
  const hiddenTagsCount = Math.max(0, data.tags.length - visibleTags.length);
  const primaryCompany = linkedCompanies.find((entry) => entry.isPrimary) ?? linkedCompanies[0] ?? null;
  const companyName = primaryCompany?.displayName ?? null;
  const companyId = primaryCompany?.id ?? profile?.companyEntityId ?? null;
  const personOrgId = person.organizationId ?? null;
  const { data: statusDict } = useCustomerDictionary("statuses", 0, personOrgId);
  const { data: lifecycleDict } = useCustomerDictionary("lifecycle-stages", 0, personOrgId);
  const { data: sourceDict } = useCustomerDictionary("sources", 0, personOrgId);
  const { data: temperatureDict } = useCustomerDictionary("temperature", 0, personOrgId);
  const { data: renewalQuarterDict } = useCustomerDictionary("renewal-quarters", 0, personOrgId);
  return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card px-6 py-5", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 sm:flex-row sm:items-start sm:gap-5", children: [
      /* @__PURE__ */ jsx(Avatar, { label: displayName, size: "xl", variant: "monochrome" }),
      /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx("h1", { className: "truncate text-2xl font-bold text-foreground", children: displayName }),
          data.isPrimary && /* @__PURE__ */ jsx("span", { className: "shrink-0 rounded-sm bg-status-warning-bg px-1.5 py-0.5 text-overline font-bold text-status-warning-text", children: t("customers.people.detail.header.primary", "PRIMARY") })
        ] }),
        (jobTitle || companyName) && /* @__PURE__ */ jsxs("p", { className: "mt-0.5 text-sm text-muted-foreground", children: [
          jobTitle,
          jobTitle && companyName && ` ${t("customers.people.detail.header.at", "at")} `,
          companyName && companyId && /* @__PURE__ */ jsx(Link, { href: `/backend/customers/companies-v2/${companyId}`, className: "text-primary hover:underline", children: companyName }),
          companyName && !companyId && companyName
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "mt-1.5 flex flex-wrap items-center gap-x-5 gap-y-1 text-sm text-muted-foreground", children: [
          person.primaryPhone && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsx(Phone, { className: "size-3.5" }),
            /* @__PURE__ */ jsx("a", { href: `tel:${person.primaryPhone}`, className: "hover:text-foreground", children: person.primaryPhone })
          ] }),
          person.primaryEmail && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsx(Mail, { className: "size-3.5" }),
            /* @__PURE__ */ jsx("a", { href: `mailto:${person.primaryEmail}`, className: "hover:text-foreground", children: person.primaryEmail })
          ] })
        ] }),
        linkedCompanies.length > 0 && /* @__PURE__ */ jsxs("div", { className: "mt-1.5 flex flex-wrap items-center gap-2 text-sm", children: [
          /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
            /* @__PURE__ */ jsx(Building2, { className: "mr-1 inline size-3.5" }),
            t("customers.people.detail.header.companies", "Companies"),
            " (",
            linkedCompanies.length,
            "):"
          ] }),
          visibleCompanies.map((company) => /* @__PURE__ */ jsxs(
            Link,
            {
              href: `/backend/customers/companies-v2/${company.id}`,
              className: cn(
                "inline-flex items-center gap-1.5 rounded-sm border px-2 py-0.5 text-xs font-semibold transition-colors hover:bg-status-info-bg",
                company.isPrimary ? "border-status-info-border bg-status-info-bg text-status-info-text" : "border-border bg-background text-foreground"
              ),
              children: [
                /* @__PURE__ */ jsx(Building2, { className: "size-3" }),
                company.displayName,
                company.isPrimary ? /* @__PURE__ */ jsx("span", { className: "rounded-sm bg-status-info-icon px-1 py-px text-overline font-bold text-white", children: t("customers.people.detail.header.primary", "PRIMARY") }) : null
              ]
            },
            company.id
          )),
          hiddenCompaniesCount > 0 ? /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "rounded-sm text-xs font-semibold", children: [
            "+",
            hiddenCompaniesCount,
            " ",
            t("customers.people.detail.header.more", "more")
          ] }) : null
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "mt-2.5 flex flex-wrap items-center gap-2", children: [
          person.status && /* @__PURE__ */ jsx(DictionaryBadge, { value: person.status, map: statusDict?.map }),
          person.lifecycleStage && /* @__PURE__ */ jsx(DictionaryBadge, { value: person.lifecycleStage, map: lifecycleDict?.map }),
          person.source && /* @__PURE__ */ jsx(DictionaryBadge, { value: person.source, map: sourceDict?.map }),
          person.temperature && /* @__PURE__ */ jsx(DictionaryBadge, { value: person.temperature, map: temperatureDict?.map }),
          person.renewalQuarter && /* @__PURE__ */ jsx(DictionaryBadge, { value: person.renewalQuarter, map: renewalQuarterDict?.map }),
          visibleTags.map((tag) => /* @__PURE__ */ jsx(TagBadge, { tag }, tag.id ?? tag.label)),
          hiddenTagsCount > 0 ? /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "rounded-sm gap-1.5 text-xs font-medium", children: [
            "+",
            hiddenTagsCount,
            " ",
            t("customers.people.detail.header.more", "more")
          ] }) : null,
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              className: "h-auto rounded-sm px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground",
              onClick: () => setManageTagsOpen(true),
              children: [
                /* @__PURE__ */ jsx(Pencil, { className: "mr-1 size-3" }),
                t("customers.people.detail.actions.manageTags", "Edit tags")
              ]
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex w-full shrink-0 items-center justify-start gap-2 sm:w-auto sm:justify-end", children: [
        /* @__PURE__ */ jsx(
          SendObjectMessageDialog,
          {
            object: {
              entityModule: "customers",
              entityType: "person",
              entityId: person.id,
              previewData: {
                title: displayName,
                subtitle: person.primaryEmail ?? companyName ?? void 0
              }
            },
            viewHref: `/backend/customers/people-v2/${person.id}`,
            buttonVariant: "outline",
            buttonSize: "icon",
            buttonClassName: HEADER_ICON_BUTTON_CLASS,
            buttonLabel: t("customers.people.detail.actions.sendMessage", "Send message")
          }
        ),
        /* @__PURE__ */ jsx(
          ObjectHistoryButton,
          {
            resourceKind: "customers.person",
            resourceId: person.id,
            organizationId: person.organizationId ?? void 0
          }
        ),
        /* @__PURE__ */ jsx(
          IconButton,
          {
            variant: "outline",
            size: "sm",
            type: "button",
            "aria-label": t("customers.people.detail.actions.delete", "Delete"),
            onClick: () => {
              void onDelete();
            },
            children: /* @__PURE__ */ jsx(Trash2, { className: "size-4" })
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            size: "sm",
            onClick: onSave,
            disabled: !isDirty || isSaving,
            children: t("customers.people.detail.actions.save", "Save")
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      PersonTagsDialog,
      {
        open: manageTagsOpen,
        onClose: () => setManageTagsOpen(false),
        personId: person.id,
        personOrganizationId: person.organizationId ?? null,
        personData: {
          status: person.status,
          lifecycleStage: person.lifecycleStage,
          source: person.source,
          temperature: person.temperature,
          renewalQuarter: person.renewalQuarter,
          jobTitle: data.profile?.jobTitle ?? null,
          customFields: data.customFields,
          tags: data.tags
        },
        onSaved: () => {
          void invalidateCustomerDictionary(queryClient, "statuses");
          void invalidateCustomerDictionary(queryClient, "lifecycle-stages");
          void invalidateCustomerDictionary(queryClient, "sources");
          void invalidateCustomerDictionary(queryClient, "temperature");
          void invalidateCustomerDictionary(queryClient, "renewal-quarters");
          onDataReload?.();
        }
      }
    )
  ] });
}
export {
  PersonDetailHeader
};
//# sourceMappingURL=PersonDetailHeader.js.map
