'use client';

/**
 * Message templates › Analyze › View sales content analytics (HUB-721): the design's
 * sales-content-analytics.php, Templates tab, on GET /email-templates/analytics. Documents and
 * Sequences open the CRM's own pages for those. Save report keeps the choices in the report
 * library, which reopens this page with them.
 */
import Link from 'next/link';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { saveFile } from '@/features/exports/ui/ExportButton';
import { createReport, listReportTags } from '@/features/saved-reports/api.client';
import type { ReportTag } from '@/features/saved-reports/types';
import {
  SaveReportDrawer,
  type SaveReportValues,
} from '@/features/saved-reports/ui/SaveReportDrawer';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  DATE_MODES,
  ROLLING_DAYS,
  dayRange,
  percent,
  rangeChip,
  rangeSummary,
  savedReportDefinition,
  type DateMode,
  type ReportChoices,
} from '../analytics';
import {
  exportTemplateAnalyticsCsv,
  getTemplateAnalytics,
  listTemplateFolders,
  type TemplateAnalytics,
  type TemplateAnalyticsRow,
  type TemplateFolder,
} from '../api.client';

const SERIES = [
  ['sends', 'Sends', '#006061'],
  ['opens', 'Opens', '#8cccd4'],
  ['clicks', 'Clicks', '#c54593'],
  ['replies', 'Replies', '#fca9cd'],
] as const;
type SeriesKey = (typeof SERIES)[number][0];

type ColumnKey = SeriesKey | 'openRate' | 'clickRate' | 'replyRate';
const COLUMNS: Array<[ColumnKey, string]> = [
  ['sends', 'Sends'],
  ['openRate', 'Send to open rate'],
  ['opens', 'Opens'],
  ['clickRate', 'Open to click rate'],
  ['clicks', 'Clicks'],
  ['replyRate', 'Open to reply rate'],
  ['replies', 'Replies'],
];
const PAGE_SIZES = [10, 25, 50, 100];
const CHART_ROWS = 10;

type Counts = Pick<TemplateAnalyticsRow, SeriesKey>;
const cell = (r: Counts, key: ColumnKey): string =>
  key === 'openRate'
    ? percent(r.opens, r.sends)
    : key === 'clickRate'
      ? percent(r.clicks, r.opens)
      : key === 'replyRate'
        ? percent(r.replies, r.opens)
        : r[key].toLocaleString('en-US');
const sortValue = (r: Counts, key: ColumnKey): number =>
  key === 'openRate'
    ? r.opens / (r.sends || 1)
    : key === 'clickRate'
      ? r.clicks / (r.opens || 1)
      : key === 'replyRate'
        ? r.replies / (r.opens || 1)
        : r[key];

/** A design dropdown: the button and its menu, closed by a click outside or Escape. */
function Dropdown({
  trigger,
  triggerClass = 'sca-text-trigger',
  menuClass = '',
  label,
  children,
}: {
  trigger: React.ReactNode;
  triggerClass?: string;
  menuClass?: string;
  label?: string;
  children: (close: () => void) => React.ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!open) return;
    const away = (e: MouseEvent) => {
      if (!ref.current?.contains(e.target as Node)) setOpen(false);
    };
    const key = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
    document.addEventListener('mousedown', away);
    document.addEventListener('keydown', key);
    return () => {
      document.removeEventListener('mousedown', away);
      document.removeEventListener('keydown', key);
    };
  }, [open]);
  return (
    <div className="sca-control-wrap" ref={ref}>
      <button
        type="button"
        className={triggerClass}
        aria-expanded={open}
        aria-label={label}
        onClick={() => setOpen((o) => !o)}
      >
        {trigger}
      </button>
      {open ? (
        <div className={cn('sca-dropdown', menuClass)}>{children(() => setOpen(false))}</div>
      ) : null}
    </div>
  );
}

const Chevron = () => (
  <svg className="sca-chevron-icon" viewBox="0 0 12 12" aria-hidden="true" focusable="false">
    <path
      d="m2.5 4.5 3.5 3 3.5-3"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
  </svg>
);

