'use client';

import Link from 'next/link';
import { useMemo, useState } from 'react';
import { fmt, healthIssues, introSummary, type HealthIssue } from '../model';
import { useDm } from './DataModelView';
import { issueKey, useDismissedIssues } from './healthLocal';
import { DmIcon } from './icons';
import { lockProps } from './viewOnly';

/** Settings pages are admin-only: a view-only user isn't shown links that would bounce them. */
const ADMIN_LINK = /^\/settings\//;

const USE_LINKS: Array<[string, string, string, string]> = [
  // Contacts' Record customization, as in HubSpot.
  ['Customize records', '/settings/objects?object=contact&tab=record', 'layout', 'indigo'],
  ['Import data', '/data-integration/import', 'upgrade', 'info'],
  ['Create workflow', '/workflows', 'workflow', 'indigo'],
  // HUB-599: the Lists page's path (not built yet; the design's lists.php).
  ['Create list', '/lists?create=1', 'list', 'info'],
  ['Create report', '/reports', 'chart', 'yellow'],
];

const RANK = { High: 0, Medium: 1, Low: 2 } as const;

function HeroArt() {
  return (
    <svg viewBox="0 0 420 260" className="dm-art">
      <ellipse cx="240" cy="220" rx="170" ry="26" className="dm-art__ground" />
      <g className="dm-art__cube">
        <path d="M230 120l55-28 55 28-55 28z" className="t" />
        <path d="M230 120v62l55 28v-62z" className="l" />
        <path d="M340 120v62l-55 28v-62z" className="r" />
      </g>
      <circle cx="70" cy="80" r="28" className="dm-art__c1" />
      <circle cx="150" cy="40" r="24" className="dm-art__c2" />
      <circle cx="220" cy="54" r="22" className="dm-art__c3" />
      <circle cx="62" cy="168" r="24" className="dm-art__c4" />
      <circle cx="140" cy="126" r="22" className="dm-art__c5" />
      <path d="M61 80h18M70 71v18" className="dm-art__ico" />
      <rect x="141" y="31" width="18" height="18" rx="3" className="dm-art__ico" />
      <path d="M212 48h16M212 54h16M212 60h10" className="dm-art__ico" />
      <circle cx="62" cy="166" r="6" className="dm-art__ico" />
      <path d="M132 120h16M132 126h16M132 132h10" className="dm-art__ico" />
      <path d="M300 60l-30 40" className="dm-art__wand" />
      <circle cx="304" cy="54" r="5" className="dm-art__spark" />
      <circle cx="318" cy="72" r="3" className="dm-art__spark" />
      <circle cx="290" cy="44" r="2.5" className="dm-art__spark" />
    </svg>
  );
}

