'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { cn } from '@/lib/utils/cn';
import {
  associationsOf,
  byText,
  canRename,
  DM_GROUPS,
  fieldTypeLabel,
  fmt,
  liveProperties,
  usedIn,
  type DmObject,
  propertyAssetCount,
  typeIdOrder,
} from '../model';
import { listPropertyUsage } from '../api.client';
import { ActivateObjectButton, activateKind } from './ActivateObjectButton';
import { useDm } from './DataModelView';
import { exportDataModelImage } from './export-image';
import { DmIcon, TypeIcon } from './icons';
import { ExportPropertiesModal } from './ExportPropertiesModal';
import { ColumnChooser } from '@/features/list-page/ui/ColumnChooser';
import {
  MANAGE_SET,
  MAX_FROZEN,
  orderColumns,
  readColumnPrefs,
  saveColumnPrefs,
  type ColumnPrefs,
} from '../manageColumns';
import { ObjectDetail } from './ObjectDetail';
import {
  ActionMenu,
  Canvas,
  CheckFilter,
  DataTable,
  SearchBox,
  SelectMenu,
  Tip,
  ViewToggle,
  type Column,
  type MenuItem,
} from './primitives';
import { nameInText } from '@/features/objects/paths';
import { lockItem, lockProps } from './viewOnly';

type Status = 'activated' | 'deactivated';

export function useCopy() {
  const toast = useToast();
  return (text: string) => {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(text).then(
        () => toast(`Copied ${text}`, 'success'),
        () => toast('Copy failed', 'danger'),
      );
    } else toast(text, 'info');
  };
}

/** Why "Edit object name" is off for activities and standard objects (fixed names). */
export const FIXED_NAME_HINT = "This object's name can't be changed";

/**
 * Objects whose Edit object panel can be opened: the renamable ones (custom objects, and
 * Contacts, Companies and Deals) and CRM-defined objects not switched on yet (read-only there).
 */
const hasEditPanel = (o: DmObject) => canRename(o) || o.deactivated;

/** "Edit object name" (HUB-603); off, saying why, for objects whose names are fixed. */
function useRenameItem() {
  const { renameObject, canEdit } = useDm();
  return (o: DmObject): MenuItem[] => [
    hasEditPanel(o)
      ? lockItem(
          { label: 'Edit object name', icon: 'pencil', onClick: () => renameObject(o.key) },
          canEdit,
        )
      : { label: 'Edit object name', icon: 'pencil', disabled: true, title: FIXED_NAME_HINT },
  ];
}

/** Switches a switched-off object on: the row menu, the table row button and the graph card. */
function useActivate() {
  const { setArchived, createObject } = useDm();
  return (o: DmObject) =>
    activateKind(o) === 'create' ? createObject(o.key) : setArchived(o.key, false);
}

/** Objects with a "Create <object>" form to customize (the design's CORE_CREATE). */
const CREATE_FORM_OBJECTS = new Set(['contact', 'company', 'deal', 'ticket']);

/**
 * The menu of an object row (rowMenu) or, with `card`, of a graph card (its first five items),
 * in the design's order.
 */