export function SalesContentAnalyticsView({
  today,
  initial,
}: {
  today: string;
  initial: ReportChoices;
}) {
  const toast = useToast();
  const [mode, setMode] = useState<DateMode>(initial.mode);
  const [days, setDays] = useState<number>(initial.days);
  const [custom, setCustom] = useState({ from: initial.from, to: initial.to });
  const [groupBy, setGroupBy] = useState<'template' | 'user'>(initial.groupBy);
  const [folders, setFolders] = useState<TemplateFolder[]>([]);
  const [folderId, setFolderId] = useState<string | null>(initial.folderId);
  const [saving, setSaving] = useState(false);
  const [savingBusy, setSavingBusy] = useState(false);
  const [tags, setTags] = useState<ReportTag[]>([]);
  const [folderQuery, setFolderQuery] = useState('');
  const [data, setData] = useState<TemplateAnalytics | null>(null);
  const [failed, setFailed] = useState<string | null>(null);
  const [shown, setShown] = useState<SeriesKey[]>(SERIES.map(([k]) => k));
  const [columns, setColumns] = useState<ColumnKey[]>(COLUMNS.map(([k]) => k));
  const [search, setSearch] = useState('');
  const [sort, setSort] = useState<{ key: ColumnKey; dir: 1 | -1 }>({ key: 'sends', dir: -1 });
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(10);

  const range = dayRange(mode, today, days, custom);
  const backwards = Boolean(range.from && range.to && range.from > range.to);
  const query = useMemo(
    () => ({
      ...(range.from ? { from: range.from } : {}),
      ...(range.to ? { to: range.to } : {}),
      ...(folderId ? { folderId } : {}),
      groupBy,
    }),
    [range.from, range.to, folderId, groupBy],
  );

  useEffect(() => {
    listTemplateFolders().then(
      (res) => setFolders(res.data),
      () => {
        // The figures still load; only the folder filter is empty.
      },
    );
  }, []);
  useEffect(() => {
    if (backwards) return;
    let alive = true;
    setData(null);
    setFailed(null);
    setPage(1);
    getTemplateAnalytics(query).then(
      (res) => alive && setData(res),
      (err: unknown) => alive && setFailed(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [query, backwards]);

  const rows = useMemo(() => {
    const term = search.trim().toLowerCase();
    return (data?.data ?? [])
      .filter((r) => !term || r.name.toLowerCase().includes(term))
      .sort(
        (a, b) =>
          (sortValue(a, sort.key) - sortValue(b, sort.key)) * sort.dir ||
          a.name.localeCompare(b.name),
      );
  }, [data, search, sort]);
  const pages = Math.max(1, Math.ceil(rows.length / perPage));
  const current = Math.min(page, pages);
  const visible = rows.slice((current - 1) * perPage, current * perPage);
  const charted = rows.slice(0, CHART_ROWS);
  const max = Math.max(4, ...charted.flatMap((r) => shown.map((k) => r[k])));

  const noun = groupBy === 'user' ? 'User' : 'Template';
  const folderName = folderId ? (folders.find((f) => f.id === folderId)?.name ?? '') : null;
  const chip = rangeChip(mode, days);
  const filtersApplied = folderName ? 2 : 1;

  useEffect(() => {
    if (!saving) return;
    listReportTags().then(setTags, () => setTags([]));
  }, [saving]);
  const saveReport = async (values: SaveReportValues) => {
    setSavingBusy(true);
    try {
      await createReport({
        name: values.name.trim(),
        description: values.description.trim() || null,
        tagIds: values.tagIds,
        addToDashboard: values.addToDashboard,
        definition: savedReportDefinition({ mode, days, ...custom, folderId, groupBy }),
      });
      toast(`"${values.name.trim()}" saved to your reports`, 'success');
      setSaving(false);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSavingBusy(false);
    }
  };

  const exportCsv = async () => {
    try {
      saveFile(await exportTemplateAnalyticsCsv(query), `template-analytics-${today}.csv`);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const chips = (
    <>
      <span className="sca-chip" title={rangeSummary(range)}>
        {chip}
      </span>
      <span
        className="sca-chip"
        title={`Sales content type: Templates${folderName ? `; Folder: ${folderName}` : ''}`}
      >
        Filters ({filtersApplied})
      </span>
    </>
  );

  return (
    <div className="sca-page" id="salesContentAnalytics">
      <div className="sca-heading">
        <div className="sca-heading__back">
          <Link href="/templates" className="sca-back">
            ‹ Back to Templates
          </Link>
        </div>
        <div className="sca-heading__main">
          <h1>Sales Content Analytics</h1>
          <div className="sca-date-controls">
            <div className="sca-date-label">Date range:</div>
            <Dropdown
              menuClass="sca-dropdown--range"
              trigger={
                <>
                  {mode} <Chevron />
                </>
              }
            >
              {(close) =>
                DATE_MODES.map((m) => (
                  <button
                    key={m}
                    type="button"
                    className={cn(m === mode && 'is-active')}
                    onClick={() => {
                      setMode(m);
                      close();
                    }}
                  >
                    {m}
                  </button>
                ))
              }
            </Dropdown>
            {mode === 'Rolling date range' ? (
              <Dropdown
                menuClass="sca-dropdown--period"
                trigger={
                  <>
                    Last {days} days (excluding today) <Chevron />
                  </>
                }
              >
                {(close) =>
                  ROLLING_DAYS.map((d) => (
                    <button
                      key={d}
                      type="button"
                      className={cn(d === days && 'is-active')}
                      onClick={() => {
                        setDays(d);
                        close();
                      }}
                    >
                      Last {d} days (excluding today)
                      <small>The previous {d} days excluding today</small>
                    </button>
                  ))
                }
              </Dropdown>
            ) : null}
            {mode === 'Custom date range' ? (
              <div className="sca-custom-dates">
                <input
                  className="input"
                  type="date"
                  aria-label="Start date"
                  value={custom.from}
                  onChange={(e) => setCustom((c) => ({ ...c, from: e.target.value }))}
                />
                <span>to</span>
                <input
                  className="input"
                  type="date"
                  aria-label="End date"
                  value={custom.to}
                  onChange={(e) => setCustom((c) => ({ ...c, to: e.target.value }))}
                />
              </div>
            ) : null}
          </div>
        </div>
        <nav className="sca-tabs" aria-label="Sales content type">
          <span className="sca-tab is-active" aria-current="page">
            Templates
          </span>
          <Link className="sca-tab" href="/documents">
            Documents
          </Link>
          <Link className="sca-tab" href="/reports/sequences">
            Sequences
          </Link>
        </nav>
      </div>

      <main className="sca-content">
        <div className="sca-filters">
          <div className="sca-segment" role="group" aria-label="Group analytics by">
            {(['template', 'user'] as const).map((g) => (
              <button
                key={g}
                type="button"
                className={cn(groupBy === g && 'is-active')}
                aria-pressed={groupBy === g}
                onClick={() => setGroupBy(g)}
              >
                By {g}
              </button>
            ))}
          </div>
          <div className="sca-folder-wrap">
            <span>Folder</span>
            <Dropdown
              menuClass="sca-dropdown--search"
              trigger={
                <>
                  {folderName ?? 'All folders'} <Chevron />
                </>
              }
            >
              {(close) => (
                <>
                  <label className="sca-dropdown-search">
                    <input
                      type="search"
                      placeholder="Search"
                      aria-label="Search folders"
                      value={folderQuery}
                      onChange={(e) => setFolderQuery(e.target.value)}
                    />
                  </label>
                  <div className="sca-dropdown-list">
                    {[{ id: null as string | null, name: 'All folders' }, ...folders]
                      .filter((f) => f.name.toLowerCase().includes(folderQuery.toLowerCase()))
                      .map((f) => (
                        <button
                          key={f.id ?? 'all'}
                          type="button"
                          className={cn(f.id === folderId && 'is-active')}
                          onClick={() => {
                            setFolderId(f.id);
                            close();
                          }}
                        >
                          {f.name}
                        </button>
                      ))}
                  </div>
                </>
              )}
            </Dropdown>
          </div>
          <div className="sca-tab-actions">
            <button type="button" className="sca-export-btn" onClick={() => void exportCsv()}>
              Export unsummarized data
            </button>
            <Dropdown
              triggerClass="sca-save-report-btn"
              menuClass="sca-dropdown--save"
              trigger={
                <>
                  Save report <Chevron />
                </>
              }
            >
              {(close) => (
                <button
                  type="button"
                  disabled={backwards}
                  onClick={() => {
                    close();
                    setSaving(true);
                  }}
                >
                  Save chart
                </button>
              )}
            </Dropdown>
          </div>
        </div>

        <h2 className="sca-section-title crm-mb-3">Templates</h2>
        <section className="sca-chart-card" aria-label="Sales content performance chart">
          <div className="sca-chart-meta">{chips}</div>
          <div className="sca-legend" aria-label="Chart legend">
            {SERIES.map(([key, label, color]) => (
              <button
                key={key}
                type="button"
                aria-pressed={shown.includes(key)}
                className={cn(!shown.includes(key) && 'is-muted')}
                onClick={() =>
                  setShown((cur) =>
                    cur.includes(key) ? cur.filter((k) => k !== key) : [...cur, key],
                  )
                }
              >
                <i className="sca-dot" style={{ background: color }} />
                {label}
              </button>
            ))}
          </div>
          <div className="sca-chart">
            <div className="sca-chart-y">
              {[4, 3, 2, 1, 0].map((i) => (
                <span key={i}>{Math.round((max * i) / 4)}</span>
              ))}
            </div>
            <div className="sca-chart-plot">
              <div className="sca-gridlines">
                {[0, 1, 2, 3, 4].map((i) => (
                  <i key={i} />
                ))}
              </div>
              <div className="sca-bars">
                {charted.map((r) => (
                  <div key={r.id} className="sca-bar-group">
                    {SERIES.filter(([k]) => shown.includes(k)).map(([key, label, color]) => (
                      <span
                        key={key}
                        className="sca-bar"
                        role="img"
                        aria-label={`${r.name}, ${label}: ${r[key]}`}
                        title={`${r.name}\n${label}: ${r[key]}`}
                        style={{
                          background: color,
                          height: `${r[key] > 0 ? Math.max(3, (r[key] / max) * 100) : 0}%`,
                        }}
                      />
                    ))}
                  </div>
                ))}
                {data && !charted.length ? (
                  <div className="sca-chart-empty">Sorry, there’s no data to show.</div>
                ) : null}
              </div>
              <div className="sca-xlabels">
                {charted.map((r) => (
                  <span key={r.id} title={r.name}>
                    {r.name}
                  </span>
                ))}
              </div>
            </div>
          </div>
          <div className="sca-axis-title">{noun}</div>
        </section>

        <div className="sca-table-heading">
          <span className="sca-breadcrumb">All {groupBy === 'user' ? 'users' : 'templates'}</span>
          <div className="sca-table-tools">
            <Dropdown
              triggerClass="sca-edit-columns"
              menuClass="sca-dropdown--save"
              trigger={
                <>
                  <span className="sca-columns-icon">▦</span> Edit columns
                </>
              }
            >
              {() =>
                COLUMNS.map(([key, label]) => (
                  <label key={key} className="check sca-column-check">
                    <input
                      type="checkbox"
                      checked={columns.includes(key)}
                      onChange={(e) =>
                        setColumns((cur) =>
                          e.target.checked ? [...cur, key] : cur.filter((k) => k !== key),
                        )
                      }
                    />
                    <span className="check__box" />
                    <span>{label}</span>
                  </label>
                ))
              }
            </Dropdown>
            <label className="sca-search">
              <input
                type="search"
                placeholder="Search"
                aria-label={`Search ${noun.toLowerCase()}s`}
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setPage(1);
                }}
              />
            </label>
          </div>
        </div>

        <section className="sca-table-card">
          <div className="sca-table-top">{chips}</div>
          <div className="sca-table-scroll">
            <table className="sca-table">
              <thead>
                <tr>
                  <th>{noun}</th>
                  {COLUMNS.filter(([k]) => columns.includes(k)).map(([key, label]) => (
                    <th
                      key={key}
                      aria-sort={
                        sort.key === key ? (sort.dir === 1 ? 'ascending' : 'descending') : 'none'
                      }
                    >
                      <button
                        type="button"
                        className={cn('sca-sort', sort.key === key && 'is-active')}
                        onClick={() =>
                          setSort((s) => ({ key, dir: s.key === key && s.dir === -1 ? 1 : -1 }))
                        }
                      >
                        {label} {sort.key === key ? (sort.dir === 1 ? '↑' : '↓') : '↕'}
                      </button>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {backwards || failed || !data || !visible.length ? (
                  <tr>
                    <td colSpan={columns.length + 1}>
                      {backwards
                        ? 'The start date is after the end date.'
                        : (failed ?? (data ? 'Sorry, there’s no data to show.' : 'Loading…'))}
                    </td>
                  </tr>
                ) : (
                  visible.map((r) => (
                    <tr key={r.id}>
                      <td className="sca-name">
                        {groupBy === 'template' ? (
                          <Link href={`/templates/${r.id}/edit`}>{r.name}</Link>
                        ) : (
                          r.name
                        )}
                      </td>
                      {COLUMNS.filter(([k]) => columns.includes(k)).map(([key]) => (
                        <td key={key}>{cell(r, key)}</td>
                      ))}
                    </tr>
                  ))
                )}
              </tbody>
              {data && !backwards ? (
                <tfoot>
                  <tr>
                    <td>Report Total</td>
                    {COLUMNS.filter(([k]) => columns.includes(k)).map(([key]) => (
                      <td key={key}>{cell(data.totals, key)}</td>
                    ))}
                  </tr>
                </tfoot>
              ) : null}
            </table>
          </div>
          {rows.length > PAGE_SIZES[0]! ? (
            <div className="sca-pagination">
              <button
                type="button"
                className="sca-page-btn sca-page-arrow"
                aria-label="Previous page"
                disabled={current === 1}
                onClick={() => setPage(current - 1)}
              >
                ‹
              </button>
              {Array.from({ length: pages }, (_, i) => i + 1).map((n) => (
                <button
                  key={n}
                  type="button"
                  className={cn('sca-page-btn', n === current && 'is-current')}
                  aria-current={n === current ? 'page' : undefined}
                  onClick={() => setPage(n)}
                >
                  {n}
                </button>
              ))}
              <button
                type="button"
                className="sca-page-btn sca-page-arrow"
                aria-label="Next page"
                disabled={current === pages}
                onClick={() => setPage(current + 1)}
              >
                ›
              </button>
              <select
                className="sca-page-size"
                aria-label="Rows per page"
                value={perPage}
                onChange={(e) => {
                  setPerPage(Number(e.target.value));
                  setPage(1);
                }}
              >
                {PAGE_SIZES.map((n) => (
                  <option key={n} value={n}>
                    {n} per page
                  </option>
                ))}
              </select>
            </div>
          ) : null}
        </section>
        <SaveReportDrawer
          open={saving}
          title="Save this report"
          initialName="Template performance"
          initialDescription=""
          initialTagIds={[]}
          tags={tags}
          generate={() =>
            `Template sends, opens, clicks and replies by ${groupBy}, ${chip.toLowerCase()}.`
          }
          busy={savingBusy}
          onClose={() => setSaving(false)}
          onSave={(values) => void saveReport(values)}
        />
        <p className="sca-note">
          Counts emails sent with a template from the composer, the Inbox and sequences. Composer
          and Inbox emails are counted from when this page was added. Opens and clicks are counted
          only for tracked emails.
        </p>
      </main>
    </div>
  );
}
