'use client';

import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import { APP_NAME } from '@/config/constants';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import { setObjectDefinitionArchived } from '@/features/objects/api.client';
import type { ObjectDefinition } from '@/features/objects/types';
import { EditObjectDrawer } from '@/features/settings/ui/CustomObjectSettings';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { loadDataModel, setStandardObjectActive } from '../api.client';
import { DM_TABS, createObjectParams, normalizeDmUrl, pickDmTab } from '../limits';
import { liveProperties, type DataModel, type DmObject } from '../model';
import { takenObjectKeys } from '../objectNames';
import { AnalysisTab } from './AnalysisTab';
import { CreateObjectPanel } from './CreateObjectPanel';
import { HealthTab } from './HealthTab';
import { DmIcon } from './icons';
import { IntroTab } from './IntroTab';
import { ManageTab } from './ManageTab';
import { Dropdown, Modal } from './primitives';
import { CreatePropertyPanel } from './CreatePropertyPanel';
import {
  PropertyEditor,
  type PropertyEditorMode,
  type PropertyEditorSection,
  type PropertySeed,
} from './PropertyEditor';
import { EditObjectPanel } from './EditObjectPanel';
import { TOURS, TourPlayer, useTourStates, type Tour } from './Tours';
import { UsageDrawer } from './UsageDrawer';
import { UsageTab } from './UsageTab';
import { canOpenProperty, lockProps } from './viewOnly';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import {
  canOpenPropertySettings,
  canOpenSettingsHref,
  isSuperAdmin,
} from '@/features/permission-sets/property-settings';

export type DmParams = Partial<
  Record<'tab' | 'from' | 'view' | 'object' | 'sub' | 'limit' | 'to', string | null>
>;

interface DmContextValue {
  model: DataModel;
  /** Loads everything again (after a change). */
  reload: () => Promise<void>;
  /** A link inside the page; inside the builder, Manage links stay in the builder. */
  href: (params: DmParams) => string;
  params: URLSearchParams;
  builder: boolean;
  /**
   * Manage settings: the user can change the data model. Without it the page is view only (the
   * user's call, 18 Nov 2026): writes are off, saying why (`viewOnly.ts`).
   */
  canEdit: boolean;
  /**
   * Batch P1: whether a link to a Settings page shows (`canOpenSettingsHref`): apart from
   * `canEdit`, as Settings › Properties opens with Edit property settings or Manage settings.
   */
  canOpenSettings: (href: string) => boolean;
  object: (key: string) => DmObject | undefined;
  openProperty: (
    objectKey: string,
    property: CustomPropertyDefinition | null,
    mode: PropertyEditorMode,
    /** The editor section to open on (default Details). */
    section?: PropertyEditorSection,
  ) => void;
  openUsage: (key: string) => void;
  /** The Create object panel; with a CRM-defined object's key, on its confirm step. */
  createObject: (key?: string) => void;
  editObject: (key: string) => void;
  /**
   * "Edit object" (HUB-603): the names of custom objects and of Contacts, Companies and Deals;
   * other objects open read-only.
   */
  renameObject: (key: string) => void;
  setArchived: (key: string, archived: boolean) => void;
}

/** Exported for tests, which render a tab with a model of their own. */
export const DmContext = createContext<DmContextValue | null>(null);

export function useDm(): DmContextValue {
  const value = useContext(DmContext);
  if (!value) throw new Error('useDm outside DataModelView');
  return value;
}