export function useObjectMenu() {
  const { href, openProperty, openUsage, setArchived, canEdit } = useDm();
  /** A write, or a link to an admin-only Settings page: off for a view-only user. */
  const lock = (item: MenuItem) => lockItem(item, canEdit);
  const router = useRouter();
  const renameItem = useRenameItem();
  const activate = useActivate();
  return (o: DmObject, { card = false }: { card?: boolean } = {}): MenuItem[] => {
    const viewProps: MenuItem = {
      label: 'View all properties',
      icon: 'list',
      onClick: () => router.push(href({ tab: 'manage', object: o.key, sub: 'properties' })),
    };
    const viewAssoc: MenuItem = {
      label: 'View all associated objects',
      icon: 'assoc',
      onClick: () =>
        router.push(href({ tab: 'manage', object: o.key, sub: 'associations', view: 'graph' })),
    };
    // A switched-off CRM-defined object is switched on from the Create object panel (HUB-605);
    // a deactivated (archived) custom object is restored.
    if (!o.active) {
      const off = `Activate ${o.name} to see them`;
      return [
        { ...viewProps, onClick: undefined, disabled: true, title: off },
        { ...viewAssoc, onClick: undefined, disabled: true, title: off },
        ...renameItem(o),
        { divider: true },
        lock({
          label: 'Activate object',
          icon: 'circle',
          onClick: () => activate(o),
        }),
      ];
    }
    const first: MenuItem[] = [
      lock({
        label: 'Create property',
        icon: 'plus',
        onClick: () => openProperty(o.key, null, 'create'),
        disabled: o.catalog,
      }),
      viewProps,
      viewAssoc,
      ...renameItem(o),
      { label: 'View object usage', icon: 'usage', onClick: () => openUsage(o.key) },
    ];
    if (card) return first;
    // HUB-609: activities have their records page and the logging defaults, never a record view.
    if (o.activity) {
      return [
        ...first,
        { divider: true },
        { label: 'View records', icon: 'external', href: o.page, disabled: !o.page },
        lock({
          label: 'Configure defaults for logging activities',
          icon: 'external',
          href: `/settings/objects?object=activities&tab=associations&type=${encodeURIComponent(o.key)}`,
        }),
      ];
    }
    const settings = `/settings/objects?object=${encodeURIComponent(o.key)}`;
    const deactivatable = Boolean(o.definition) || Boolean(o.deactivatable);
    return [
      ...first,
      { divider: true },
      // Only custom objects can be switched off; core objects stay on.
      deactivatable
        ? lock({
            label: 'Deactivate object',
            icon: 'circle',
            onClick: () => setArchived(o.key, true),
          })
        : {
            label: 'Deactivate object',
            icon: 'circle',
            disabled: true,
            title: `${o.name} can't be deactivated`,
          },
      { divider: true },
      ...(CREATE_FORM_OBJECTS.has(o.key)
        ? [
            lock({
              label: `Customize the 'create ${nameInText(o.singular)}' form`,
              icon: 'external',
              href: `${settings}&tab=setup#create-form`,
            }),
          ]
        : []),
      lock({
        label: 'Customize the record view',
        icon: 'external',
        href: `${settings}&tab=record`,
        disabled: o.catalog,
      }),
    ];
  };
}

