'use client';

import { useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { MERGE_DENIED_TITLE } from '@/features/auth/record-access';
import { MergeDesignDialog } from '@/features/duplicates/design/MergeDesignDialog';
import { getContactHistory, updateContact } from '@/features/contacts/api.client';
import { useFieldAccess, VIEW_ONLY_TITLE } from '@/features/permission-sets/field-access';
import { ownerLock } from '@/features/record-tools/recordAccessView';
import { useObjectNames } from '@/features/objects/useObjectNames';
import type { Contact } from '@/features/contacts/types';
import { LpIcon, type LpIconName } from '@/features/list-page/ui/LpIcon';
import { LpMenu, LpPopover, type LpMenuItem } from '@/features/list-page/ui/LpPopover';
import type { DescribeField } from '@/features/property-history/describe';
import { PropertyHistoryDrawer } from '@/features/property-history/PropertyHistoryDrawer';
import { useRecordTools } from '@/features/record-tools/ui/RecordTools';
import { cn } from '@/lib/utils/cn';

/** The record tools' icons in a preview's Actions menu (Contacts and, since B4, Companies). */
export const TOOL_ICONS: Record<string, LpIconName> = {
  'association-history': 'assoc',
  'review-associations': 'link',
  google: 'search',
  'opt-out': 'email',
  'restore-activity': 'undo',
  'record-access': 'lock',
  clone: 'copy',
};

/**
 * The preview's Actions ▾ (design contact-preview.js `actionsMenu`): the list preview's Follow,
 * View all properties, Export and Delete, with the record page's tools and their drawers between
 * them. The drawers go to the body so the panel's header styles don't reach them.
 */
export function ContactPreviewActions({
  contactId,
  contact,
  name,
  following,
  onToggleFollow,
  href,
  canEdit,
  canDelete,
  canMerge,
  canLog,
  timeZone,
  describeHistory,
  canManageProperties = false,
  onExport,
  onDelete,
  onClone,
  onChanged,
}: {
  contactId: string;
  /** Null until it has loaded (the button is off until then). */
  contact: Contact | null;
  name: string;
  following: boolean;
  onToggleFollow: () => void;
  /** The record page. */
  href: string;
  canEdit: boolean;
  canDelete: boolean;
  /** P2a: the set's Merge scope covers this contact (`recordRights`). */
  canMerge: boolean;
  canLog: boolean;
  timeZone: string;
  describeHistory: DescribeField;
  /** PH1: may open Settings › Properties (P1 `canOpenPropertySettings`), for the history's Manage properties. */
  canManageProperties?: boolean;
  onExport?: () => void;
  onDelete: () => void;
  onClone: () => void;
  /** After a restore, an opt-out or a new link. */
  onChanged: () => void;
}) {
  const [open, setOpen] = useState(false);
  const [historyOpen, setHistoryOpen] = useState(false);
  const [mergeOpen, setMergeOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const fieldAccess = useFieldAccess('contact');
  const names = useObjectNames('contact');
  const primary = contact?.companies.find((c) => c.isPrimary);
  const tools = useRecordTools({
    recordType: 'contact',
    recordId: contactId,
    name,
    email: contact?.email,
    searchText: [name, primary?.name].filter(Boolean).join(' '),
    canEdit,
    canLog,
    timeZone,
    properties: () => [],
    onChanged,
    onClone,
    icon: () => null,
    // G12: View record access as the design's preview (`contact-preview.js` `recordAccess`).
    accessDesign: {
      variant: 'preview',
      // The business's name for contacts ("Clients"), as the record page.
      one: names.singular.toLowerCase(),
      ownerLabel: `${names.singular} owner`,
      owner: contact?.owner ? { id: contact.owner.id, name: contact.owner.name } : null,
      ...ownerLock({
        canEdit: canEdit && contact !== null,
        deletedTitle: null,
        viewOnlyTitle: fieldAccess.locked('ownerId') ? VIEW_ONLY_TITLE : null,
      }),
      saveOwner: async (ownerId) => {
        if (!contact) return;
        await updateContact(contactId, { ownerId, updatedAt: contact.updatedAt });
        onChanged();
      },
      loadHistory: (params) => getContactHistory(contactId, params),
      describe: describeHistory,
      reloadKey: contact?.updatedAt,
    },
  });
  /** The tools' own items, as this menu draws them. */
  const tool = (key: string, iconAfter?: LpIconName): LpMenuItem[] =>
    tools.actions
      .filter((a) => a.key === key)
      .map((a) => ({
        key: a.key,
        label: a.label,
        icon: TOOL_ICONS[a.key],
        iconAfter,
        onSelect: a.onSelect,
        disabled: a.disabled,
        title: a.title,
      }));

  const items: LpMenuItem[] = [
    {
      key: 'follow',
      label: following ? 'Unfollow' : 'Follow',
      icon: 'eye',
      onSelect: onToggleFollow,
    },
    { sep: true },
    { key: 'all', label: 'View all properties', icon: 'columns', href },
    {
      key: 'history',
      label: 'View property history',
      icon: 'clock',
      onSelect: () => setHistoryOpen(true),
    },
    { sep: true },
    ...tool('association-history'),
    ...tool('review-associations'),
    { sep: true },
    ...tool('google', 'external'),
    ...tool('opt-out'),
    { sep: true },
    ...tool('restore-activity'),
    ...tool('record-access'),
    {
      key: 'merge',
      label: 'Merge',
      icon: 'share',
      onSelect: () => setMergeOpen(true),
      disabled: !canMerge,
      title: canMerge ? undefined : MERGE_DENIED_TITLE,
    },
    ...tool('clone'),
    ...(onExport
      ? [{ key: 'export', label: 'Export', icon: 'download' as const, onSelect: onExport }]
      : []),
    ...(canDelete
      ? [
          { sep: true as const },
          {
            key: 'delete',
            label: 'Delete',
            icon: 'trash' as const,
            danger: true,
            onSelect: onDelete,
          },
        ]
      : []),
  ];

  return (
    <>
      <button
        ref={buttonRef}
        type="button"
        className={cn('lp-btn lp-btn--outline lp-btn--sm', open && 'is-open')}
        aria-haspopup="menu"
        aria-expanded={open}
        disabled={!contact}
        onClick={() => setOpen((v) => !v)}
      >
        Actions
        <LpIcon name="caret" />
      </button>
      <LpPopover
        pop="menu"
        open={open}
        anchorRef={buttonRef}
        onClose={() => setOpen(false)}
        label="Actions"
        className="lp-pop--menu"
        align="end"
      >
        <LpMenu label="Actions" onClose={() => setOpen(false)} items={items} />
      </LpPopover>
      {createPortal(
        <>
          {tools.drawers}
          <PropertyHistoryDrawer
            open={historyOpen}
            onClose={() => setHistoryOpen(false)}
            load={(params) => getContactHistory(contactId, params)}
            describe={describeHistory}
            reloadKey={contact?.updatedAt}
            timeZone={timeZone}
            design={{ recordName: name, objectType: 'contact', canManageProperties }}
          />
          {contact ? (
            <MergeDesignDialog
              open={mergeOpen}
              objectType="contact"
              record={{ id: contact.id, label: name, secondary: contact.email }}
              onClose={() => setMergeOpen(false)}
              timeZone={timeZone}
            />
          ) : null}
        </>,
        document.body,
      )}
    </>
  );
}
