'use client';

import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  fitRange,
  lastAllowedDay,
  monthCells,
  parseMdy,
  presetRange,
  RANGE_PRESETS,
  toMdy,
  type DayRange,
} from '../analysisRange';
import { utcOffsetText } from '../zoneText';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { listRecordChanges, type RecordChangeAction, type RecordChangeCount } from '../api.client';
import { byText, fmt } from '../model';
import { useDm } from './DataModelView';
import { DmIcon } from './icons';
import { CheckFilter, DataTable, Dropdown, Tip } from './primitives';
import { nameInText } from '@/features/objects/paths';

const COLORS = [
  '#f2994a',
  '#2bb6a3',
  '#9b8afb',
  '#f2c94c',
  '#f08cc6',
  '#6fa8f5',
  '#7bc67e',
  '#e57373',
  '#a1887f',
  '#90a4ae',
];

const ACTIONS: Array<[RecordChangeAction, string, string]> = [
  ['all', 'All Actions', 'changes'],
  ['create', 'Create', 'creates'],
  ['delete', 'Delete', 'deletes'],
  ['update', 'Update', 'updates'],
  ['merge', 'Merge', 'merges'],
];

/**
 * The design's source types, in its order, then this CRM's own (CRM UI edits and forms). Types
 * with no events yet are still offered, with nothing charted.
 */
const SOURCE_LABEL: Record<string, string> = {
  crm_setting: 'CRM Setting',
  bulk_action: 'CRM UI Bulk Action',
  enrichment: 'Data Enrichment',
  email: 'Email Activity',
  ai: 'AI',
  calculation: 'Calculation',
  import: 'Import',
  integration: 'Integration',
  sales: 'Sales Processing',
  workflow: 'Workflow',
  manual: 'CRM UI',
  form: 'Forms',
};
const KNOWN_SOURCES = Object.keys(SOURCE_LABEL);
/** The CRM events' sources counted under one of the design's types. */
const SOURCE_TYPE: Record<string, string> = {
  system: 'calculation',
  sequence: 'sales',
  api: 'integration',
  webhook: 'integration',
};
const sourceType = (source: string) => SOURCE_TYPE[source] ?? source;
const sourceLabel = (s: string) =>
  SOURCE_LABEL[s] ?? s.charAt(0).toUpperCase() + s.slice(1).replace(/_/g, ' ');
/** The chart reads at most this many source types at once. */
const MAX_SOURCES = 10;
/** The API answers at most this many days at once. */
const MAX_DAYS = 366;