/** Data Management > Data Model (data-model.php). Tabs and object pages live in the URL. */
export function DataModelView() {
  const toast = useToast();
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  // Batch P1 (HubSpot): only Super Admins change the Data Model; Edit property settings is for
  // Settings › Properties. The API's Data Model writes need the admin role too.
  const me = useCurrentUser();
  const canEdit = isSuperAdmin(me);
  // Old ?tab=usage links open Limits (pickDmTab).
  const { tab, builder, from } = pickDmTab(params);

  const [model, setModel] = useState<DataModel | null>(null);
  const [error, setError] = useState<string | null>(null);

  /** Two writes in a row start two reloads: only the newest one's answer is shown. */
  const reloadSeq = useRef(0);
  const reload = useCallback(async () => {
    const seq = ++reloadSeq.current;
    try {
      const next = await loadDataModel();
      if (seq !== reloadSeq.current) return;
      setModel(next);
      setError(null);
    } catch (err) {
      if (seq === reloadSeq.current) setError(errorText(err));
    }
  }, []);

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

  // The design's ?tab=associations, ?fromObjectTypeId, ?toObjectTypeId and ?create=1 links,
  // once the objects (and their type ids) are known.
  useEffect(() => {
    if (!model) return;
    const next = normalizeDmUrl(params, model.objects, tab);
    if (next) router.replace(`${pathname}?${next.toString()}`, { scroll: false });
  }, [model, params, pathname, router, tab]);

  /** The tab is picked client-side from the URL, so the static page title can't name it. */
  useEffect(() => {
    const label = DM_TABS.find(([k]) => k === tab)![1];
    document.title = `${builder ? 'Data Model Builder' : `Data Model | ${label}`} · ${APP_NAME}`;
  }, [builder, tab]);

  const href = useCallback(
    (next: DmParams) => {
      const p = { ...next };
      if (builder && (p.tab === undefined || p.tab === 'manage' || p.tab === 'builder')) {
        p.tab = 'builder';
        p.from = from;
      }
      const q = new URLSearchParams();
      for (const [k, v] of Object.entries(p)) if (v) q.set(k, v);
      const s = q.toString();
      return s ? `${pathname}?${s}` : pathname;
    },
    [builder, from, pathname],
  );

  /* ---------------------------------------------------------- shared drawers */
  const [prop, setProp] = useState<{
    key: string;
    property: CustomPropertyDefinition | null;
    mode: PropertyEditorMode;
    /** Create: the quick panel first; "Edit more options" opens the full page with its values. */
    quick?: boolean;
    seed?: PropertySeed;
    section?: PropertyEditorSection;
  } | null>(null);
  const [usageKey, setUsageKey] = useState<string | null>(null);
  // ?create=1 opens it too (data-model.php:122); normalizeDmUrl then keeps ?createCustomObject.
  const [creating, setCreating] = useState(
    canEdit &&
      (params.get('createCustomObject') === 'true' ||
        Boolean(params.get('create') && params.get('create') !== '0')),
  );
  const [creatingKey, setCreatingKey] = useState<string | null>(null);
  /** Set when the drawer closes because an object was created (its page opens instead). */
  const created = useRef(false);
  const [editing, setEditing] = useState<ObjectDefinition | null>(null);
  const [renaming, setRenaming] = useState<DmObject | null>(null);
  const [archiving, setArchiving] = useState<{ object: DmObject; archived: boolean } | null>(null);
  // HUB-600: the self-paced tour being played, and which ones were finished or skipped.
  const [tour, setTour] = useState<Tour | null>(null);
  const [tourStates, markTour] = useTourStates();

  /** The editor's field in the URL (`&editProperty=<name>`, `&cloneProperty=<name>`; HUB-606). */
  const propertyUrl = useCallback(
    (mode: PropertyEditorMode | null, name?: string) => {
      const q = new URLSearchParams(params.toString());
      q.delete('editProperty');
      q.delete('cloneProperty');
      if (mode === 'edit' && name) q.set('editProperty', name);
      if (mode === 'clone' && name) q.set('cloneProperty', name);
      const str = q.toString();
      router.replace(str ? `${pathname}?${str}` : pathname, { scroll: false });
    },
    [params, pathname, router],
  );

  // Opening a link with the field in it opens the editor once the model is loaded.
  const urlProperty = params.get('editProperty') ?? params.get('cloneProperty');
  /** The field just closed: the URL keeps it until the navigation lands, so don't reopen it. */
  const closedProperty = useRef<string | null>(null);
  useEffect(() => {
    if (urlProperty !== closedProperty.current) closedProperty.current = null;
    if (!model || prop || !urlProperty || closedProperty.current) return;
    const key = params.get('object');
    const found = key ? (model.properties[key] ?? []).find((p) => p.name === urlProperty) : null;
    const mode = params.get('editProperty') ? 'edit' : 'clone';
    // View only: a clone link writes, so it opens nothing; an edit link opens read-only.
    if (key && found && canOpenProperty(canEdit, mode, true)) {
      setProp({ key, property: found, mode });
    }
  }, [model, prop, urlProperty, params, canEdit]);

  const value = useMemo<DmContextValue | null>(() => {
    if (!model) return null;
    const object = (key: string) => model.objects.find((o) => o.key === key);
    return {
      model,
      reload,
      href,
      params,
      builder,
      canEdit,
      canOpenSettings: (target) => canOpenSettingsHref(me, target),
      object,
      // View only: the controls are off; these refuse too, so nothing that writes opens. A
      // property opens read-only (the editor's `viewOnly`).
      openProperty: (key, property, mode, section) => {
        if (!canOpenProperty(canEdit, mode, Boolean(property))) return;
        setProp({ key, property, mode, quick: mode === 'create' && !property, section });
        if (property && mode !== 'create') propertyUrl(mode, property.name);
      },
      openUsage: setUsageKey,
      createObject: (key) => {
        if (!canEdit) return;
        setCreatingKey(key ?? null);
        setCreating(true);
        // A create before this one leaves it set (onCreated doesn't close the drawer).
        created.current = false;
        router.replace(`${pathname}?${createObjectParams(params, tab, true).toString()}`, {
          scroll: false,
        });
      },
      editObject: (key) => {
        const def = canEdit ? object(key)?.definition : undefined;
        if (def) setEditing(def);
      },
      renameObject: (key) => {
        const o = canEdit ? object(key) : undefined;
        if (o) setRenaming(o);
      },
      setArchived: (key, archived) => {
        const o = canEdit ? object(key) : undefined;
        // HUB-226 D2: Contracts and Projects too, kept off per business.
        if (o?.definition || o?.deactivatable) setArchiving({ object: o, archived });
      },
    };
  }, [model, reload, href, params, builder, canEdit, me, propertyUrl, pathname, router, tab]);

  const propObject = prop && model?.objects.find((o) => o.key === prop.key);
  // #561: plural names count as keys too ("Contact" -> `contacts`).
  const takenKeys = useMemo(() => takenObjectKeys(model?.objects ?? []), [model]);

  const body = !value ? (
    error ? (
      <Alert tone="danger">
        Couldn&apos;t load the data model: {error}{' '}
        <button type="button" className="dm-link-strong" onClick={() => void reload()}>
          Try again
        </button>
      </Alert>
    ) : (
      <div className="dm-empty" aria-busy="true">
        <p>Loading the data model…</p>
      </div>
    )
  ) : (
    <>
      {model!.failed.length > 0 && (
        <Alert tone="warning">
          Some parts didn&apos;t load: {model!.failed.join(', ')}. Counts for them show as empty.
        </Alert>
      )}
      {builder || tab === 'manage' ? (
        <ManageTab />
      ) : tab === 'intro' ? (
        <IntroTab />
      ) : tab === 'limits' ? (
        <UsageTab />
      ) : tab === 'health' ? (
        <HealthTab />
      ) : (
        <AnalysisTab />
      )}
    </>
  );

  const drawers = value && (
    <>
      {propObject && prop.quick && (
        <CreatePropertyPanel
          object={propObject}
          model={value.model}
          onClose={() => setProp(null)}
          onSaved={() => void reload()}
          onMore={(seed) => setProp({ ...prop, quick: false, seed })}
        />
      )}
      {propObject && !prop.quick && (
        <PropertyEditor
          mode={prop.mode}
          object={propObject}
          // C7 (DMG7): creating, the object can be changed in the editor.
          onObjectChange={prop.mode === 'create' ? (key) => setProp({ ...prop, key }) : undefined}
          property={prop.property}
          seed={prop.seed}
          model={value.model}
          startSection={prop.section}
          viewOnly={!canEdit}
          settingsLinks={canOpenPropertySettings(me)}
          onClose={() => {
            setProp(null);
            if (urlProperty) {
              closedProperty.current = urlProperty;
              propertyUrl(null);
            }
          }}
          onSaved={() => void reload()}
        />
      )}
      <UsageDrawer objectKey={usageKey} onClose={() => setUsageKey(null)} />
      {/* HUB-605: CRM-defined objects or a custom object. */}
      {model && (
        <CreateObjectPanel
          open={creating}
          startKey={creatingKey}
          model={model}
          onClose={() => {
            setCreating(false);
            // Only the param goes, as the design (data-model.js:838-845): the page stays put.
            if (!created.current && params.get('createCustomObject') !== null)
              router.replace(`${pathname}?${createObjectParams(params, tab, false).toString()}`, {
                scroll: false,
              });
            created.current = false;
          }}
          takenKeys={takenKeys}
          onCreated={(def) => {
            created.current = true;
            setCreating(false);
            void reload();
            router.push(href({ tab: 'manage', object: def.key, sub: 'properties' }));
          }}
        />
      )}
      <EditObjectDrawer
        definition={editing}
        open={editing !== null}
        onClose={() => setEditing(null)}
        onSaved={() => {
          setEditing(null);
          void reload();
        }}
      />
      {renaming && (
        <EditObjectPanel
          object={renaming}
          objects={model?.objects ?? []}
          properties={model ? liveProperties(model, renaming.key) : []}
          onClose={() => setRenaming(null)}
          onSaved={() => void reload()}
        />
      )}
      {archiving && (
        <Modal
          title={
            archiving.archived
              ? `Deactivate ${archiving.object.name}?`
              : `Activate ${archiving.object.name}?`
          }
          okLabel={archiving.archived ? 'Deactivate' : 'Activate'}
          danger={archiving.archived}
          onClose={() => setArchiving(null)}
          onOk={async () => {
            try {
              if (archiving.object.definition) {
                await setObjectDefinitionArchived(
                  archiving.object.definition.id,
                  archiving.archived,
                );
              } else {
                await setStandardObjectActive(archiving.object.key, !archiving.archived);
              }
              toast(
                `${archiving.object.name} ${archiving.archived ? 'deactivated' : 'activated'}`,
                'success',
              );
              await reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <p className="dm-muted">
            {archiving.archived
              ? `${archiving.object.name} will be hidden from navigation, filters and reports. Records and fields are kept and you can activate the object again at any time.`
              : `${archiving.object.name} shows in navigation again, with its records and fields.`}
          </p>
        </Modal>
      )}
    </>
  );

  if (builder) {
    return (
      <DmContext.Provider value={value}>
        <div className="dm-builder" role="dialog" aria-modal="true" aria-label="Data Model Builder">
          <div className="dm-builder__bar">
            <Link className="dm-builder__exit" href={`${pathname}?tab=${from}`}>
              <DmIcon name="chevron-left" />
              Exit
            </Link>
            <h1 className="dm-builder__title">Data Model Builder</h1>
            <span />
          </div>
          <div className="dm-builder__body">
            <div className="dm">{body}</div>
          </div>
        </div>
        {drawers}
      </DmContext.Provider>
    );
  }

  return (
    <DmContext.Provider value={value}>
      <div className="dm">
        <div className="dm-head">
          <h1 className="dm-head__title">Data Model</h1>
          <div className="dm-head__actions">
            {tab === 'manage' ? (
              <Dropdown
                btnClass="dm-btn dm-btn--outline dm-btn--sm"
                menuClass="dm-tours"
                right
                label={
                  <>
                    Self-paced tours
                    <DmIcon name="chevron-down" />
                  </>
                }
              >
                {(close) =>
                  TOURS.map((t) => (
                    <button
                      key={t.name}
                      type="button"
                      className="dm-tour"
                      role="menuitem"
                      onClick={() => {
                        close();
                        setTour(t);
                      }}
                    >
                      <DmIcon name="chevron-right" />
                      <span className="dm-tour__text">
                        <span className="dm-tour__name">{t.name}</span>
                        {t.time && <span className="dm-tour__time">{t.time}</span>}
                      </span>
                      {tourStates[t.name] ? (
                        <span className="dm-tour__state">
                          {tourStates[t.name] === 'done' ? 'Completed' : 'Skipped'}
                        </span>
                      ) : null}
                    </button>
                  ))
                }
              </Dropdown>
            ) : canEdit ? (
              <Link
                className="dm-btn dm-btn--primary dm-btn--sm"
                href={`${pathname}?tab=builder&from=${tab}`}
              >
                <DmIcon name="pencil" />
                Edit Data Model
              </Link>
            ) : (
              <button
                type="button"
                className="dm-btn dm-btn--primary dm-btn--sm"
                {...lockProps(false)}
              >
                <DmIcon name="pencil" />
                Edit Data Model
              </button>
            )}
            {tab !== 'intro' && (
              <Link className="dm-btn dm-btn--outline dm-btn--sm" href="/data-integration/import">
                Import
                <DmIcon name="external" />
              </Link>
            )}
          </div>
        </div>
        {/* QA 18 Nov (#560): tablist, tab and tabpanel roles with arrow keys; the tabs stay page
            links (?tab=), so a link still opens in a new tab. The focus ring is unchanged. */}
        <nav
          className="dm-tabs"
          role="tablist"
          aria-label="Data model sections"
          onKeyDown={(e) => {
            const at = DM_TABS.findIndex(([k]) => k === tab);
            const next =
              e.key === 'ArrowRight'
                ? (at + 1) % DM_TABS.length
                : e.key === 'ArrowLeft'
                  ? (at - 1 + DM_TABS.length) % DM_TABS.length
                  : e.key === 'Home'
                    ? 0
                    : e.key === 'End'
                      ? DM_TABS.length - 1
                      : -1;
            if (next < 0) return;
            e.preventDefault();
            const key = DM_TABS[next]![0];
            document.getElementById(`dm-tab-${key}`)?.focus();
            router.push(`${pathname}?tab=${key}`);
          }}
        >
          {DM_TABS.map(([k, label]) => (
            <Link
              key={k}
              id={`dm-tab-${k}`}
              role="tab"
              className={cn('dm-tabs__link', k === tab && 'is-active')}
              href={`${pathname}?tab=${k}`}
              aria-selected={k === tab}
              aria-controls="dm-tabpanel"
              tabIndex={k === tab ? 0 : -1}
            >
              {label}
            </Link>
          ))}
        </nav>
        <div
          id="dm-tabpanel"
          role="tabpanel"
          aria-labelledby={`dm-tab-${tab}`}
          className={cn('dm-body', `dm-body--${tab}`)}
        >
          {body}
        </div>
      </div>
      {drawers}
      {tour && tab === 'manage' ? (
        <TourPlayer
          tour={tour}
          onEnd={(state) => {
            markTour(tour.name, state);
            setTour(null);
          }}
        />
      ) : null}
    </DmContext.Provider>
  );
}
