'use client';

import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { listDashboards } from '@/features/reports/api.client';
import { listReports } from '@/features/saved-reports/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  listRecentSalesReports,
  listSalesReports,
  markSalesReportViewed,
  runSalesReport,
  type SalesDesignGroup,
  type SalesReportInfo,
} from '../api.client';
import {
  DESIGN_GROUPS,
  defaultRange,
  designGroupOf,
  isListedReport,
  reportTabs,
} from '../constants';
import { parseIsoDate, rangeBounds } from '../ranges';
import { SaCaret, SaIcon } from './icons';
import { MenuPop } from './layers';
import { ReportView, initialReportState, type ReportState } from './ReportView';
import { SalesHome, type CardResult } from './SalesHome';

/**
 * Sales › Sales Analytics (HUB-713, 13 / 17 Nov design sales-analytics.html): the Sales analytics
 * suite. Home (quick answers, recently viewed, suggested, ready-made report cards), a group page
 * (`?group=`) and a report (`?report=<key>`, with `from`, `to`, `ownerId`, `teamId`, `pipelineId`
 * and `compare` as a saved sales report links to it). Every report comes from the catalogue.
 */

const RECENT_KEY = 'crm.sa.recent';

function readLocalRecent(): string[] {
  try {
    const v = JSON.parse(localStorage.getItem(RECENT_KEY) ?? 'null');
    return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [];
  } catch {
    return [];
  }
}

function writeLocalRecent(keys: string[]) {
  try {
    localStorage.setItem(RECENT_KEY, JSON.stringify(keys));
  } catch {
    /* private window */
  }
}

const isGroup = (g: string | null): g is SalesDesignGroup => DESIGN_GROUPS.some((x) => x.key === g);