/** Intro: what a data model is, quick actions, suggestions from the health check, and links. */
export function IntroTab() {
  const { model, href, object, createObject, openProperty, canEdit } = useDm();
  // #243: the custom properties total is Usage › Custom Properties' own.
  const summary = introSummary(model);
  // DM-18: shared with Health, so a dismissed suggestion leaves both.
  const { dismissed, dismiss } = useDismissedIssues();
  const suggestions = useMemo(
    () =>
      healthIssues(model)
        .filter((i) => i.severity !== 'Low')
        .sort((a, b) => RANK[a.severity] - RANK[b.severity]),
    [model],
  );
  const list = suggestions.filter((s) => !dismissed.has(issueKey(s)));
  const [idx, setIdx] = useState(0);
  const cur = Math.min(idx, Math.max(0, list.length - 1));
  const s = list[cur];

  const fix = (issue: HealthIssue) => {
    const p =
      issue.propertyId && model.properties[issue.object]?.find((x) => x.id === issue.propertyId);
    if (p) openProperty(issue.object, p, 'edit');
  };

  return (
    <>
      <section className="dm-hero">
        <div className="dm-hero__text">
          <h2>
            Structure your data to grow
            <br />
            ambitiously
          </h2>
          <p>
            A data model is the blueprint for how all your customer data is structured, connected,
            and made usable across our tools. A good data model helps you:
          </p>
          <ul>
            <li>Report on what matters</li>
            <li>Segment your customers effectively</li>
            <li>Automate work</li>
          </ul>
        </div>
        <div className="dm-hero__art" aria-hidden>
          <HeroArt />
        </div>
      </section>

      <div className="dm-intro-grid">
        <section className="dm-card dm-ai">
          <h3 className="dm-card__title">Build your data model</h3>
          <div className="dm-ai__inner">
            <div className="dm-ai__art" aria-hidden>
              <DmIcon name="database" size={48} />
            </div>
            <div className="dm-ai__body">
              <p className="dm-ai__lead">
                {summary.objects} active objects, {fmt(summary.properties)} custom properties and{' '}
                {summary.labels} association labels.
              </p>
              <p className="dm-ai__sub">
                Add an object for anything your business tracks, then give it properties, groups and
                associations.
              </p>
              <div className="dm-ai__foot" style={{ gap: 8 }}>
                <Link
                  className="dm-btn dm-btn--outline dm-btn--sm"
                  href={href({ tab: 'manage', view: 'graph' })}
                >
                  <DmIcon name="tree" size={14} />
                  View data model
                </Link>
                <button
                  type="button"
                  className="dm-btn dm-btn--soft dm-btn--sm"
                  onClick={() => createObject()}
                  {...lockProps(canEdit)}
                >
                  <DmIcon name="plus" size={14} />
                  Create object
                </button>
              </div>
            </div>
          </div>
        </section>

        <section className="dm-card dm-sugg">
          <h3 className="dm-card__title">Apply quick suggestions</h3>
          {!s ? (
            <div className="dm-empty dm-empty--sm">
              <DmIcon name="check-big" size={32} />
              <p>
                <b>You&apos;re all caught up</b>
              </p>
              <p>No more suggestions right now.</p>
            </div>
          ) : (
            <>
              <div
                className="dm-sugg__wrap"
                onKeyDown={(e) => {
                  if (e.key === 'ArrowLeft' && cur > 0) setIdx(cur - 1);
                  if (e.key === 'ArrowRight' && cur < list.length - 1) setIdx(cur + 1);
                }}
              >
                <button
                  type="button"
                  className="dm-round"
                  aria-label="Previous suggestion"
                  disabled={cur === 0}
                  onClick={() => setIdx(cur - 1)}
                >
                  <DmIcon name="chevron-left" />
                </button>
                <div className="dm-sugg__card" aria-live="polite">
                  <p className="dm-sugg__kicker">
                    <DmIcon name={object(s.object)?.icon ?? 'grid'} size={14} />
                    {object(s.object)?.singular ?? s.object} · {s.category.toLowerCase()}
                  </p>
                  <p className="dm-sugg__prop">
                    <i className={`dm-dot dm-dot--${s.severity.toLowerCase()}`} />
                    {s.item}
                  </p>
                  <p className="dm-sugg__desc">{s.issue}</p>
                  <p className="dm-sugg__note" title={s.details}>
                    <DmIcon name="info" size={14} />
                    <span>{s.details}</span>
                  </p>
                  <div className="dm-sugg__actions">
                    {s.propertyId ? (
                      <button
                        type="button"
                        className="dm-btn dm-btn--outline dm-btn--xs"
                        onClick={() => fix(s)}
                        {...lockProps(canEdit)}
                      >
                        <DmIcon name="pencil" size={14} />
                        Fix
                      </button>
                    ) : (
                      <Link
                        className="dm-btn dm-btn--outline dm-btn--xs"
                        href={href({ tab: 'health' })}
                      >
                        <DmIcon name="check" size={14} />
                        Review
                      </Link>
                    )}
                    <button
                      type="button"
                      className="dm-btn dm-btn--outline dm-btn--xs"
                      onClick={() => dismiss(s)}
                    >
                      Dismiss
                    </button>
                  </div>
                </div>
                <button
                  type="button"
                  className="dm-round"
                  aria-label="Next suggestion"
                  disabled={cur >= list.length - 1}
                  onClick={() => setIdx(cur + 1)}
                >
                  <DmIcon name="chevron-right" />
                </button>
              </div>
              <p className="dm-sugg__count">
                {cur + 1}/{list.length}
              </p>
            </>
          )}
        </section>
      </div>

      <section className="dm-card dm-use">
        <h3 className="dm-card__title">Use your data model across CRM</h3>
        <div className="dm-use__row">
          {USE_LINKS.filter(([, to]) => canEdit || !ADMIN_LINK.test(to)).map(
            ([label, to, icon, tone]) => (
              <Link key={label} className="dm-use__link" href={to}>
                <span className={`dm-use__icon dm-tone--${tone}`}>
                  <DmIcon name={icon} />
                </span>
                <span>{label}</span>
                <DmIcon name="external" size={14} />
              </Link>
            ),
          )}
        </div>
      </section>
    </>
  );
}