const iso = (d: Date) =>
  `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
const parse = (s: string) => {
  const [y, m, d] = s.split('-').map(Number);
  return new Date(y!, m! - 1, d!);
};
/** YYYY-MM-DD as MM/DD/YYYY, the design's format (chart axis and date range alike). */
const mdy = (s: string) => `${s.slice(5, 7)}/${s.slice(8, 10)}/${s.slice(0, 4)}`;

/**
 * A12 (DMG2): the design's date range, "same UI as Sequences > Analyze" (data-model.js:6247-6250,
 * 6320-6450): one button showing both ends; its popover has From and To boxes (MM/DD/YYYY, Enter
 * commits), the twelve presets, a month calendar and Clear. Days after `last` can't be picked
 * (DM558B); a preset reaching past it is cut there.
 */
function RangePicker({
  range,
  last,
  onApply,
}: {
  range: DayRange;
  last: string;
  onApply: (r: DayRange) => void;
}) {
  return (
    <Dropdown
      className="dm-dr"
      btnClass="dm-dr__btn"
      menuClass="dm-pop dm-pop--dp"
      role="dialog"
      ariaLabel={`Date range, ${toMdy(range.from)} to ${toMdy(range.to)}`}
      label={
        <>
          <span className="dm-date">
            <DmIcon name="calendar" size={14} />
            <span>{toMdy(range.from) || 'MM/DD/YYYY'}</span>
          </span>
          <span className="dm-muted">to</span>
          <span className="dm-date">
            <DmIcon name="calendar" size={14} />
            <span>{toMdy(range.to) || 'MM/DD/YYYY'}</span>
          </span>
        </>
      }
    >
      {(close) => (
        <RangePanel
          range={range}
          last={last}
          onApply={(r, done) => {
            onApply(r);
            if (done) close();
          }}
        />
      )}
    </Dropdown>
  );
}

function RangePanel({
  range,
  last,
  onApply,
}: {
  range: DayRange;
  last: string;
  /** `done`: close the popover too (a preset, or Enter with both ends). */
  onApply: (r: DayRange, done: boolean) => void;
}) {
  const [from, setFrom] = useState(range.from);
  const [to, setTo] = useState(range.to);
  const [active, setActive] = useState<'from' | 'to'>('from');
  const base = parse(range.to || last);
  const [view, setView] = useState({ y: base.getFullYear(), m: base.getMonth() });
  const [text, setText] = useState({ from: toMdy(range.from), to: toMdy(range.to) });
  const [bad, setBad] = useState<'from' | 'to' | null>(null);
  const today = iso(shift(0));
  /** The design's dpSet: a start after the end swaps them (data-model.js:6406). */
  const set = (a: string, b: string) => {
    const r = a && b && a > b ? { from: b, to: a } : { from: a, to: b };
    setFrom(r.from);
    setTo(r.to);
    setText({ from: toMdy(r.from), to: toMdy(r.to) });
    return r;
  };
  const pick = (day: string) => {
    if (active === 'from') {
      set(day, to && to >= day ? to : '');
      setActive('to');
    } else {
      const r = set(from || day, day);
      setActive('from');
      if (r.from && r.to) onApply(r, false);
    }
  };
  const commit = (end: 'from' | 'to') => {
    const v = parseMdy(text[end]);
    if (v === null) {
      setBad(end);
      return;
    }
    setBad(null);
    const r = set(end === 'from' ? v : from, end === 'to' ? v : to);
    if (v) setView({ y: +v.slice(0, 4), m: +v.slice(5, 7) - 1 });
    if (end === 'from') setActive('to');
    else if (r.from && r.to) onApply(r, true);
  };
  const title = new Date(view.y, view.m, 1).toLocaleDateString('en-US', {
    month: 'long',
    year: 'numeric',
  });
  const move = (n: number) => {
    const d = new Date(view.y, view.m + n, 1);
    setView({ y: d.getFullYear(), m: d.getMonth() });
  };
  const box = (end: 'from' | 'to', label: string) => (
    <label className={cn('seq-dp__input', active === end && 'is-active')}>
      <DmIcon name="calendar" size={16} />
      <span className="crm-visually-hidden">{label}</span>
      <input
        type="text"
        inputMode="numeric"
        placeholder="MM/DD/YYYY"
        value={text[end]}
        aria-invalid={bad === end || undefined}
        title={bad === end ? 'Use MM/DD/YYYY' : undefined}
        autoFocus={end === 'from'}
        onFocus={() => setActive(end)}
        onChange={(e) => setText((t) => ({ ...t, [end]: e.target.value }))}
        onKeyDown={(e) => {
          if (e.key !== 'Enter') return;
          e.preventDefault();
          commit(end);
        }}
      />
    </label>
  );
  return (
    <div className="seq-dp">
      <div className="seq-dp__inputs">
        {box('from', 'From')}
        {box('to', 'To')}
      </div>
      <div className="seq-dp__body">
        <div className="seq-dp__presets">
          {RANGE_PRESETS.map(([key, label]) => (
            <button
              key={key}
              type="button"
              className="seq-dp__preset"
              onClick={() => onApply(fitRange(presetRange(key, new Date()), last), true)}
            >
              {label}
            </button>
          ))}
        </div>
        <div className="seq-dp__cal">
          <div className="seq-dp__head">
            <button
              type="button"
              className="seq-dp__nav"
              aria-label="Previous month"
              onClick={() => move(-1)}
            >
              &lsaquo;
            </button>
            <strong aria-live="polite">{title}</strong>
            <button
              type="button"
              className="seq-dp__nav"
              aria-label="Next month"
              onClick={() => move(1)}
            >
              &rsaquo;
            </button>
          </div>
          <div className="seq-dp__grid" role="group" aria-label={title}>
            {['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((w) => (
              <span key={w} className="seq-dp__wd">
                {w}
              </span>
            ))}
            {monthCells(view.y, view.m).map(({ day, out }) => {
              const sel = day === from || day === to;
              return (
                <button
                  key={day}
                  type="button"
                  className={cn(
                    'seq-dp__day',
                    out && 'is-out',
                    sel && 'is-sel',
                    from && to && day > from && day < to && 'is-range',
                    day === today && 'is-today',
                  )}
                  aria-pressed={sel}
                  disabled={day > last}
                  onClick={() => pick(day)}
                >
                  {+day.slice(8, 10)}
                </button>
              );
            })}
          </div>
          <button
            type="button"
            className="seq-dp__clear"
            onClick={() => {
              set('', '');
              setActive('from');
            }}
          >
            Clear
          </button>
        </div>
      </div>
    </div>
  );
}

function shift(days: number) {
  const d = new Date();
  d.setHours(0, 0, 0, 0);
  d.setDate(d.getDate() + days);
  return d;
}

function niceMax(v: number) {
  const p = Math.pow(10, Math.floor(Math.log10(v)));
  const n = v / p;
  return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * p;
}
const short = (v: number) =>
  v >= 1e6 ? `${v / 1e6}M` : v >= 1000 ? `${v / 1000}K` : String(Math.round(v));

interface Series {
  name: string;
  color: string;
  values: number[];
}

/** Area chart with a hover cursor and tooltip (chart() of data-model.js). */
function Chart({ days, series, ylabel }: { days: string[]; series: Series[]; ylabel: string }) {
  const ref = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(900);
  const [hover, setHover] = useState<{ i: number; left: number } | null>(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const ro = new ResizeObserver(() => setWidth(Math.max(280, el.clientWidth || 900)));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  if (!days.length) {
    return (
      <div className="dm-chart" ref={ref}>
        <div className="dm-empty dm-empty--sm">
          <p>Choose a valid date range.</p>
        </div>
      </div>
    );
  }
  const W = width;
  const narrow = W < 560;
  const H = narrow ? 280 : 340;
  const L = narrow ? 52 : 70;
  const R = narrow ? 10 : 20;
  const T = 16;
  const B = 56;
  const max = Math.max(0, ...series.flatMap((s) => s.values));
  const nice = niceMax(max || 10);
  const x = (i: number) =>
    L + (days.length > 1 ? (i * (W - L - R)) / (days.length - 1) : (W - L - R) / 2);
  const y = (v: number) => T + (H - T - B) * (1 - v / nice);
  const every = Math.max(
    1,
    Math.ceil(days.length / Math.max(2, Math.min(9, Math.floor((W - L - R) / 86)))),
  );

  return (
    <div className="dm-chart" ref={ref}>
      <svg
        viewBox={`0 0 ${W} ${H}`}
        width="100%"
        height={H}
        role="img"
        aria-label={`${ylabel} by date`}
      >
        {[0, 1, 2, 3, 4, 5].map((g) => {
          const gv = (nice / 5) * g;
          return (
            <g key={g}>
              <line
                x1={L}
                x2={W - R}
                y1={y(gv)}
                y2={y(gv)}
                className={cn('dm-chart__grid', g === 0 && 'is-base')}
              />
              <text x={L - 10} y={y(gv) + 4} className="dm-chart__ytick" textAnchor="end">
                {short(gv)}
              </text>
            </g>
          );
        })}
        {days.map((d, i) =>
          i % every ? null : (
            <text key={d} x={x(i)} y={H - B + 18} className="dm-chart__xtick" textAnchor="middle">
              {mdy(d)}
            </text>
          ),
        )}
        <text x={(W + L) / 2} y={H - 8} className="dm-chart__axis" textAnchor="middle">
          Date
        </text>
        <text
          transform={`translate(16 ${(H - B + T) / 2}) rotate(-90)`}
          className="dm-chart__axis"
          textAnchor="middle"
        >
          {ylabel}
        </text>
        {series.map((s) => {
          const pts = s.values.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`);
          return (
            <g key={s.name}>
              <path
                d={`M${x(0)},${y(0)}L${pts.join('L')}L${x(days.length - 1)},${y(0)}Z`}
                fill={s.color}
                opacity=".22"
              />
              <path d={`M${pts.join('L')}`} fill="none" stroke={s.color} strokeWidth="1.8" />
              {days.length <= 120 &&
                s.values.map((v, i) => (
                  <circle
                    key={i}
                    cx={x(i).toFixed(1)}
                    cy={y(v).toFixed(1)}
                    r="2.6"
                    fill="var(--surface)"
                    stroke={s.color}
                    strokeWidth="1.4"
                  />
                ))}
            </g>
          );
        })}
        {hover && (
          <line className="dm-chart__cursor" x1={x(hover.i)} x2={x(hover.i)} y1={T} y2={H - B} />
        )}
        <rect
          x={L}
          y={T}
          width={W - L - R}
          height={H - T - B}
          fill="transparent"
          onMouseMove={(e) => {
            const r = (e.currentTarget.ownerSVGElement as SVGSVGElement).getBoundingClientRect();
            const px = ((e.clientX - r.left) * W) / r.width;
            const i = Math.max(
              0,
              Math.min(
                days.length - 1,
                Math.round((px - L) / ((W - L - R) / Math.max(1, days.length - 1))),
              ),
            );
            setHover({ i, left: (x(i) * r.width) / W });
          }}
          onMouseLeave={() => setHover(null)}
        />
      </svg>
      {hover && (
        <div
          className="dm-chart__tip"
          style={{
            left: hover.left + 14 + 210 > width ? hover.left - 224 : hover.left + 14,
            top: 20,
          }}
        >
          <b>
            {parse(days[hover.i]!).toLocaleDateString('en-US', {
              month: 'short',
              day: 'numeric',
              year: 'numeric',
            })}
          </b>
          {series.map((s) => (
            <span key={s.name}>
              <i style={{ background: s.color }} />
              {s.name}
              <em>{fmt(s.values[hover.i] ?? 0)}</em>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

/**
 * Analysis: daily changes to one object's records broken down by source (CRM UI, import,
 * workflow…), counted from the CRM events by UTC day (GET /record-changes/daily).
 */
export function AnalysisTab() {
  const { model } = useDm();
  const objects = useMemo(
    () =>
      model.objects
        .filter((o) => o.active && !o.catalog && !o.activity)
        .sort((a, b) => byText(a.name, b.name)),
    [model.objects],
  );
  const [objectKey, setObjectKey] = useState('contact');
  const object = objects.find((o) => o.key === objectKey) ?? objects[0];
  // A14: 90 days ending yesterday, as the design (data-model.js:6199-6201).
  const [range, setRange] = useState(() => ({ from: iso(shift(-90)), to: iso(shift(-1)) }));
  const { timeZone } = useUserPrefs();
  /** A13: series hidden by clicking their legend item (data-model.js:6262, 6460). */
  const [hidden, setHidden] = useState<Set<string>>(new Set());
  // #558: a start after the end swaps (the popover's dpSet). DM558B (the user's call, 17 Nov;
  // the design accepts any day): nor after the last day, on every apply (RangePicker).
  /** Worked out on each render, so a page left open past midnight moves on. */
  const last = lastAllowedDay(new Date());
  const [action, setAction] = useState<RecordChangeAction>('update');
  const [chosen, setChosen] = useState<string[] | null>(null);
  const [rows, setRows] = useState<RecordChangeCount[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const days = useMemo(() => {
    const out: string[] = [];
    if (!range.from || !range.to || range.from > range.to) return out;
    const d = parse(range.from);
    const end = parse(range.to);
    while (d <= end && out.length <= MAX_DAYS) {
      out.push(iso(d));
      d.setDate(d.getDate() + 1);
    }
    return out;
  }, [range.from, range.to]);
  const tooLong = days.length > MAX_DAYS;

  /** A newer request wins over a slower earlier one. */
  const loadSeq = useRef(0);
  const load = useCallback(async () => {
    if (!object || !days.length || tooLong) return;
    const seq = ++loadSeq.current;
    setLoading(true);
    try {
      const next = await listRecordChanges({
        objectType: object.key,
        from: range.from,
        to: range.to,
        action,
      });
      if (seq !== loadSeq.current) return;
      setRows(next);
      setError(null);
    } catch (err) {
      if (seq === loadSeq.current) setError(errorText(err));
    } finally {
      if (seq === loadSeq.current) setLoading(false);
    }
  }, [object, days.length, tooLong, range.from, range.to, action]);

  useEffect(() => {
    void load();
  }, [load]);

  // The known source types, plus any other the events used, in a fixed order.
  const sources = useMemo(
    () => [...new Set([...KNOWN_SOURCES, ...(rows ?? []).map((r) => sourceType(r.source))])],
    [rows],
  );
  // Default: the types with the most changes in the range (ties keep the list's order).
  const top = useMemo(() => {
    const volume = new Map<string, number>();
    for (const r of rows ?? []) {
      const t = sourceType(r.source);
      volume.set(t, (volume.get(t) ?? 0) + r.count);
    }
    return [...sources]
      .sort((a, b) => (volume.get(b) ?? 0) - (volume.get(a) ?? 0))
      .slice(0, MAX_SOURCES)
      .sort((a, b) => sources.indexOf(a) - sources.indexOf(b));
  }, [rows, sources]);
  const selected = (chosen ?? top).filter((s) => sources.includes(s));

  const allSeries = useMemo<Series[]>(() => {
    const index = new Map(days.map((d, i) => [d, i]));
    // At most MAX_SOURCES charted, so each gets its own colour.
    return selected.map((source, n) => {
      const values = days.map(() => 0);
      for (const r of rows ?? []) {
        if (sourceType(r.source) !== source) continue;
        const i = index.get(r.date);
        if (i !== undefined) values[i]! += r.count;
      }
      return { name: sourceLabel(source), color: COLORS[n % COLORS.length]!, values };
    });
  }, [rows, days, selected]);

  const table = useMemo(
    () =>
      days
        .map((d, i) => {
          const r: Record<string, string | number> = { date: d };
          allSeries.forEach((s) => (r[s.name] = s.values[i] ?? 0));
          return r;
        })
        .reverse(),
    [days, allSeries],
  );

  if (!object) {
    return (
      <div className="dm-an">
        <p className="dm-muted">No objects to analyze.</p>
      </div>
    );
  }

  const [, actionLabel, actionWord] = ACTIONS.find(([k]) => k === action)!;
  const one = nameInText(object.singular);

  return (
    <div className="dm-an">
      <div className="dm-an__head">
        <Dropdown
          btnClass="dm-an__obj"
          menuClass="dm-menu dm-menu--switch"
          role="listbox"
          label={
            <>
              {object.name}
              <DmIcon name="caret" />
            </>
          }
        >
          {(close) =>
            objects.map((o) => (
              <button
                key={o.key}
                type="button"
                role="option"
                aria-selected={o.key === object.key}
                className={cn('dm-menu__item', o.key === object.key && 'is-selected')}
                onClick={() => {
                  close();
                  setObjectKey(o.key);
                }}
              >
                <DmIcon name={o.icon} size={15} />
                <span>{o.name}</span>
              </button>
            ))
          }
        </Dropdown>
      </div>
      <p className="dm-an__desc">
        View daily {actionWord} on the {object.singular} records broken down by source types, counts
        are updated daily, shown in UTC time.{' '}
        <Tip text={`Your local time is ${utcOffsetText(new Date(), timeZone)}.`} />
      </p>
      <div className="dm-an__filters">
        <span className="dm-muted">Date range:</span>
        <RangePicker range={range} last={last} onApply={(r) => setRange(fitRange(r, last))} />
        <span className="dm-pair">
          <span className="dm-muted">Action types:</span>
          <Dropdown
            btnClass="dm-filter__btn dm-filter__btn--strong"
            menuClass="dm-menu"
            label={
              <>
                <span>{actionLabel}</span>
                <DmIcon name="caret" />
              </>
            }
          >
            {(close) =>
              ACTIONS.map(([k, label]) => (
                <button
                  key={k}
                  type="button"
                  className={cn('dm-menu__item', k === action && 'is-selected')}
                  onClick={() => {
                    close();
                    setAction(k);
                  }}
                >
                  {label}
                </button>
              ))
            }
          </Dropdown>
        </span>
        <span className="dm-pair">
          <span className="dm-muted">Source types:</span>
          <CheckFilter
            label={`${selected.length} source type${selected.length === 1 ? '' : 's'}`}
            options={sources.map((src) => ({ value: src, label: sourceLabel(src) }))}
            selected={selected}
            onChange={setChosen}
            max={MAX_SOURCES}
            search
            footer={(close) => (
              <div className="dm-checks__foot">
                <button
                  type="button"
                  className="dm-btn dm-btn--outline dm-btn--xs"
                  onClick={() => {
                    setChosen(null);
                    close();
                  }}
                >
                  <DmIcon name="check" size={14} />
                  Default - top source types selected
                </button>
                <button type="button" className="dm-link-strong" onClick={() => setChosen([])}>
                  Clear all selections
                </button>
              </div>
            )}
          />
          <Tip text="By default, we choose the top 10 source types when available. You can manually choose 10 source types maximum. And you can choose top sources with one click at any time." />
        </span>
        {loading && <span className="dm-muted">Loading…</span>}
      </div>
      {tooLong && <Alert tone="warning">Choose a range of {MAX_DAYS} days or fewer.</Alert>}
      {error && <Alert tone="danger">{error}</Alert>}
      <Chart
        days={tooLong ? [] : days}
        series={allSeries.filter((x) => !hidden.has(x.name))}
        ylabel={`Count of ${one} ${actionWord}`}
      />
      <div className="dm-legend">
        {allSeries.map((s) => (
          <button
            key={s.name}
            type="button"
            className={cn('dm-legend__item', hidden.has(s.name) && 'is-off')}
            aria-pressed={!hidden.has(s.name)}
            onClick={() =>
              setHidden((cur) => {
                const next = new Set(cur);
                if (next.has(s.name)) next.delete(s.name);
                else next.add(s.name);
                return next;
              })
            }
          >
            <i style={{ background: s.color }} />
            {s.name}
          </button>
        ))}
      </div>
      <DataTable
        rows={tooLong ? [] : table}
        rowKey={(r) => String(r.date)}
        wrapCls="dm-table-wrap--x dm-table-wrap--card"
        empty="No data for this date range."
        cols={[
          {
            key: 'date',
            label: 'Date',
            sort: true,
            render: (r) =>
              parse(String(r.date)).toLocaleDateString('en-US', {
                month: 'long',
                day: 'numeric',
                year: 'numeric',
              }),
          },
          ...allSeries.map((s) => ({
            key: s.name,
            label: s.name,
            sort: true,
            render: (r: Record<string, string | number>) => fmt(Number(r[s.name] ?? 0)),
          })),
        ]}
      />
    </div>
  );
}
