'use client';

import Link from 'next/link';
import { useMemo, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  archiveCustomProperty,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  byText,
  CATEGORIES,
  healthIssues,
  SEVERITIES,
  type HealthIssue,
  type IssueCategory,
  type Severity,
} from '../model';
import { issuesShownText, objectsWithIssuesText, openIssuesText } from '../healthText';
import { lastRunText } from '../zoneText';
import { useDm } from './DataModelView';
import { issueKey, useDismissedIssues, useHealthLastRun } from './healthLocal';
import { DmIcon } from './icons';
import { ActionMenu, CheckFilter, DataTable, Modal, SearchBox, type MenuItem } from './primitives';
import { lockItem } from './viewOnly';

const SEV_RANK: Record<Severity, number> = { High: 3, Medium: 2, Low: 1 };

/** Health: gaps found in the data model, by severity or by object (renderHealth). */
export function HealthTab() {
  const { model, reload, href, object, openProperty, canEdit } = useDm();
  /** A write, or a link to an admin-only Settings page: off for a view-only user. */
  const lock = (item: MenuItem) => lockItem(item, canEdit);
  const { timeZone } = useUserPrefs();
  const toast = useToast();
  // DM-18, DM-12: issues dismissed here or on Intro are left out.
  const { dismissed, dismiss } = useDismissedIssues();
  const issues = useMemo(
    () => healthIssues(model).filter((i) => !dismissed.has(issueKey(i))),
    [model, dismissed],
  );
  // #77: the last Re-run, not the last time the data model loaded.
  const { lastRun, markRun } = useHealthLastRun(model.loadedAt);
  const [view, setView] = useState<'severity' | 'object'>('severity');
  const [search, setSearch] = useState('');
  const [osearch, setOsearch] = useState('');
  const [cat, setCat] = useState<string[]>([]);
  const [obj, setObj] = useState<string[]>([]);
  const [sev, setSev] = useState<string[]>([]);
  /** A2: the design's Issue filter (data-model.js:6040, 6067, 6084). */
  const [issue, setIssue] = useState<string[]>([]);
  const [running, setRunning] = useState(false);
  /** Archive from a health issue asks first, as the Properties tab does. */
  const [archiving, setArchiving] = useState<CustomPropertyDefinition | null>(null);
  const listRef = useRef<HTMLElement>(null);

  const objName = (key: string) => object(key)?.name ?? key;
  // The table names each object in the singular ("Contact"), as in the design.
  const objSingular = (key: string) => object(key)?.singular ?? key;
  const filtered = (ignore?: 'cat' | 'issue' | 'obj' | 'sev') => {
    const q = search.trim().toLowerCase();
    return issues.filter((x) => {
      if (q && !`${x.item} ${x.issue} ${x.details} ${objName(x.object)}`.toLowerCase().includes(q))
        return false;
      if (ignore !== 'cat' && cat.length && !cat.includes(x.category)) return false;
      if (ignore !== 'issue' && issue.length && !issue.includes(x.issue)) return false;
      if (ignore !== 'obj' && obj.length && !obj.includes(x.object)) return false;
      if (ignore !== 'sev' && sev.length && !sev.includes(x.severity)) return false;
      return true;
    });
  };
  const counts = (list: HealthIssue[], f: (x: HealthIssue) => string) => {
    const c: Record<string, number> = {};
    list.forEach((x) => (c[f(x)] = (c[f(x)] ?? 0) + 1));
    return c;
  };
  const filterLabel = (
    name: string,
    sel: string[],
    c: Record<string, number>,
    show: (v: string) => string = (v) => v,
  ) =>
    !sel.length
      ? name
      : sel.length === 1
        ? `${show(sel[0]!)} (${c[sel[0]!] ?? 0})`
        : `(${sel.length}) ${name}`;

  const bySev = counts(issues, (x) => x.severity);
  const high: Record<string, number> = {};
  issues
    .filter((x) => x.severity === 'High')
    .forEach((x) => (high[x.object] = (high[x.object] ?? 0) + 1));
  const top = Object.keys(high)
    .sort((a, b) => high[b]! - high[a]!)
    .slice(0, 3);

  const jump = (next: { sev?: string[]; obj?: string[]; cat?: string[] }) => {
    setView('severity');
    setSev(next.sev ?? []);
    setObj(next.obj ?? []);
    setCat(next.cat ?? []);
    // The summary and object jumps, and Clear filters, clear it too (data-model.js:6138-6148).
    setIssue([]);
    listRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const rerun = async () => {
    setRunning(true);
    await reload();
    markRun(new Date());
    setRunning(false);
    toast('Health check complete', 'success');
  };

  /** DM-12: every row can be dismissed; it leaves Health and Intro in this browser. */
  const dismissItem = (x: HealthIssue): MenuItem => ({
    label: 'Dismiss',
    onClick: () => {
      dismiss(x);
      toast('Issue dismissed', 'success');
    },
  });
  const actions = (x: HealthIssue): MenuItem[] => [...issueActions(x), dismissItem(x)];
  const issueActions = (x: HealthIssue): MenuItem[] => {
    const p = x.propertyId
      ? model.properties[x.object]?.find((y) => y.id === x.propertyId)
      : undefined;
    if (x.category === 'Property' && p) {
      // An object's record name field is never offered: archiving it leaves records unnamed.
      const isNameField = model.objects.some(
        (o) => o.key === x.object && o.definition?.displayProperty === p.name,
      );
      // #281: a duplicate label's row archives either field of the pair, as in HubSpot.
      const other = x.duplicateOfId
        ? model.properties[x.object]?.find((y) => y.id === x.duplicateOfId && !y.archived)
        : undefined;
      const otherIsName = model.objects.some(
        (o) => o.key === x.object && o.definition?.displayProperty === other?.name,
      );
      // As in the design: Archive property, then Manage property.
      return [
        // Nor an activity's default field (HUB-609), which can't be archived.
        ...(isNameField || p.system
          ? []
          : [
              lock({
                label: other ? 'Archive this property' : 'Archive property',
                onClick: () => setArchiving(p),
              }),
            ]),
        ...(other && !other.system && !other.standard && !otherIsName
          ? [
              lock({
                label: `Archive duplicate property ("${other.label}")`,
                onClick: () => setArchiving(other),
              }),
            ]
          : []),
        // Opens the field; read-only for a view-only user.
        { label: 'Manage property', onClick: () => openProperty(x.object, p, 'edit') },
      ];
    }
    if (x.category === 'Property')
      return [
        {
          label: 'Manage property groups',
          href: href({ tab: 'manage', object: x.object, sub: 'groups' }),
        },
      ];
    if (x.category === 'Association')
      return [
        {
          label: 'Manage association labels',
          href: href({ tab: 'manage', object: x.object, sub: 'associations', view: 'table' }),
        },
      ];
    if (x.category === 'Pipeline')
      return [
        lock({
          label: 'Manage pipelines',
          href: `/settings/objects?object=${encodeURIComponent(x.object)}&tab=pipelines`,
        }),
      ];
    return [
      {
        label: 'Manage object',
        href: href({ tab: 'manage', object: x.object, sub: 'properties' }),
      },
      lock({
        label: 'Object settings',
        href: `/settings/objects?object=${encodeURIComponent(x.object)}`,
      }),
    ];
  };

  const list = filtered();
  const any = cat.length || issue.length || obj.length || sev.length;
  const toggle = (
    <div className="dm-viewby">
      <span>View by:</span>
      <div className="dm-seg" role="group">
        <button
          type="button"
          className={cn(view === 'severity' && 'is-active')}
          aria-pressed={view === 'severity'}
          onClick={() => setView('severity')}
        >
          Severity
        </button>
        <button
          type="button"
          className={cn(view === 'object' && 'is-active')}
          aria-pressed={view === 'object'}
          onClick={() => setView('object')}
        >
          Object
        </button>
      </div>
    </div>
  );

  const objectRows = Object.values(
    issues.reduce<
      Record<string, { key: string; label: string; total: number } & Record<IssueCategory, number>>
    >((acc, x) => {
      const r = (acc[x.object] ??= {
        key: x.object,
        label: objName(x.object),
        total: 0,
        Object: 0,
        Property: 0,
        Association: 0,
        Pipeline: 0,
      });
      r.total++;
      r[x.category]++;
      return acc;
    }, {}),
  ).filter((r) => !osearch || r.label.toLowerCase().includes(osearch.toLowerCase()));

  const cnt = (r: (typeof objectRows)[number], k: IssueCategory) =>
    r[k] ? (
      <button
        type="button"
        className="dm-num-link"
        onClick={() => jump({ obj: [r.key], cat: [k] })}
      >
        {r[k]}
      </button>
    ) : (
      '0'
    );

  return (
    <>
      <section className="dm-card dm-hsum">
        <div className="dm-hsum__intro">
          <h2>Health Check Results Summary</h2>
          <p>Find and fix the gaps between how your business runs and how CRM models it today.</p>
        </div>
        <div className="dm-hsum__col">
          <p className="dm-hsum__label">Open issues</p>
          <div className="dm-hsum__counts">
            {SEVERITIES.map((s) => (
              <button
                key={s}
                type="button"
                className="dm-hsum__count"
                onClick={() => jump({ sev: [s] })}
              >
                <b>{bySev[s] ?? 0}</b>
                <span>
                  <i className={`dm-dot dm-dot--${s.toLowerCase()}`} />
                  {s}
                </span>
              </button>
            ))}
          </div>
        </div>
        <div className="dm-hsum__col">
          <p className="dm-hsum__label">Highest severity objects</p>
          <ul className="dm-hsum__top">
            {top.map((k) => (
              <li key={k}>
                <button
                  type="button"
                  className="dm-link-strong"
                  onClick={() => jump({ obj: [k], sev: ['High'] })}
                >
                  {objName(k)}
                </button>
                <span>
                  <i className="dm-dot dm-dot--high" />
                  {high[k]} High
                </span>
              </li>
            ))}
            {!top.length && <li className="dm-muted">No high severity issues</li>}
          </ul>
        </div>
        <div className="dm-hsum__run">
          <button
            type="button"
            className={cn('dm-btn dm-btn--primary', running && 'is-loading')}
            disabled={running}
            onClick={() => void rerun()}
          >
            <DmIcon name="refresh" />
            Re-run health check
          </button>
          <p>Last run on {lastRunText(lastRun, timeZone)}</p>
        </div>
      </section>

      <section ref={listRef} className="dm-card dm-hlist">
        {view === 'object' ? (
          <>
            <div className="dm-hlist__head">
              <h3>{objectsWithIssuesText(objectRows.length)}</h3>
              {toggle}
            </div>
            {/* A3: the design's two-row toolbar, in both views (data-model.js:6077-6091). */}
            <div className="dm-toolbar dm-toolbar--rows">
              <div className="dm-toolbar__top">
                <SearchBox value={osearch} onChange={setOsearch} placeholder="Search object" wide />
              </div>
            </div>
            {/* Keyed per view: otherwise React keeps the other table's sort column. */}
            <DataTable
              key="object"
              rows={objectRows}
              rowKey={(r) => r.key}
              sortKey="total"
              sortDir={-1}
              size={20}
              empty="No objects with issues."
              cols={[
                {
                  key: 'label',
                  label: 'Object name',
                  sort: true,
                  render: (r) => (
                    <span className="dm-obj">
                      <DmIcon name={object(r.key)?.icon ?? 'grid'} size={14} />
                      {r.label}
                    </span>
                  ),
                },
                {
                  key: 'total',
                  label: 'Number of issues',
                  sort: true,
                  render: (r) => (
                    <span className="dm-issue-chip">
                      <DmIcon name="alert" size={13} />
                      {openIssuesText(r.total)}
                    </span>
                  ),
                },
                {
                  key: 'Object',
                  label: 'Configuration issues',
                  sort: true,
                  render: (r) => cnt(r, 'Object'),
                },
                {
                  key: 'Property',
                  label: 'Property issues',
                  sort: true,
                  render: (r) => cnt(r, 'Property'),
                },
                {
                  key: 'Association',
                  label: 'Association issues',
                  sort: true,
                  render: (r) => cnt(r, 'Association'),
                },
                {
                  key: 'Pipeline',
                  label: 'Pipeline or lifecycle issues',
                  sort: true,
                  render: (r) => cnt(r, 'Pipeline'),
                },
              ]}
            />
          </>
        ) : (
          <>
            <div className="dm-hlist__head">
              <h3>{issuesShownText(list.length)}</h3>
              {toggle}
            </div>
            <div className="dm-toolbar dm-toolbar--rows">
              <div className="dm-toolbar__top">
                <SearchBox value={search} onChange={setSearch} placeholder="Search issues" />
                <span className="dm-grow" />
              </div>
              <div className="dm-toolbar__filters">
                {(() => {
                  const c = counts(filtered('cat'), (x) => x.category);
                  return (
                    <CheckFilter
                      label={filterLabel('Category', cat, c)}
                      options={CATEGORIES.filter((k) => c[k] || cat.includes(k)).map((k) => ({
                        value: k,
                        label: k,
                        count: c[k] ?? 0,
                      }))}
                      selected={cat}
                      onChange={setCat}
                    />
                  );
                })()}
                {(() => {
                  // A2: options by count, most first, then by name; chosen ones stay listed.
                  const c = counts(filtered('issue'), (x) => x.issue);
                  const keys = [...new Set([...Object.keys(c), ...issue])].sort(
                    (a, b) => (c[b] ?? 0) - (c[a] ?? 0) || byText(a, b),
                  );
                  return (
                    <CheckFilter
                      label={filterLabel('Issue', issue, c)}
                      options={keys.map((k) => ({ value: k, label: k, count: c[k] ?? 0 }))}
                      selected={issue}
                      onChange={setIssue}
                      search
                      wide
                    />
                  );
                })()}
                {(() => {
                  const c = counts(filtered('obj'), (x) => x.object);
                  const keys = [...new Set([...Object.keys(c), ...obj])].sort((a, b) =>
                    byText(objName(a), objName(b)),
                  );
                  return (
                    <CheckFilter
                      label={filterLabel('Object', obj, c, objName)}
                      options={keys.map((k) => ({ value: k, label: objName(k), count: c[k] ?? 0 }))}
                      selected={obj}
                      onChange={setObj}
                      search
                    />
                  );
                })()}
                {(() => {
                  const c = counts(filtered('sev'), (x) => x.severity);
                  return (
                    <CheckFilter
                      label={filterLabel('Severity', sev, c)}
                      options={SEVERITIES.filter((k) => c[k] || sev.includes(k)).map((k) => ({
                        value: k,
                        label: k,
                        count: c[k] ?? 0,
                      }))}
                      selected={sev}
                      onChange={setSev}
                    />
                  );
                })()}
                {any ? (
                  <button type="button" className="dm-link-strong" onClick={() => jump({})}>
                    Clear filters
                  </button>
                ) : null}
              </div>
            </div>
            <DataTable
              key="property"
              rows={list}
              rowKey={(x) => x.id}
              sortKey="severity"
              sortDir={-1}
              size={20}
              sizes={[20, 50, 100]}
              wrapCls="dm-table-wrap--x"
              empty={
                issues.length
                  ? 'No issues match your filters.'
                  : 'No issues found. Your data model looks healthy.'
              }
              cols={[
                {
                  key: 'severity',
                  label: 'Severity',
                  sort: true,
                  width: '110px',
                  val: (x) => SEV_RANK[x.severity],
                  render: (x) => (
                    <span className="dm-sev">
                      <i className={`dm-dot dm-dot--${x.severity.toLowerCase()}`} />
                      {x.severity}
                    </span>
                  ),
                },
                { key: 'category', label: 'Category', sort: true },
                {
                  key: 'object',
                  label: 'Object',
                  sort: true,
                  val: (x) => objSingular(x.object),
                  render: (x) =>
                    object(x.object)?.active ? (
                      <Link
                        className="dm-link-strong dm-obj"
                        href={href({ tab: 'manage', object: x.object, sub: 'properties' })}
                      >
                        <DmIcon name={object(x.object)!.icon} size={14} />
                        {objSingular(x.object)}
                      </Link>
                    ) : (
                      objSingular(x.object)
                    ),
                },
                {
                  key: 'item',
                  label: 'Affected item',
                  sort: true,
                  render: (x) => (
                    <span className="dm-row-hover">
                      <span className="dm-ellipsis" title={x.item}>
                        {x.item}
                      </span>
                      <ActionMenu
                        label={
                          <>
                            Actions
                            <DmIcon name="caret" size={14} />
                          </>
                        }
                        btnClass="dm-btn dm-btn--outline dm-btn--xxs dm-row-hover__btn"
                        items={actions(x)}
                      />
                    </span>
                  ),
                },
                {
                  key: 'issue',
                  label: 'Issue',
                  sort: true,
                  render: (x) => (
                    <span className="dm-issue-chip">
                      <DmIcon name="alert" size={13} />
                      {x.issue}
                    </span>
                  ),
                },
                {
                  key: 'details',
                  label: 'Details',
                  render: (x) => <span className="dm-details">{x.details}</span>,
                },
              ]}
            />
          </>
        )}
      </section>
      {archiving && (
        <Modal
          title="Archive property?"
          okLabel="Archive"
          danger
          onClose={() => setArchiving(null)}
          onOk={async () => {
            try {
              await archiveCustomProperty(archiving.id);
              toast(`Property "${archiving.label}" archived`, 'success');
              await reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <p className="dm-muted">
            <b>{archiving.label}</b> will be hidden from records, forms and filters, and becomes
            read-only. Its values are kept, and it can be restored from Property settings.
          </p>
        </Modal>
      )}
    </>
  );
}
