'use client';

import Link from 'next/link';
import {
  useCallback,
  useContext,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type ReactNode,
} from 'react';
import { DmContext } from './DataModelView';

/**
 * Self-paced tours on the Data Model's Manage tab (HUB-600; the design's $DM_TOURS). A tour is
 * a few steps, each pointing at a part of the page (by selector) with what it does; a step whose
 * part isn't on screen (another view, no rows) shows in the middle instead. Finished and skipped
 * tours are remembered in this browser, and the menu marks them.
 */

export interface TourStep {
  /** CSS selector of the part the step is about; none: shown in the middle. */
  target?: string;
  title: string;
  body: ReactNode;
}

export interface Tour {
  name: string;
  time: string;
  steps: TourStep[];
}

/** The admin-only Settings pages (Manage settings); Imports & Exports is open to importers. */
export const ADMIN_SETTINGS = /^\/settings\/(objects|properties|associations)\b/;

/** A link to a Settings page, or plain text for someone it would not open for (batch P1). */
function SettingsLink({ href, label }: { href: string; label: string }) {
  const canOpen = useContext(DmContext)?.canOpenSettings(href) ?? false;
  if (!canOpen && ADMIN_SETTINGS.test(href)) return <span className="dm-link-strong">{label}</span>;
  return (
    <Link className="dm-link-strong" href={href}>
      {label}
    </Link>
  );
}

const settingsLink = (href: string, label: string) => <SettingsLink href={href} label={label} />;

export const TOURS: Tour[] = [
  {
    name: "What's a data model",
    time: '5 minutes',
    steps: [
      {
        title: "What's a data model",
        body: 'Your data model is the objects your CRM keeps (contacts, companies, deals and your own), the properties each one stores, and how their records are associated with each other.',
      },
      {
        target: '.dm-tabs',
        title: 'Sections',
        body: 'Manage lists your objects. Limits counts your records and definitions, Health finds what to clean up, and Analysis shows how many records of an object change each day, by source.',
      },
      {
        target: '.dm-viewtoggle',
        title: 'Table or graph',
        body: 'See your objects as a table, or as a graph of objects and the associations between them.',
      },
      {
        target: '.dm-obj--row',
        title: 'Objects',
        body: 'Each row is an object: its records, properties and associated objects. Open one to see its properties, associations and pipelines.',
      },
      {
        target: '.dm-head__actions a[href="/data-integration/import"]',
        title: 'Bring your data in',
        body: 'Import records into any object from a spreadsheet. The columns map to the properties shown here.',
      },
    ],
  },
  {
    name: 'How to customize objects',
    time: '2 minutes',
    steps: [
      {
        target: '.dm-obj--row',
        title: 'Open an object',
        body: 'Click an object to see everything about it: properties, associations, pipelines and record settings.',
      },
      {
        target: '.dm-rowtools',
        title: 'Object actions',
        body: 'Rename an object, create a property, view its usage, customize its record view or deactivate an object you don’t use.',
      },
      {
        target: '.dm-tour-status',
        title: 'Deactivated objects',
        body: 'Deactivated objects are hidden from the CRM but keep their data. Filter for them here to switch one back on.',
      },
      {
        title: 'Object settings',
        body: (
          <>
            Record pages, lifecycle stages, pipelines and the index page of each object are set in{' '}
            {settingsLink('/settings/objects', 'Settings › Objects')}.
          </>
        ),
      },
    ],
  },
  {
    name: 'Quickly create properties',
    time: '2 minutes',
    steps: [
      {
        target: '[data-tour="properties"]',
        title: 'Properties',
        body: "The number of properties an object has. Click it to see them all, with each one's type, group and where it is used.",
      },
      {
        target: '.dm-rowtools',
        title: 'Create a property',
        body: 'Choose Create property from the object’s actions to add one without leaving the page.',
      },
      {
        title: 'Pick a field type',
        body: 'Give the property a label, a group and a field type: text, number, date, dropdown, checkbox and more. The internal name is made for you.',
      },
    ],
  },
  {
    name: 'Review create and edit properties',
    time: '1 minute',
    steps: [
      {
        title: 'Edit a property',
        body: 'Open a property to change its label, description, group, options and rules: required, unique, read only, or limits such as a number range.',
      },
      {
        title: 'Keep track of changes',
        body: (
          <>
            Export a property’s history to see every change to its values. Manage them all in{' '}
            {settingsLink('/settings/properties', 'Settings › Properties')}.
          </>
        ),
      },
    ],
  },
  {
    name: 'Use associations and association labels',
    time: '1 minute',
    steps: [
      {
        target: '[data-tour="associations"]',
        title: 'Associated objects',
        body: "The objects this object's records can be associated with. Click to see them and their labels.",
      },
      {
        title: 'Association labels',
        body: (
          <>
            Labels say how two records are related, such as “Decision maker” between a contact and a
            deal. Create them in {settingsLink('/settings/associations', 'Settings › Associations')}
            .
          </>
        ),
      },
    ],
  },
  {
    name: 'Create custom objects',
    time: '1 minute',
    steps: [
      {
        target: '[data-tour="create-object"]',
        title: 'Create an object',
        body: 'Add an object for anything the standard ones don’t cover, such as events or vehicles, or switch on a CRM-defined one.',
      },
      {
        title: 'Name it and choose its properties',
        body: 'Give it a singular and plural name and a primary display property. It gets its own records page, properties and associations.',
      },
    ],
  },
  {
    name: 'Resources',
    time: '',
    steps: [
      {
        title: 'Resources',
        body: (
          <ul className="dm-tourpop__links">
            <li>{settingsLink('/data-model?tab=intro', 'Data model introduction')}</li>
            <li>{settingsLink('/settings/objects', 'Object settings')}</li>
            <li>{settingsLink('/settings/properties', 'Properties')}</li>
            <li>{settingsLink('/settings/associations', 'Associations and labels')}</li>
            <li>{settingsLink('/settings/imports', 'Imports and exports')}</li>
          </ul>
        ),
      },
    ],
  },
];

