'use client';

import Link from 'next/link';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { DmIcon } from '@/features/data-model/ui/icons';
import { listAllObjectDefinitions, listCrmDefinedObjects } from '@/features/objects/api.client';
import { objectKeyForAlias } from '@/features/objects/paths';
import { listObjectLabels, type ObjectLabel } from '@/features/objects/labels';
import type { CrmDefinedObject, ObjectDefinition } from '@/features/objects/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { EditObjectDrawer, toggleObjectArchived } from './CustomObjectSettings';
import { ActivitiesSettings } from './object-settings/ActivitiesSettings';
import { ForecastsSettings } from './object-settings/ForecastsSettings';
import {
  buildObjects,
  dataModelHref,
  ACTIVITY_OBJECT_ALIASES,
  normaliseObjectKey,
  settingsHref,
  TAB_LABELS,
  type OsObject,
  type TabKey,
} from './object-settings/config';
import { IndexTab, ViewsTab } from './object-settings/CustomizationTabs';
import { RecordCustomizationTab } from '@/features/record-layouts/ui/RecordCustomizationTab';
import { LifecycleTab } from './object-settings/LifecycleTab';
import { ObjectPicker } from './object-settings/ObjectPicker';
import { PipelinesTab } from './object-settings/PipelinesTab';
import { OsDropdown } from './object-settings/primitives';
import { SetupTab } from './object-settings/SetupTab';

const BUILDER_HREF = '/data-model?tab=builder&from=manage';
/** Design: data-model.php?tab=builder&from=manage&create=1 */
const CREATE_OBJECT_HREF = '/data-model?tab=builder&from=manage&create=1';
const CUSTOM_OBJECT_LIMIT = 10;

/**
 * Settings > Objects (object-settings.php): "Select an object", then that object's tabs. The
 * object, tab and sub-tab live in the URL (?object=&tab=&sub=), so every view can be linked to.
 */