/** Manage: every object as a table or a graph, or one object (?object=). */
export function ManageTab() {
  const dm = useDm();
  const { model, params, href, builder, createObject } = dm;
  const router = useRouter();
  const copy = useCopy();
  const menu = useObjectMenu();
  const activate = useActivate();
  const objectKey = params.get('object');
  const [view, setView] = useState<'graph' | 'table'>(
    params.get('view') === 'graph' ? 'graph' : 'table',
  );
  const [search, setSearch] = useState('');
  const [chosen, setChosen] = useState<string[] | null>(null);
  const [status, setStatus] = useState<Status[]>(['activated', 'deactivated']);
  const [exporting, setExporting] = useState(false);
  // #757 / DMG3: the columns this viewer chose, in order (kept in the browser); read after mount,
  // as the server has none.
  const [columns, setColumns] = useState<ColumnPrefs>({ ids: MANAGE_SET.defaults, frozen: 0 });
  const [editingColumns, setEditingColumns] = useState(false);
  useEffect(() => setColumns(readColumnPrefs(MANAGE_SET)), []);
  const shownColumns = (cols: Array<Column<DmObject>>) => orderColumns(cols, columns.ids);
  const toast = useToast();

  // A deactivated object has no page (its fields are hidden while it is off), as in HubSpot:
  // deactivating the open object, or a link to one, lands on All objects.
  const offObject = objectKey ? dm.object(objectKey) : undefined;
  useEffect(() => {
    if (offObject && !offObject.active)
      router.replace(href({ tab: builder ? 'builder' : 'manage' }));
  }, [offObject, router, href, builder]);

  const allKeys = model.objects.map((o) => o.key);
  const selected = chosen ?? allKeys;
  // A switched-off CRM-defined object has no associations yet; a deactivated custom object keeps
  // its own.
  const offAssociations = (o: DmObject) =>
    o.active ? null : o.deactivated ? 0 : associationsOf(model, o.key).length;

  const rows = useMemo(() => {
    const q = search.trim().toLowerCase();
    return model.objects.filter((o) => {
      if (!selected.includes(o.key)) return false;
      if (status.length === 1 && (status[0] === 'activated') !== o.active) return false;
      return !q || o.name.toLowerCase().includes(q);
    });
  }, [model.objects, selected, status, search]);

  const shownObject = objectKey ? dm.object(objectKey) : undefined;
  if (shownObject?.active) return <ObjectDetail object={shownObject} />;

  const switchView = (v: 'graph' | 'table') => {
    setView(v);
    router.replace(builder ? href({ tab: 'builder', view: v }) : href({ tab: 'manage', view: v }));
  };

  /** HUB-602: the graph view's visible objects (search and filters applied) as a PNG. */
  const exportImage = async () => {
    try {
      await exportDataModelImage(model, rows);
      toast('Data model image exported', 'success');
    } catch {
      toast("The image couldn't be created", 'danger');
    }
  };

  const objectOptions = DM_GROUPS.flatMap((g) =>
    model.objects
      .filter((o) => o.group === g)
      .sort((a, b) => byText(a.name, b.name))
      .map((o) => ({ value: o.key, label: o.name, group: g })),
  );

  return (
    <>
      {/* DMG3 (B5): the design's two rows, search and actions above the filters
          (data-model.js:2576-2587). */}
      <div className="dm-toolbar dm-toolbar--rows">
        <div className="dm-toolbar__top">
          <ViewToggle view={view} onChange={switchView} />
          <SearchBox value={search} onChange={setSearch} placeholder="Search for an object" />
          <span className="dm-grow" />
          <button
            type="button"
            className="dm-btn dm-btn--primary dm-btn--sm"
            data-tour="create-object"
            onClick={() => createObject()}
            {...lockProps(dm.canEdit)}
          >
            <DmIcon name="plus" size={14} />
            Create object
          </button>
          {/* DMG3 (B3, user's call): the design's Edit columns button, table view only
              (data-model.js:2583, 2707-2708), in place of #757's gear. */}
          {view === 'table' && (
            <button
              type="button"
              className="dm-btn dm-btn--outline dm-btn--sm"
              onClick={() => setEditingColumns(true)}
            >
              <DmIcon name="columns" size={14} />
              Edit columns
            </button>
          )}
          <ActionMenu
            label={
              <>
                More
                <DmIcon name="chevron-down" size={14} />
              </>
            }
            btnClass="dm-btn dm-btn--outline dm-btn--sm"
            right
            items={[
              { label: 'Export properties', icon: 'cloud', onClick: () => setExporting(true) },
              {
                label: 'Export data model as an image',
                icon: 'image',
                onClick: () => void exportImage(),
                disabled: view === 'table',
              },
            ]}
          />
        </div>
        <div className="dm-toolbar__filters">
          <CheckFilter
            label={
              selected.length === allKeys.length
                ? 'Viewing all objects'
                : `Viewing ${selected.length} object${selected.length === 1 ? '' : 's'}`
            }
            options={objectOptions}
            selected={selected}
            onChange={setChosen}
            selectAll
            wide
          />
          <CheckFilter
            label={status.length ? `(${status.length}) Object status` : 'Object status'}
            options={[
              { value: 'activated', label: 'Activated objects' },
              { value: 'deactivated', label: 'Deactivated objects' },
            ]}
            selected={status}
            onChange={(v) => setStatus(v as Status[])}
            clear
            chip
            className="dm-tour-status"
          />
        </div>
      </div>
      {/* DMG3 (B4): the design's "Choose which columns you see" (data-model.js:2712-2742,
          3072-3257), the same dialog as the record lists. */}
      <ColumnChooser
        open={editingColumns}
        columns={MANAGE_SET.columns}
        selected={columns.ids}
        lockedId={MANAGE_SET.locked}
        frozen={columns.frozen}
        maxFrozen={MAX_FROZEN}
        createHref={null}
        okLabel="Save"
        onClose={() => setEditingColumns(false)}
        onApply={(ids, frozen) => {
          const next = { ids, frozen };
          setColumns(next);
          saveColumnPrefs(MANAGE_SET, next);
          toast('Columns updated', 'success');
        }}
      />

      {view === 'table' ? (
        <DataTable
          rows={rows}
          rowKey={(o) => o.key}
          sortKey="name"
          frozen={columns.frozen}
          rowCls={(o) => (o.active ? undefined : 'is-inactive')}
          empty="No objects match your filters."
          cols={shownColumns([
            {
              key: 'name',
              label: 'Name',
              sort: true,
              width: '34%',
              render: (o) => (
                <div className="dm-obj dm-obj--row">
                  <span className="dm-obj__icon">
                    <DmIcon name={o.active ? o.icon : 'circle'} size={o.active ? 16 : 12} />
                  </span>
                  <div className="dm-obj__text">
                    {/* As in the design and HubSpot, the name opens the object's properties. */}
                    {o.active ? (
                      <Link
                        className="dm-link-strong"
                        href={href({ tab: 'manage', object: o.key, sub: 'properties' })}
                      >
                        {o.name}
                      </Link>
                    ) : (
                      <span className="dm-name-off">{o.name}</span>
                    )}
                    {o.desc && (
                      <span className="dm-obj__desc" title={o.desc}>
                        {o.desc}
                      </span>
                    )}
                  </div>
                  {/* #563: inline, as in HubSpot; outside the row tools, which show on hover. */}
                  <ActivateObjectButton
                    object={o}
                    onActivate={() => activate(o)}
                    canEdit={dm.canEdit}
                  />
                  <span className="dm-rowtools">
                    {hasEditPanel(o) && (
                      <button
                        type="button"
                        className="dm-icon-btn dm-icon-btn--xs"
                        aria-label={`Edit ${o.name} name`}
                        title="Edit object name"
                        onClick={() => dm.renameObject(o.key)}
                        {...lockProps(dm.canEdit)}
                      >
                        <DmIcon name="pencil" size={13} />
                      </button>
                    )}
                    <ActionMenu
                      label={
                        <>
                          <DmIcon name="more-vertical" size={14} />
                          <span className="crm-visually-hidden">Actions for {o.name}</span>
                        </>
                      }
                      btnClass="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring"
                      items={menu(o)}
                    />
                  </span>
                </div>
              ),
            },
            { key: 'group', label: 'Group', sort: true },
            {
              key: 'records',
              label: 'Records',
              val: (o) => o.records ?? -1,
              render: (o) =>
                o.records === null ? (
                  <span className="dm-muted">--</span>
                ) : o.records > 0 && !o.page ? (
                  fmt(o.records)
                ) : o.records > 0 ? (
                  <Link
                    className="dm-num-link"
                    href={o.page}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    {fmt(o.records)}
                    <DmIcon name="external" size={14} />
                  </Link>
                ) : (
                  '0'
                ),
            },
            {
              key: 'props',
              label: 'Properties',
              val: (o) =>
                o.active ? liveProperties(model, o.key).length : (o.offProperties ?? -1),
              render: (o) => {
                const n = liveProperties(model, o.key).length;
                return o.active ? (
                  <Link
                    className="dm-num-link"
                    data-tour="properties"
                    href={href({ tab: 'manage', object: o.key, sub: 'properties' })}
                  >
                    {n}
                  </Link>
                ) : (
                  <span className="dm-muted">{o.offProperties ?? '--'}</span>
                );
              },
            },
            {
              key: 'assoc',
              label: 'Associated Objects',
              val: (o) => offAssociations(o) ?? associationsOf(model, o.key).length,
              render: (o) =>
                o.active ? (
                  <Link
                    className="dm-num-link"
                    data-tour="associations"
                    href={href({
                      tab: 'manage',
                      object: o.key,
                      sub: 'associations',
                      view: 'table',
                    })}
                  >
                    {associationsOf(model, o.key).length}
                  </Link>
                ) : (
                  <span className="dm-muted">{offAssociations(o)}</span>
                ),
            },
            {
              // HUB-601: assets using the object; opens the usage drawer that lists them.
              key: 'used',
              label: 'Used In',
              val: (o) => usedIn(model, o) ?? -1,
              render: (o) => {
                const n = usedIn(model, o);
                if (n === null) return <span className="dm-muted">{o.active ? '--' : 'N/A'}</span>;
                return (
                  <button type="button" className="dm-num-link" onClick={() => dm.openUsage(o.key)}>
                    {fmt(n)}
                  </button>
                );
              },
            },
            {
              key: 'typeId',
              label: 'Object Type ID',
              sort: true,
              // #756: by number (0-1, 0-2 … 0-14, then 2-…), as HubSpot sorts.
              val: (o) => typeIdOrder(o.typeId),
              render: (o) => (
                <span className="dm-copy-cell">
                  <span className="dm-copy-cell__id">{o.typeId}</span>
                  <button type="button" className="dm-copy" onClick={() => copy(o.typeId)}>
                    <DmIcon name="copy" size={14} />
                    Copy
                  </button>
                </span>
              ),
            },
          ])}
        />
      ) : (
        <Canvas legend="Each card is an object. Open its properties, or view the objects it can be associated with.">
          {[
            ['CRM objects', 'Custom objects'],
            ['Sales objects', 'Activities'],
          ].map((col) => (
            <div key={col.join()} className="dm-canvas__col">
              {col.map((g) => {
                const items = rows
                  .filter((o) => o.group === g)
                  .sort((a, b) => byText(a.name, b.name));
                if (!items.length) return null;
                return (
                  <section key={g} className="dm-gsec">
                    <span className="dm-gsec__label">{g}</span>
                    <div className="dm-gsec__grid">
                      {items.map((o) => (
                        <GraphCard key={o.key} object={o} />
                      ))}
                    </div>
                  </section>
                );
              })}
            </div>
          ))}
        </Canvas>
      )}
      {exporting && <ExportPropertiesModal model={model} onClose={() => setExporting(false)} />}
    </>
  );
}

