'use client';

import Link from 'next/link';
import { fmt, isCalculated, liveProperties, usedIn } from '../model';
import { useDm } from './DataModelView';
import { DmIcon } from './icons';
import { Accordion, Drawer, DrawerHead } from './primitives';

interface AssetGroup {
  title: string;
  items: Array<{ key: string; name: string; href: string | null }>;
  /** "View all <title>" target; none when the app has no page listing them. */
  all: string | null;
}

/**
 * "View object usage" / Used In (openUsage): the object's records and the assets using it:
 * reports, workflows, lists, sales views (saved list views), forms and calculated properties.
 */
export function UsageDrawer({
  objectKey,
  onClose,
}: {
  objectKey: string | null;
  onClose: () => void;
}) {
  const { model, object, href } = useDm();
  const o = objectKey ? object(objectKey) : undefined;
  const used = o ? usedIn(model, o) : null;
  const u = o ? model.usage?.[o.key] : undefined;
  const calculated = o ? liveProperties(model, o.key).filter(isCalculated) : [];
  const propsHref = o ? href({ tab: 'manage', object: o.key, sub: 'properties' }) : '';

  const groups: AssetGroup[] = o
    ? [
        {
          title: 'Reports',
          items: (u?.reports ?? []).map((r) => ({
            key: r.id,
            name: r.name,
            href: `/reports/dashboards/${r.dashboardId}`,
          })),
          all: '/reports/dashboards',
        },
        {
          title: 'Workflows',
          items: (u?.workflows ?? []).map((w) => ({
            key: w.id,
            name: w.name,
            href: `/workflows/${w.id}`,
          })),
          all: '/workflows',
        },
        {
          title: 'Lists',
          // The design links each list and "View all lists" to the lists page (data-model.js:2848-2849).
          items: (u?.lists ?? []).map((l) => ({ key: l.id, name: l.name, href: '/lists' })),
          all: '/lists',
        },
        {
          title: 'Sales Views',
          items: (u?.views ?? []).map((v) => ({ key: v.id, name: v.name, href: o.page || null })),
          all: o.page || null,
        },
        {
          title: 'Forms',
          items: (u?.forms ?? []).map((f) => ({ key: f.id, name: f.name, href: null })),
          all: null,
        },
        {
          title: 'Calculated Properties',
          items: calculated.map((p) => ({ key: p.id, name: p.label, href: propsHref })),
          all: propsHref,
        },
      ].filter((g) => g.items.length > 0)
    : [];
  const total = (o?.records ?? 0) + groups.reduce((n, g) => n + g.items.length, 0);

  return (
    <Drawer open={Boolean(o)} onClose={onClose} label="Usage">
      <DrawerHead title="Usage" onClose={onClose} />
      {o && (
        <div className="dm-drawer__body">
          <div className="dm-usage-obj">
            <h3>
              <DmIcon name={o.icon} />
              {o.singular}
            </h3>
            <p>{o.desc || o.name}</p>
          </div>
          <div className="dm-usage-stats">
            <div className="dm-usage-stat">
              {o.records && o.page ? (
                <Link className="dm-usage-stat__num" href={o.page}>
                  {fmt(o.records)}
                  <DmIcon name="external" />
                </Link>
              ) : (
                <span className="dm-usage-stat__num">
                  {o.records === null ? '--' : fmt(o.records)}
                </span>
              )}
              <span>Total records created</span>
            </div>
            <div className="dm-usage-stat">
              <span className="dm-usage-stat__num">
                {used === null ? (o.active ? '--' : 'N/A') : fmt(used)}
              </span>
              <span>Assets using this object</span>
            </div>
          </div>
          <p className="dm-usage-total">Assets ({fmt(total)})</p>
          <div className="dm-acc">
            <Accordion title={`Records (${o.records === null ? '--' : fmt(o.records)})`}>
              {o.page ? (
                <Link className="dm-acc__link" href={o.page}>
                  View all records <DmIcon name="external" size={12} />
                </Link>
              ) : (
                <p className="dm-muted">No records yet.</p>
              )}
            </Accordion>
            {groups.map((g) => (
              <Accordion key={g.title} title={`${g.title} (${g.items.length})`}>
                {g.items.slice(0, 5).map((it) =>
                  it.href ? (
                    <Link key={it.key} className="dm-acc__link" href={it.href} onClick={onClose}>
                      {it.name} <DmIcon name="external" size={12} />
                    </Link>
                  ) : (
                    <span key={it.key} className="dm-acc__link">
                      {it.name}
                    </span>
                  ),
                )}
                {g.all && (
                  <Link className="dm-acc__link dm-acc__all" href={g.all} onClick={onClose}>
                    View all {g.title.toLowerCase()} <DmIcon name="external" size={12} />
                  </Link>
                )}
              </Accordion>
            ))}
            {!groups.length && !o.records && (
              <p className="dm-muted">This object isn&apos;t used in any assets yet.</p>
            )}
          </div>
        </div>
      )}
    </Drawer>
  );
}