export function SalesAnalyticsView() {
  const params = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const reportKey = params.get('report');
  const groupKey = params.get('group');

  const [catalog, setCatalog] = useState<SalesReportInfo[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [cards, setCards] = useState<Record<string, CardResult>>({});
  const [recent, setRecent] = useState<string[]>([]);
  const [states, setStates] = useState<Record<string, ReportState>>({});
  const [q, setQ] = useState('');
  const [open, setOpen] = useState<Record<string, boolean>>({ sales: true });
  const [navOpen, setNavOpen] = useState(false);
  const [createBtn, setCreateBtn] = useState<HTMLElement | null>(null);
  const [counts, setCounts] = useState<{ dashboards?: number; reports?: number }>({});
  const [favorites, setFavorites] = useState<{ id: string; name: string }[]>([]);
  const searchRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    listSalesReports().then(setCatalog, (err: unknown) => setError(errorText(err)));
    listRecentSalesReports().then(setRecent, () => setRecent(readLocalRecent()));
    listDashboards().then(
      (d) => setCounts((c) => ({ ...c, dashboards: d.length })),
      () => undefined,
    );
    listReports({ limit: 1 }).then(
      (r) => setCounts((c) => ({ ...c, reports: r.total })),
      () => undefined,
    );
    listReports({ view: 'favorites', limit: 5 }).then(
      (r) => setFavorites(r.data.map((x) => ({ id: x.id, name: x.name }))),
      () => undefined,
    );
  }, []);

  // Each card's figure for its own default range, against the previous period.
  useEffect(() => {
    if (!catalog) return;
    const ctrl = new AbortController();
    // LP9: a second tab has no card of its own.
    for (const info of catalog.filter(isListedReport)) {
      runSalesReport(
        info.key,
        { ...rangeBounds(defaultRange(info.key)), compare: 'previous_period' },
        { signal: ctrl.signal },
      ).then(
        (r) => setCards((cur) => ({ ...cur, [info.key]: r })),
        (err: unknown) => {
          if (!ctrl.signal.aborted) setCards((cur) => ({ ...cur, [info.key]: errorText(err) }));
        },
      );
    }
    return () => ctrl.abort();
  }, [catalog]);

  const byKey = useMemo(() => new Map((catalog ?? []).map((r) => [r.key, r])), [catalog]);
  const info = reportKey ? byKey.get(reportKey) : undefined;

  // A report opened from a link (a saved sales report): its period and filters from the URL.
  const linkState = useMemo((): Partial<ReportState> | null => {
    if (!reportKey) return null;
    const from = params.get('from');
    const to = params.get('to');
    const out: Partial<ReportState> = {};
    if (parseIsoDate(from) && parseIsoDate(to)) {
      out.range = { key: 'custom', from: from!, to: to! };
    }
    for (const k of ['ownerId', 'teamId', 'pipelineId'] as const) {
      const v = params.get(k);
      if (v) out[k] = v;
    }
    if (params.get('compare') === 'previous_period') out.compare = true;
    return Object.keys(out).length ? out : null;
  }, [params, reportKey]);

  // Recently viewed: told to the API when a report opens.
  const lastMarked = useRef<string | null>(null);
  useEffect(() => {
    if (!info) {
      lastMarked.current = null;
      return;
    }
    if (lastMarked.current === info.key) return;
    lastMarked.current = info.key;
    setRecent((cur) => {
      const next = [info.key, ...cur.filter((k) => k !== info.key)].slice(0, 10);
      writeLocalRecent(next);
      return next;
    });
    markSalesReportViewed(info.key).catch(() => undefined);
    setOpen((o) => ({ ...o, sales: true, [designGroupOf(info)]: true }));
  }, [info]);

  const stateOf = (r: SalesReportInfo): ReportState =>
    states[r.key] ?? { ...initialReportState(r), ...(linkState ?? {}) };
  const setStateOf = useCallback(
    (key: string, next: ReportState) => setStates((s) => ({ ...s, [key]: next })),
    [],
  );

  const go = (query: string) => {
    setNavOpen(false);
    router.push(query ? `${pathname}?${query}` : pathname);
  };
  const openReport = (key: string) => go(`report=${encodeURIComponent(key)}`);
  const openGroup = (g: SalesDesignGroup) => {
    setOpen((o) => ({ ...o, sales: true, [g]: true }));
    go(`group=${g}`);
  };

  useEffect(() => {
    if (!navOpen) return;
    searchRef.current?.focus();
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setNavOpen(false);
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [navOpen]);

  const needle = q.trim().toLowerCase();
  const currentGroup = info ? designGroupOf(info) : isGroup(groupKey) ? groupKey : null;

  const nav = (
    <>
      <label className="sa-search">
        <span className="sa-sr">Search reports</span>
        <SaIcon name="search" />
        <input
          ref={searchRef}
          type="search"
          placeholder="Search"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
      </label>
      <Link className="sa-nav__it" href="/reports/dashboards">
        My dashboards
        {counts.dashboards !== undefined ? (
          <span className="sa-count">{counts.dashboards}</span>
        ) : null}
      </Link>
      <Link className="sa-nav__it" href="/reports/library">
        My reports
        {counts.reports !== undefined ? <span className="sa-count">{counts.reports}</span> : null}
      </Link>
      {favorites.length ? (
        <>
          <h2 className="sa-nav__h">Favorites</h2>
          {favorites.map((f) => (
            <Link key={f.id} className="sa-nav__it sa-nav__fav" href={`/reports/library/${f.id}`}>
              <SaIcon name="table" className="sa-i--sm" />
              <span>{f.name}</span>
            </Link>
          ))}
        </>
      ) : null}
      <h2 className="sa-nav__h">Analytics suites</h2>
      {needle ? (
        (() => {
          const hits = (catalog ?? [])
            .filter(isListedReport)
            .filter((r) => r.title.toLowerCase().includes(needle));
          return hits.length ? (
            <ul className="sa-tree">
              {hits.map((r) => (
                <li key={r.key}>
                  <button type="button" className="sa-tree__rep" onClick={() => openReport(r.key)}>
                    {r.title}
                  </button>
                </li>
              ))}
            </ul>
          ) : (
            <p className="sa-muted sa-nav__none">No reports match &quot;{q.trim()}&quot;.</p>
          );
        })()
      ) : (
        <ul className="sa-tree">
          <li>
            <button
              type="button"
              className={cn('sa-tree__node', !reportKey && !currentGroup && 'is-cur')}
              aria-expanded={Boolean(open.sales)}
              onClick={(e) => {
                const onChev = (e.target as Element).closest('svg');
                if (onChev || (!reportKey && !currentGroup)) {
                  setOpen((o) => ({ ...o, sales: !o.sales }));
                } else go('');
              }}
            >
              <SaIcon name={open.sales ? 'down' : 'right'} className="sa-i--sm" />
              <span>Sales</span>
            </button>
            {open.sales ? (
              <ul className="sa-tree sa-tree--sub">
                {DESIGN_GROUPS.map((g) => {
                  const kids = (catalog ?? [])
                    .filter(isListedReport)
                    .filter((r) => designGroupOf(r) === g.key);
                  const isOpen = Boolean(open[g.key]);
                  const here = !reportKey && currentGroup === g.key;
                  return (
                    <li key={g.key}>
                      <button
                        type="button"
                        className={cn('sa-tree__node', here && 'is-cur')}
                        aria-expanded={isOpen}
                        onClick={(e) => {
                          const onChev = (e.target as Element).closest('svg');
                          if (onChev || here) setOpen((o) => ({ ...o, [g.key]: !o[g.key] }));
                          else openGroup(g.key);
                        }}
                      >
                        <SaIcon name={isOpen ? 'down' : 'right'} className="sa-i--sm" />
                        <span>{g.label}</span>
                      </button>
                      {isOpen ? (
                        <ul className="sa-tree sa-tree--sub">
                          {kids.map((r) => (
                            <li key={r.key}>
                              <button
                                type="button"
                                className="sa-tree__rep"
                                aria-current={reportKey === r.key ? 'page' : undefined}
                                onClick={() => openReport(r.key)}
                              >
                                {r.title}
                              </button>
                            </li>
                          ))}
                        </ul>
                      ) : null}
                    </li>
                  );
                })}
              </ul>
            ) : null}
          </li>
        </ul>
      )}
    </>
  );

  let main: React.ReactNode;
  if (error) {
    main = (
      <p className="sa-muted" role="alert">
        The reports could not be loaded: {error}
      </p>
    );
  } else if (!catalog) {
    main = <p className="sa-muted">Loading reports…</p>;
  } else if (reportKey) {
    main = info ? (
      <ReportView
        key={info.key}
        info={info}
        state={stateOf(info)}
        onState={(next) => setStateOf(info.key, next)}
        onHome={() => go('')}
        onGroup={openGroup}
        tabs={reportTabs(catalog, info)}
        // LP9: as the design's tab click (sales-analytics.js:5715-5717), in place; each tab keeps
        // its own settings.
        onTab={(key) => router.replace(`${pathname}?report=${encodeURIComponent(key)}`)}
      />
    ) : (
      <p className="sa-muted">This report doesn&apos;t exist.</p>
    );
  } else {
    main = (
      <SalesHome
        catalog={catalog}
        cards={cards}
        recent={recent}
        group={isGroup(groupKey) ? groupKey : null}
        search={needle}
        onOpen={openReport}
        onHome={() => go('')}
      />
    );
  }

  return (
    <div className={cn('sa', navOpen && 'is-nav')}>
      <header className="sa-head">
        <h1 className="sa-head__t">Reports</h1>
        <div className="sa-head__acts">
          <button
            type="button"
            className="sa-btn sa-btn--icon sa-navtoggle"
            aria-controls="saNav"
            aria-expanded={navOpen}
            aria-label="Show report navigation"
            onClick={() => setNavOpen((v) => !v)}
          >
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path
                d="M4 6h16M4 12h16M4 18h10"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
              />
            </svg>
          </button>
          <button
            type="button"
            className="sa-btn sa-btn--primary"
            aria-haspopup="menu"
            aria-expanded={Boolean(createBtn)}
            onClick={(e) => setCreateBtn(createBtn ? null : e.currentTarget)}
          >
            Create
            <SaCaret />
          </button>
        </div>
      </header>
      <div className="sa-body">
        <div className="sa-navov" hidden={!navOpen} onClick={() => setNavOpen(false)} />
        <nav className="sa-nav" id="saNav" aria-label="Reports navigation">
          {nav}
        </nav>
        <main className="sa-main sa-main-div" tabIndex={-1}>
          {main}
        </main>
      </div>
      <MenuPop
        anchor={createBtn}
        onClose={() => setCreateBtn(null)}
        items={[
          { label: 'Create dashboard', href: '/reports/dashboards' },
          { label: 'Create report', href: '/reports/library/new?returnTo=/sales-analytics' },
        ]}
      />
    </div>
  );
}