function GraphCard({ object: o }: { object: DmObject }) {
  const { model, href, openProperty, renameObject, canEdit } = useDm();
  const menu = useObjectMenu();
  const activate = useActivate();
  const [open, setOpen] = useState(false);
  const [mode, setMode] = useState<'top' | 'recent'>('top');
  // Assets using each field (GET /object-usage/properties), loaded when the list first opens.
  const [assets, setAssets] = useState<Map<string, number> | null>(null);
  useEffect(() => {
    if (!open || assets || o.catalog) return;
    let alive = true;
    listPropertyUsage(o.key).then(
      (rows) => alive && setAssets(new Map(rows.map((r) => [r.name, propertyAssetCount(r)]))),
      () => alive && setAssets(new Map()),
    );
    return () => {
      alive = false;
    };
  }, [open, assets, o.catalog, o.key]);
  const props = liveProperties(model, o.key);
  const shown = (
    mode === 'recent'
      ? // Custom properties only: an activity's default fields aren't "created".
        props.filter((p) => !p.system).sort((a, b) => b.createdAt.localeCompare(a.createdAt))
      : [...props].sort(
          (a, b) =>
            (assets?.get(b.name) ?? 0) - (assets?.get(a.name) ?? 0) ||
            a.displayOrder - b.displayOrder ||
            byText(a.label, b.label),
        )
  ).slice(0, 10);

  return (
    <article className={cn('dm-gcard', !o.active && 'is-inactive')}>
      <header className="dm-gcard__head">
        <span className="dm-gcard__icon">
          <DmIcon name={o.active ? o.icon : 'circle'} size={o.active ? 14 : 10} />
        </span>
        <span className="dm-gcard__name">{o.name}</span>
        {/* HUB-603: what the object is for, and its name pencil. */}
        <Tip text={o.desc || o.name}>
          <DmIcon name="info" size={13} />
        </Tip>
        <span className="dm-grow" />
        {hasEditPanel(o) && (
          <button
            type="button"
            className="dm-icon-btn dm-icon-btn--xs"
            aria-label={`Edit ${o.name} name`}
            title="Edit object name"
            onClick={() => renameObject(o.key)}
            {...lockProps(canEdit)}
          >
            <DmIcon name="pencil" size={13} />
          </button>
        )}
        <ActionMenu
          label={
            <>
              <DmIcon name="more-vertical" size={14} />
              <span className="crm-visually-hidden">Actions for {o.name}</span>
            </>
          }
          btnClass="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring"
          items={menu(o, { card: true })}
        />
      </header>
      {!o.active ? (
        <div className="dm-gcard__off">
          <button
            type="button"
            className="dm-btn dm-btn--outline dm-btn--xs"
            onClick={() => activate(o)}
            {...lockProps(canEdit)}
          >
            Activate object
          </button>
        </div>
      ) : (
        <>
          <button
            type="button"
            className={cn('dm-gcard__row', open && 'is-open')}
            aria-expanded={open}
            onClick={() => setOpen((v) => !v)}
          >
            <DmIcon name="chevron-right" size={13} />
            <span className="dm-ti dm-ti--abc">Abc</span>
            {props.length} properties
          </button>
          {open && (
            <div className="dm-gcard__props">
              <SelectMenu
                className="dm-select--sm"
                value={mode}
                options={[
                  { value: 'top', label: 'Top 10 most used properties' },
                  { value: 'recent', label: 'Recently created custom properties' },
                ]}
                onChange={setMode}
                ariaLabel="Properties shown"
              />
              <div className="dm-gcard__th">Property name</div>
              <ul className="dm-gcard__list">
                {!shown.length && <li className="dm-gcard__none">No properties to show</li>}
                {shown.map((p) => (
                  <li key={p.id}>
                    <TypeIcon label={fieldTypeLabel(p)} />
                    <span>{p.label}</span>
                    <button
                      type="button"
                      className="dm-icon-btn dm-icon-btn--xs dm-gcard__edit"
                      aria-label={`Edit ${p.label}`}
                      onClick={() => openProperty(o.key, p, 'edit')}
                      {...lockProps(canEdit)}
                    >
                      <DmIcon name="pencil" size={12} />
                    </button>
                  </li>
                ))}
              </ul>
              <div className="dm-gcard__btns">
                <button
                  type="button"
                  className="dm-btn dm-btn--primary dm-btn--xxs"
                  onClick={() => openProperty(o.key, null, 'create')}
                  {...lockProps(canEdit)}
                >
                  <DmIcon name="plus" size={12} />
                  Create property
                </button>
                <Link
                  className="dm-btn dm-btn--outline dm-btn--xxs"
                  href={href({ tab: 'manage', object: o.key, sub: 'properties' })}
                >
                  View all
                </Link>
              </div>
            </div>
          )}
          <div className="dm-gcard__row dm-gcard__row--assoc">
            <DmIcon name="assoc" size={13} />
            <span>{associationsOf(model, o.key).length} associated objects</span>
            <span className="dm-grow" />
            <Link
              className="dm-btn dm-btn--outline dm-btn--xxs"
              href={href({ tab: 'manage', object: o.key, sub: 'associations', view: 'graph' })}
            >
              View all
            </Link>
          </div>
        </>
      )}
    </article>
  );
}