export type TourState = 'done' | 'skipped';
const STORE_KEY = 'crm.dataModel.tours';

function readStates(): Record<string, TourState> {
  try {
    const raw = window.localStorage.getItem(STORE_KEY);
    const parsed: unknown = raw ? JSON.parse(raw) : {};
    return parsed && typeof parsed === 'object' ? (parsed as Record<string, TourState>) : {};
  } catch {
    return {};
  }
}

/** Each tour's state in this browser (none until it is finished or skipped). */
export function useTourStates() {
  const [states, setStates] = useState<Record<string, TourState>>({});
  useEffect(() => setStates(readStates()), []);
  const mark = useCallback((name: string, state: TourState) => {
    setStates((cur) => {
      const next = { ...cur, [name]: state };
      try {
        window.localStorage.setItem(STORE_KEY, JSON.stringify(next));
      } catch {
        // storage off (private window): the menu just doesn't remember
      }
      return next;
    });
  }, []);
  return [states, mark] as const;
}

interface Box {
  top: number;
  left: number;
  width: number;
  height: number;
}

const POP_WIDTH = 320;
const GAP = 12;
const EDGE = 16;

/** The tour being played: a spotlight on the step's part and the step's card next to it. */
export function TourPlayer({
  tour,
  onEnd,
}: {
  tour: Tour;
  /** `done` after the last step; `skipped` when closed before it. */
  onEnd: (state: TourState) => void;
}) {
  const [index, setIndex] = useState(0);
  const [box, setBox] = useState<Box | null>(null);
  const [popHeight, setPopHeight] = useState(0);
  const pop = useRef<HTMLDivElement>(null);
  const step = tour.steps[index]!;
  const last = index === tour.steps.length - 1;

  // Find the step's part, bring it into view and follow it as the page scrolls or resizes.
  useLayoutEffect(() => {
    const el = step.target ? document.querySelector<HTMLElement>(step.target) : null;
    if (!el) {
      setBox(null);
      return;
    }
    el.scrollIntoView({ block: 'center', behavior: 'smooth' });
    const place = () => {
      const r = el.getBoundingClientRect();
      setBox({ top: r.top, left: r.left, width: r.width, height: r.height });
    };
    place();
    const timer = window.setTimeout(place, 350);
    window.addEventListener('resize', place);
    window.addEventListener('scroll', place, true);
    return () => {
      window.clearTimeout(timer);
      window.removeEventListener('resize', place);
      window.removeEventListener('scroll', place, true);
    };
  }, [step.target]);

  useLayoutEffect(() => {
    setPopHeight(pop.current?.offsetHeight ?? 0);
    pop.current?.focus();
  }, [index, box === null]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onEnd('skipped');
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onEnd]);

  // Below the part when it fits, else above it; inside the window either way.
  let style: React.CSSProperties;
  if (box) {
    const below = box.top + box.height + GAP;
    const top =
      below + popHeight <= window.innerHeight - EDGE
        ? below
        : Math.max(EDGE, box.top - GAP - popHeight);
    const left = Math.min(
      Math.max(EDGE, box.left),
      Math.max(EDGE, window.innerWidth - POP_WIDTH - EDGE),
    );
    style = { top, left };
  } else {
    style = { top: '50%', left: '50%', transform: 'translate(-50%, -50%)' };
  }

  return (
    <div className="dm-tour-layer">
      {box ? (
        <div
          className="dm-tour-spot"
          style={{
            top: box.top - 4,
            left: box.left - 4,
            width: box.width + 8,
            height: box.height + 8,
          }}
          aria-hidden
        />
      ) : (
        <div className="dm-tour-dim" aria-hidden />
      )}
      <div
        ref={pop}
        className="dm-tourpop"
        role="dialog"
        aria-modal="true"
        aria-labelledby="dm-tourpop-title"
        tabIndex={-1}
        style={style}
      >
        <p className="dm-tourpop__meta">
          {tour.name}
          {tour.steps.length > 1 ? ` · ${index + 1} of ${tour.steps.length}` : ''}
        </p>
        <h2 className="dm-tourpop__title" id="dm-tourpop-title">
          {step.title}
        </h2>
        <div className="dm-tourpop__body">{step.body}</div>
        <div className="dm-tourpop__foot">
          {last ? null : (
            <button
              type="button"
              className="dm-btn dm-btn--ghost dm-btn--sm"
              onClick={() => onEnd('skipped')}
            >
              Skip tour
            </button>
          )}
          <span className="dm-grow" />
          {index > 0 ? (
            <button
              type="button"
              className="dm-btn dm-btn--outline dm-btn--sm"
              onClick={() => setIndex((i) => i - 1)}
            >
              Back
            </button>
          ) : null}
          <button
            type="button"
            className="dm-btn dm-btn--primary dm-btn--sm"
            onClick={() => (last ? onEnd('done') : setIndex((i) => i + 1))}
          >
            {last ? 'Done' : 'Next'}
          </button>
        </div>
      </div>
    </div>
  );
}