export function ObjectsSettingsView() {
  const params = useSearchParams();
  const router = useRouter();
  const toast = useToast();
  const me = useCurrentUser();
  const canManage = Boolean(me.permissionSet.rules.app.manage_settings);

  const [definitions, setDefinitions] = useState<ObjectDefinition[] | null>(null);
  const [catalog, setCatalog] = useState<CrmDefinedObject[]>([]);
  const [names, setNames] = useState<ObjectLabel[]>([]);
  const [editOpen, setEditOpen] = useState(false);

  const load = useCallback(async () => {
    const [defs, crmDefined, labels] = await Promise.allSettled([
      listAllObjectDefinitions(),
      listCrmDefinedObjects(),
      listObjectLabels(),
    ]);
    if (defs.status === 'fulfilled') setDefinitions(defs.value);
    else {
      setDefinitions([]);
      toast(errorText(defs.reason), 'danger');
    }
    if (crmDefined.status === 'fulfilled') setCatalog(crmDefined.value);
    if (labels.status === 'fulfilled') setNames(labels.value);
  }, [toast]);

  useEffect(() => {
    void load();
  }, [load]);

  const objects = useMemo(
    () => buildObjects(definitions ?? [], catalog, names),
    [definitions, catalog, names],
  );
  const rawObject = (params.get('object') ?? '').trim().toLowerCase();
  const activityType = ACTIVITY_OBJECT_ALIASES[rawObject];
  const key = activityType ? 'activities' : normaliseObjectKey(rawObject);
  // HUB-746 #4: `?object=2-34907060` (a HubSpot type id) or another name of a custom object.
  const aliasKey = definitions ? objectKeyForAlias(key, definitions) : null;
  const current = objects.find((o) => o.key === (aliasKey ?? key));

  useEffect(() => {
    if (activityType) {
      router.replace(settingsHref('activities', 'associations', { type: activityType }));
    }
  }, [activityType, router]);

  // An unknown or archived object in the URL: back to Contacts once the objects are loaded.
  useEffect(() => {
    if (definitions && !current) router.replace(settingsHref('contact'));
  }, [current, definitions, router]);

  if (!current) {
    return <p className="os-muted">Loading objects…</p>;
  }

  const customCount = objects.filter((o) => o.group === 'custom').length;
  const isCustom = current.group === 'custom';
  const replaceDefinition = (saved: ObjectDefinition) =>
    setDefinitions((cur) => (cur ?? []).map((d) => (d.id === saved.id ? saved : d)));

  const onArchive = async () => {
    const def = current.definition;
    if (!def) return;
    try {
      const saved = await toggleObjectArchived(def, true);
      if (!saved) return;
      replaceDefinition(saved);
      toast(`${saved.pluralLabel} archived.`, 'success');
      router.replace(settingsHref('contact'));
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  return (
    <div className="os">
      <div className="os-banner" role="note">
        <div>
          <p className="os-banner__title">Manage custom objects in the data model builder</p>
          <p className="os-banner__text">
            You can now create, edit, and manage custom objects in the data model builder.{' '}
            <Link className="os-pill" href={BUILDER_HREF}>
              Open data model builder
            </Link>
          </p>
        </div>
      </div>

      <h1 className="os-title">Objects</h1>

      {!canManage ? (
        <Alert tone="warning">You can view these settings, but only admins can change them.</Alert>
      ) : null}

      <div className={cn('os-picker', !isCustom && 'os-picker--plain')}>
        <span className="os-picker__label">Select an object:</span>
        <ObjectPicker objects={objects} current={current} />
        {isCustom ? (
          <span className="os-picker__side">
            <span className="os-picker__count">
              {customCount} out of {CUSTOM_OBJECT_LIMIT} custom objects created
            </span>
            {canManage ? (
              <Link
                className="btn-crm btn-crm--primary btn-crm--sm os-picker__create"
                href={CREATE_OBJECT_HREF}
              >
                Create Object
              </Link>
            ) : null}
          </span>
        ) : null}
      </div>

      {current.kind === 'activities' ? (
        <ActivitiesSettings
          tab={params.get('tab')}
          subject={params.get('subject')}
          type={params.get('type')}
          objects={objects}
          canManage={canManage}
        />
      ) : current.kind === 'forecasts' ? (
        <ForecastsSettings tab={params.get('tab')} canManage={canManage} />
      ) : current.kind === 'off' ? (
        <Deactivated />
      ) : (
        <ObjectTabs
          object={current}
          tab={params.get('tab')}
          sub={params.get('sub')}
          canManage={canManage}
          onEditObject={() => setEditOpen(true)}
          onArchiveObject={() => void onArchive()}
          onSaved={replaceDefinition}
        />
      )}

      <EditObjectDrawer
        definition={current.definition}
        open={editOpen}
        onClose={() => setEditOpen(false)}
        onSaved={replaceDefinition}
      />
    </div>
  );
}

/** A CRM-defined object that isn't switched on: the design's "Activate the object" message. */
function Deactivated() {
  return (
    <section className="os-off" aria-label="Object is deactivated">
      <svg className="os-off__art" viewBox="0 0 160 120" aria-hidden>
        <rect x="22" y="24" width="116" height="78" rx="8" className="a" />
        <path d="M22 42h116" className="b" />
        <circle cx="36" cy="33" r="3" className="c" />
        <circle cx="46" cy="33" r="3" className="c" />
        <rect x="40" y="56" width="50" height="8" rx="4" className="c" />
        <rect x="40" y="72" width="80" height="8" rx="4" className="c" />
        <circle cx="122" cy="96" r="18" className="d" />
        <path d="M114 96h16" className="e" />
      </svg>
      <h2 className="os-off__title">Activate the object to access its settings.</h2>
      <p className="os-off__text">
        The object is deactivated, so it&apos;s not visible in the settings page. To view and edit
        this object&apos;s settings, you need to activate it in the Data Model Builder first.
      </p>
      <Link className="btn-crm btn-crm--primary btn-crm--sm" href={CREATE_OBJECT_HREF}>
        Activate the object in Data Model Builder
      </Link>
    </section>
  );
}

function ObjectTabs({
  object: o,
  tab: rawTab,
  sub,
  canManage,
  onEditObject,
  onArchiveObject,
  onSaved,
}: {
  object: OsObject;
  tab: string | null;
  sub: string | null;
  canManage: boolean;
  onEditObject: () => void;
  onArchiveObject: () => void;
  onSaved: (definition: ObjectDefinition) => void;
}) {
  const tab: TabKey = o.tabs.includes(rawTab as TabKey) ? (rawTab as TabKey) : 'setup';
  return (
    <>
      <div className="os-tabbar">
        <TabStrip object={o} active={tab} />
        {o.inModel ? (
          <Link
            className="os-viewlink"
            href={dataModelHref(o.key)}
            title={`View ${o.plural} in the data model`}
          >
            <span>View {o.plural} in the data model</span>
            <DmIcon name="external" size={14} />
          </Link>
        ) : null}
      </div>

      {tab === 'setup' ? (
        <SetupTab
          object={o}
          canManage={canManage}
          onEditObject={onEditObject}
          onArchiveObject={onArchiveObject}
          onSaved={onSaved}
        />
      ) : tab === 'lifecycle' ? (
        <LifecycleTab object={o} sub={sub} canManage={canManage} />
      ) : tab === 'pipelines' ? (
        <PipelinesTab object={o} sub={sub} canManage={canManage} onSaved={onSaved} />
      ) : tab === 'record' && ['contact', 'company', 'deal', 'event', 'lead'].includes(o.key) ? (
        // HUB-381: the record page views of contacts, companies and deals. EV18a: and events
        // (the 6 Nov design's object-settings.php:133-135). LR1: and leads.
        <RecordCustomizationTab objectType={o.key} singular={o.singular} canManage={canManage} />
      ) : tab === 'record' || tab === 'preview' ? (
        <ViewsTab object={o} tab={tab} />
      ) : (
        <IndexTab object={o} />
      )}
    </>
  );
}

/** The folder tabs; the ones that don't fit move into "More" (the design's object-settings.js). */
function TabStrip({ object: o, active }: { object: OsObject; active: TabKey }) {
  const navRef = useRef<HTMLElement>(null);
  const widths = useRef<Record<string, number>>({});
  const [fit, setFit] = useState(o.tabs.length);

  useLayoutEffect(() => {
    const nav = navRef.current;
    const bar = nav?.parentElement;
    if (!nav || !bar) return;
    // Hidden tabs measure 0: keep the width they had when shown.
    nav.querySelectorAll<HTMLElement>('[data-os-tab]').forEach((el) => {
      if (el.offsetWidth) widths.current[el.dataset.osTab!] = el.offsetWidth;
    });
    const measure = () => {
      // The data-model link keeps at least 140px beside the tabs on wide screens.
      const room = bar.clientWidth - (window.innerWidth >= 768 ? 140 : 0);
      const more = 96;
      let used = 0;
      let n = 0;
      for (const t of o.tabs) {
        const w = widths.current[t] ?? 160;
        const last = n === o.tabs.length - 1;
        if (used + w + (last ? 0 : more) > room) break;
        used += w;
        n++;
      }
      setFit(Math.max(1, n));
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(bar);
    return () => ro.disconnect();
  }, [o.tabs]);

  let shown = o.tabs.slice(0, fit);
  if (!shown.includes(active)) shown = [...shown.slice(0, Math.max(0, fit - 1)), active];
  const hidden = o.tabs.filter((t) => !shown.includes(t));

  return (
    <nav className="os-tabs" aria-label={`${o.plural} settings`} ref={navRef}>
      {/* Every tab renders once so its width is known; the ones that don't fit are hidden. */}
      {o.tabs.map((t) => (
        <Link
          key={t}
          data-os-tab={t}
          className={cn('os-tab', t === active && 'is-active')}
          href={settingsHref(o.key, t)}
          aria-current={t === active ? 'page' : undefined}
          hidden={!shown.includes(t)}
        >
          {TAB_LABELS[t]}
        </Link>
      ))}
      {hidden.length ? (
        <div className="os-tab-more">
          <OsDropdown
            className="os-tab"
            align="end"
            width={220}
            label={
              <>
                More
                <DmIcon name="caret" size={16} />
              </>
            }
          >
            {(close) => (
              <div role="menu">
                {hidden.map((t) => (
                  <Link
                    key={t}
                    className="os-menu__item"
                    role="menuitem"
                    href={settingsHref(o.key, t)}
                    onClick={close}
                  >
                    {TAB_LABELS[t]}
                  </Link>
                ))}
              </div>
            )}
          </OsDropdown>
        </div>
      ) : null}
    </nav>
  );
}
