'use client';

import { useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { MERGE_DENIED_TITLE, recordRights } from '@/features/auth/record-access';
import { getCompanyHistory, updateCompany } from '@/features/companies/api.client';
import type { Company } from '@/features/companies/types';
import { TOOL_ICONS } from '@/features/contacts/ui/ContactPreviewActions';
import { MergeRecordAction } from '@/features/duplicates/ui/MergeRecordAction';
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 { useFieldAccess, VIEW_ONLY_TITLE } from '@/features/permission-sets/field-access';
import { ownerLock } from '@/features/record-tools/recordAccessView';
import { useRecordTools, type AccessDesign } from '@/features/record-tools/ui/RecordTools';
import { cn } from '@/lib/utils/cn';
import type { MeResponse } from '@/types/api';

export interface CompanyPreviewAccess {
  /** Edit rights on this company: the owner, the team or an S5 share, as the API decides. */
  canEdit: boolean;
  /** Log and restore activity (not read-only). */
  canLog: boolean;
  /** Delete: the list allows it and the set's Delete scope covers this company (P2a). */
  canDelete: boolean;
  /** Merge: the set's Merge scope covers this company (P2a); the API checks the other too. */
  canMerge: boolean;
}

/** What the preview's tools may do for this person on this company (the API checks again). */
export function companyPreviewAccess(
  me: MeResponse,
  company: Pick<Company, 'owner' | 'sharedWithMe' | 'ownerFieldMatch'>,
  canDelete: boolean,
): CompanyPreviewAccess {
  const rights = recordRights(
    me.permissionSet.rules.objects.company,
    company.owner?.id,
    me,
    company.sharedWithMe,
    company.ownerFieldMatch,
  );
  return {
    canEdit: rights.edit,
    canLog: me.role !== 'read_only',
    canDelete: canDelete && rights.delete,
    canMerge: rights.merge,
  };
}

export interface CompanyPreviewActionsArgs {
  company: Company;
  following: boolean;
  onToggleFollow: () => void;
  /** The record page ("View all properties", as the design's link). */
  href: string;
  access: CompanyPreviewAccess;
  timeZone: string;
  /** The design's Export: the list's export with this company. */
  onExport?: () => void;
  /** The design's Delete: the panel's confirm dialog. */
  onAskDelete: () => void;
  onHistory: () => void;
  onMerge: () => void;
  onClone: () => void;
  /** A tool changed the company (a restore, a new link): the panel and the list load again. */
  onChanged: () => void;
  /** G12: View record access as the design's preview (`contact-preview.js` `recordAccess`). */
  accessDesign?: AccessDesign;
}

/**
 * B4 point 41: the company preview's Actions ▾. The design's Follow, View all properties, Export
 * and Delete (list-page.js:3650-3654) keep their order, with Delete last after a separator; the
 * record page's tools go between them, as Contacts' preview (`ContactPreviewActions`). Opt out of
 * email is contacts only; Customize preview and "Export contact data" are out (gap 29).
 */
export function useCompanyPreviewActions({
  company,
  following,
  onToggleFollow,
  href,
  access,
  timeZone,
  onExport,
  onAskDelete,
  onHistory,
  onMerge,
  onClone,
  onChanged,
  accessDesign,
}: CompanyPreviewActionsArgs): { items: LpMenuItem[]; drawers: ReactNode } {
  const tools = useRecordTools({
    recordType: 'company',
    recordId: company.id,
    name: company.name,
    searchText: [company.name, company.domain].filter(Boolean).join(' '),
    canEdit: access.canEdit,
    canLog: access.canLog,
    timeZone,
    // "View all properties" is the design's link to the record page, not the tools' drawer.
    properties: () => [],
    onChanged,
    onClone,
    icon: () => null,
    accessDesign,
  });
  /** 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: onHistory },
    { sep: true },
    ...tool('association-history'),
    ...tool('review-associations'),
    { sep: true },
    ...tool('google', 'external'),
    { sep: true },
    ...tool('restore-activity'),
    ...tool('record-access'),
    {
      key: 'merge',
      label: 'Merge',
      icon: 'share',
      onSelect: onMerge,
      disabled: !access.canMerge,
      title: access.canMerge ? undefined : MERGE_DENIED_TITLE,
    },
    ...tool('clone'),
    ...(onExport
      ? [{ key: 'export', label: 'Export', icon: 'download' as const, onSelect: onExport }]
      : []),
    ...(access.canDelete
      ? [
          { sep: true as const },
          {
            key: 'delete',
            label: 'Delete',
            icon: 'trash' as const,
            danger: true,
            onSelect: onAskDelete,
          },
        ]
      : []),
  ];
  return { items, drawers: tools.drawers };
}

/** The Actions ▾ button, its menu and the drawers its tools open (to the body, over the panel). */
export function CompanyPreviewActions({
  describeHistory,
  canManageProperties = false,
  ...args
}: Omit<CompanyPreviewActionsArgs, 'onHistory' | 'onMerge'> & {
  /** Field labels and value texts for the property history (`companyHistoryDescriber`). */
  describeHistory: DescribeField;
  /** PH1: may open Settings › Properties (P1 `canOpenPropertySettings`), for the history's Manage properties. */
  canManageProperties?: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [historyOpen, setHistoryOpen] = useState(false);
  const [mergeOpen, setMergeOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const fieldAccess = useFieldAccess('company');
  const { company: current } = args;
  const { items, drawers } = useCompanyPreviewActions({
    ...args,
    accessDesign: {
      variant: 'preview',
      one: 'company',
      ownerLabel: 'Company owner',
      owner: current.owner ? { id: current.owner.id, name: current.owner.name } : null,
      ...ownerLock({
        canEdit: args.access.canEdit,
        deletedTitle: null,
        viewOnlyTitle: fieldAccess.locked('ownerId') ? VIEW_ONLY_TITLE : null,
      }),
      saveOwner: async (ownerId) => {
        await updateCompany(current.id, { ownerId, updatedAt: current.updatedAt });
        args.onChanged();
      },
      loadHistory: (params) => getCompanyHistory(current.id, params),
      describe: describeHistory,
      reloadKey: current.updatedAt,
    },
    onHistory: () => setHistoryOpen(true),
    onMerge: () => setMergeOpen(true),
  });
  const { company } = args;
  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}
        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(
        <>
          {drawers}
          <PropertyHistoryDrawer
            open={historyOpen}
            onClose={() => setHistoryOpen(false)}
            load={(params) => getCompanyHistory(company.id, params)}
            describe={describeHistory}
            reloadKey={company.updatedAt}
            timeZone={args.timeZone}
            design={{ recordName: company.name, objectType: 'company', canManageProperties }}
          />
          <MergeRecordAction
            open={mergeOpen}
            objectType="company"
            record={{ id: company.id, label: company.name, secondary: company.domain }}
            onClose={() => setMergeOpen(false)}
            timeZone={args.timeZone}
          />
        </>,
        document.body,
      )}
    </>
  );
}
