'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { LpModal } from '@/features/list-page/ui/LpModal';
import { createDashboard, listDashboards } from '@/features/reports/api.client';
import type { Dashboard } from '@/features/reports/types';
import { errorText } from '@/lib/api/errors';
import {
  SPREADSHEET_MIME,
  spreadsheetFile,
  type Cell,
  type SpreadsheetFormat,
} from '@/lib/export/spreadsheet';
import { cn } from '@/lib/utils/cn';
import {
  createSalesReportSegment,
  listSalesReportRecords,
  saveSalesReport,
  type SalesReportInfo,
  type SalesReportQuery,
  type SalesReportRecord,
} from '../api.client';
import { fileSlug, pageList, recordHref, recordTypeLabel } from '../model';
import { formatFigure } from '../format';
import { formatDay, isoDate, parseIsoDate, type RangeState } from '../ranges';
import { LpI, SaIcon } from './icons';
import { MenuPop, SaDialog, SelectPop } from './layers';

/** The report view's dialogs: export, save, segment, records, date range, quick filters. */

export function downloadSheet(rows: Cell[][], name: string, format: SpreadsheetFormat) {
  const data = spreadsheetFile({ name, rows }, format);
  const blob = new Blob([data as BlobPart], { type: SPREADSHEET_MIME[format] });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = `${fileSlug(name)}.${format}`;
  document.body.appendChild(a);
  a.click();
  a.remove();
  window.setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}

const FORMAT_HELP: Record<SpreadsheetFormat, string> = {
  csv: 'CSV files support a maximum of 1,000,000 rows of data.',
  xls: 'XLS files support a maximum of 65,000 rows of data. Choose CSV or XLSX file format to export more rows of data.',
  xlsx: 'XLSX files support a maximum of 1,000,000 rows of data.',
};

/** "Export" (design `exportDialog`): a name and a file format; `run` makes the file. */
export function ExportDialog({
  name,
  onClose,
  run,
}: {
  name: string;
  onClose: () => void;
  run: (name: string, format: SpreadsheetFormat) => Promise<void> | void;
}) {
  const [value, setValue] = useState(name);
  const [format, setFormat] = useState<SpreadsheetFormat>('csv');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const go = async () => {
    setBusy(true);
    setErr(null);
    try {
      await run(value.trim() || name, format);
      onClose();
    } catch (e) {
      setErr(errorText(e));
      setBusy(false);
    }
  };
  return (
    <SaDialog
      title="Export"
      onClose={onClose}
      footer={
        <>
          <button type="button" className="sa-btn sa-btn--primary" disabled={busy} onClick={go}>
            {busy ? 'Exporting…' : 'Export'}
          </button>
          <button type="button" className="sa-btn sa-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </>
      }
    >
      <div className="sa-field">
        <label htmlFor="saExportName">Name</label>
        <input
          id="saExportName"
          className="sa-input"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && !busy) go();
          }}
        />
      </div>
      <div className="sa-field">
        <label htmlFor="saExportFormat">File format</label>
        <select
          id="saExportFormat"
          className="sa-input"
          value={format}
          onChange={(e) => setFormat(e.target.value as SpreadsheetFormat)}
        >
          <option value="csv">CSV</option>
          <option value="xls">XLS</option>
          <option value="xlsx">XLSX</option>
        </select>
      </div>
      <p className="sa-export-help">{FORMAT_HELP[format]}</p>
      {err ? (
        <p className="sa-rerr" role="alert">
          {err}
        </p>
      ) : null}
    </SaDialog>
  );
}

/** Every record behind the report (or a row), page by page, for the unsummarized export. */
export async function allRecords(
  key: string,
  query: SalesReportQuery & { rowId?: string },
): Promise<SalesReportRecord[]> {
  const out: SalesReportRecord[] = [];
  let cursor: string | undefined;
  for (;;) {
    const page = await listSalesReportRecords(key, { ...query, limit: 500, cursor });
    out.push(...page.data);
    if (!page.nextCursor || out.length >= 1_000_000) break;
    cursor = page.nextCursor;
  }
  return out;
}

/**
 * "Save report" (design `saveDrawer`): the name, and whether to add it to an existing or a new
 * dashboard. The design's tags and generated description have no place in Save as report.
 */
export function SaveReportDialog({
  info,
  defaultName,
  query,
  onClose,
}: {
  info: SalesReportInfo;
  defaultName: string;
  query: SalesReportQuery;
  onClose: () => void;
}) {
  const toast = useToast();
  const [step, setStep] = useState<1 | 2>(1);
  const [name, setName] = useState(defaultName);
  const [dash, setDash] = useState<'none' | 'existing' | 'new'>('none');
  const [dashboards, setDashboards] = useState<Dashboard[] | null>(null);
  const [dashboard, setDashboard] = useState<Dashboard | null>(null);
  const [dashBtn, setDashBtn] = useState<HTMLElement | null>(null);
  const [newName, setNewName] = useState(`${info.title} dashboard`);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    if (dash !== 'existing' || dashboards) return;
    listDashboards().then(
      (d) => setDashboards(d.filter((x) => x.canEdit)),
      (e: unknown) => setErr(errorText(e)),
    );
  }, [dash, dashboards]);

  const finish = async () => {
    setBusy(true);
    setErr(null);
    try {
      let target: { id: string; name: string } | null = dash === 'existing' ? dashboard : null;
      if (dash === 'new') target = await createDashboard({ name: newName.trim() });
      const res = await saveSalesReport(info.key, {
        ...query,
        name: name.trim(),
        ...(target ? { dashboardId: target.id } : {}),
      });
      toast(
        `"${name.trim()}" saved to My reports${target ? ` and added to ${dash === 'new' ? 'the new dashboard ' : ''}${target.name}` : ''}`,
        'success',
        {
          link: target
            ? { label: 'View dashboard', href: `/reports/dashboards/${target.id}` }
            : { label: 'View report', href: `/reports/library/${res.savedReportId}` },
        },
      );
      onClose();
    } catch (e) {
      setErr(errorText(e));
      setBusy(false);
    }
  };

  const next = () => {
    if (!name.trim()) {
      setErr('Enter a report name');
      return;
    }
    if (step === 1 && dash === 'new') {
      setErr(null);
      setStep(2);
      return;
    }
    if (step === 2 && !newName.trim()) {
      setErr('Enter a dashboard name');
      return;
    }
    void finish();
  };
  const saveAdd = step === 2 || dash === 'existing';

  return (
    <SaDialog
      title="Save report"
      className="sa-save-drawer"
      onClose={onClose}
      footer={
        <button
          type="button"
          className="sa-btn sa-btn--primary"
          disabled={busy || (step === 1 && dash === 'existing' && !dashboard)}
          onClick={next}
        >
          {busy ? 'Saving…' : saveAdd ? 'Save & add' : dash === 'new' ? 'Next' : 'Save'}
          {!busy && !saveAdd && dash === 'new' ? (
            <SaIcon name="right" className="sa-i--sm" />
          ) : null}
        </button>
      }
    >
      {step === 1 ? (
        <>
          <p className="sa-save-intro">
            This report will be saved to your reports. You can also add it to a dashboard.
          </p>
          <div className="sa-field">
            <label htmlFor="saSaveN">Report name *</label>
            <input
              id="saSaveN"
              className="sa-input"
              value={name}
              maxLength={120}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
          <fieldset className="sa-save-dash">
            <legend>Add this report to a dashboard?</legend>
            {(
              [
                ['none', 'Don’t add to a dashboard'],
                ['existing', 'Add to existing dashboard'],
              ] as const
            ).map(([v, l]) => (
              <label key={v}>
                <input
                  type="radio"
                  name="saSaveDash"
                  value={v}
                  checked={dash === v}
                  onChange={() => setDash(v)}
                />{' '}
                {l}
              </label>
            ))}
            {dash === 'existing' ? (
              <div className="sa-save-exist">
                <button
                  type="button"
                  className="sa-combo"
                  aria-haspopup="listbox"
                  aria-expanded={Boolean(dashBtn)}
                  aria-label="Choose a dashboard"
                  onClick={(e) => setDashBtn(dashBtn ? null : e.currentTarget)}
                >
                  <span className={cn('sa-combo__v', !dashboard && 'sa-combo__ph')}>
                    {dashboard?.name ?? (dashboards ? 'Search' : 'Loading…')}
                  </span>
                  <SaIcon name="caret" className="sa-i--xs" />
                </button>
              </div>
            ) : null}
            <label>
              <input
                type="radio"
                name="saSaveDash"
                value="new"
                checked={dash === 'new'}
                onChange={() => setDash('new')}
              />{' '}
              Add to new dashboard
            </label>
          </fieldset>
        </>
      ) : (
        <>
          <button type="button" className="sa-save-back" onClick={() => setStep(1)}>
            <SaIcon name="back" className="sa-i--sm" />
            Back
          </button>
          <p className="sa-save-intro">
            Name your new dashboard. This report will be added to it when you save.
          </p>
          <div className="sa-field">
            <label htmlFor="saSaveDN">Dashboard name *</label>
            <input
              id="saSaveDN"
              className="sa-input"
              maxLength={120}
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
            />
          </div>
        </>
      )}
      {err ? (
        <p className="sa-rerr" role="alert">
          {err}
        </p>
      ) : null}
      {dashBtn && dashboards ? (
        <SelectPop
          anchor={dashBtn}
          onClose={() => setDashBtn(null)}
          groups={[{ label: '', options: dashboards.map((d) => ({ value: d.id, label: d.name })) }]}
          value={dashboard?.id ?? null}
          onPick={(id) => setDashboard(dashboards.find((d) => d.id === id) ?? null)}
          minWidth={dashBtn.offsetWidth}
        />
      ) : null}
    </SaDialog>
  );
}

/**
 * "Add contacts to a segment" (design `segModal`): a new static segment of the report's contacts
 * (or one row's). The design's "Add to an existing static segment" has no API, so only a new one.
 */
export function SegmentDialog({
  info,
  query,
  rowId,
  onClose,
}: {
  info: SalesReportInfo;
  query: SalesReportQuery;
  rowId?: string;
  onClose: () => void;
}) {
  const toast = useToast();
  const [name, setName] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const submit = async () => {
    setBusy(true);
    setErr(null);
    try {
      const { compare: _c, ...filters } = query;
      void _c;
      const res = await createSalesReportSegment(info.key, {
        ...filters,
        name: name.trim(),
        ...(rowId ? { rowId } : {}),
      });
      toast(`Segment "${name.trim()}" created`, 'success', {
        link: { label: 'View segment', href: `/lists/${res.listId}` },
      });
      onClose();
    } catch (e) {
      setErr(errorText(e));
      setBusy(false);
    }
  };
  return (
    <LpModal
      open
      title="Add contacts to a segment"
      className="lp-modal--qf sa-segdlg sa-layer"
      onClose={onClose}
      footer={
        <div className="lp-modal__acts">
          <button
            type="button"
            className="lp-btn lp-btn--primary lp-btn--pill"
            disabled={busy || !name.trim()}
            onClick={submit}
          >
            {busy ? 'Submitting…' : 'Submit'}
          </button>
          <button type="button" className="lp-btn lp-btn--outline lp-btn--pill" onClick={onClose}>
            Cancel
          </button>
        </div>
      }
    >
      <label className="sa-seg__r">
        <input type="radio" name="saSegM" value="new" checked readOnly /> Create a new segment
      </label>
      <div className="lp-field">
        <label htmlFor="saSegN">Segment name *</label>
        <input
          className="lp-input"
          id="saSegN"
          data-autofocus
          value={name}
          maxLength={191}
          onChange={(e) => setName(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && name.trim() && !busy) submit();
          }}
        />
      </div>
      {err ? (
        <p className="sa-rerr" role="alert">
          {err}
        </p>
      ) : null}
    </LpModal>
  );
}

const PAGE_SIZE = 25;

/**
 * A row's records (design `openValueRecords`): the records behind one row, paged, with More >
 * Export unsummarized data, Save as report and (segmentable reports) Use in segment.
 */
export function RecordsDialog({
  info,
  title,
  query,
  rowId,
  chips,
  currency,
  onExport,
  onSave,
  onSegment,
  onClose,
}: {
  info: SalesReportInfo;
  title: string;
  query: SalesReportQuery;
  rowId?: string;
  chips: string[];
  currency: string;
  onExport: () => void;
  onSave: () => void;
  onSegment?: () => void;
  onClose: () => void;
}) {
  const [cursors, setCursors] = useState<Array<string | undefined>>([undefined]);
  const [page, setPage] = useState(0);
  const [data, setData] = useState<{
    rows: SalesReportRecord[];
    next: string | null;
    total?: number;
  } | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const [moreBtn, setMoreBtn] = useState<HTMLElement | null>(null);

  useEffect(() => {
    const ctrl = new AbortController();
    setData(null);
    setErr(null);
    listSalesReportRecords(
      info.key,
      { ...query, ...(rowId ? { rowId } : {}), limit: PAGE_SIZE, cursor: cursors[page] },
      { signal: ctrl.signal },
    ).then(
      (r) => {
        setData({ rows: r.data, next: r.nextCursor, total: r.total });
        if (r.nextCursor) {
          setCursors((c) => {
            const out = c.slice(0, page + 1);
            out[page + 1] = r.nextCursor!;
            return out;
          });
        }
      },
      (e: unknown) => {
        if (!ctrl.signal.aborted) setErr(errorText(e));
      },
    );
    return () => ctrl.abort();
    // cursors grows from this effect; the page's cursor is read when the page changes.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [info.key, query, rowId, page]);

  const pages = data?.total !== undefined ? Math.max(1, Math.ceil(data.total / PAGE_SIZE)) : null;
  const count =
    data?.total !== undefined
      ? `${data.total.toLocaleString('en-US')} records`
      : data
        ? `${(page * PAGE_SIZE + data.rows.length).toLocaleString('en-US')}${data.next ? '+' : ''} records`
        : '';
  const hasNext = Boolean(data?.next);

  return (
    <SaDialog title={title} className="sa-record-ov" onClose={onClose}>
      <div className="sa-rec">
        <div className="sa-rec-bar">
          <span className="sa-rec-count">{count}</span>
          <span className="sa-rec-sep" />
          <span className="sa-chips">
            {chips.map((c) => (
              <span key={c} className="sa-chip">
                {c}
              </span>
            ))}
          </span>
          <button
            type="button"
            className="sa-rec-more"
            aria-haspopup="menu"
            aria-expanded={Boolean(moreBtn)}
            onClick={(e) => setMoreBtn(moreBtn ? null : e.currentTarget)}
          >
            More
          </button>
        </div>
        <div className="sa-rec-grid" tabIndex={0} role="region" aria-label="Records">
          <table className="sa-rec-table">
            <thead>
              <tr>
                <th scope="col">Name</th>
                <th scope="col">Type</th>
                <th scope="col">Owner</th>
                <th scope="col">Date</th>
                <th scope="col">Amount</th>
              </tr>
            </thead>
            <tbody>
              {err ? (
                <tr>
                  <td className="sa-rec-empty" colSpan={5} role="alert">
                    The records could not be loaded: {err}
                  </td>
                </tr>
              ) : !data ? (
                <tr>
                  <td className="sa-rec-empty" colSpan={5}>
                    Loading…
                  </td>
                </tr>
              ) : !data.rows.length ? (
                <tr>
                  <td className="sa-rec-empty" colSpan={5}>
                    No records to show.
                  </td>
                </tr>
              ) : (
                data.rows.map((r) => {
                  const href = recordHref(r);
                  return (
                    <tr key={`${r.objectType}:${r.id}`}>
                      <td>
                        {href ? (
                          <Link className="sa-emlink" href={href}>
                            {r.name}
                          </Link>
                        ) : (
                          r.name
                        )}
                      </td>
                      <td>{recordTypeLabel(r.objectType)}</td>
                      <td>{r.ownerName ?? ''}</td>
                      <td>{r.date ? formatDay(r.date.slice(0, 10)) : ''}</td>
                      <td>
                        {r.amount === null ? '' : formatFigure(r.amount, 'currency', currency)}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
        <div className="sa-rec-foot">
          {page > 0 || hasNext ? (
            <nav className="sa-rec-pager" aria-label="Records pagination">
              <button
                type="button"
                className="sa-rp sa-rp--arr"
                disabled={page === 0}
                aria-label="Previous page"
                onClick={() => setPage((p) => Math.max(0, p - 1))}
              >
                <SaIcon name="arrowl" className="sa-i--sm" />
              </button>
              {(pages ? pageList(page + 1, pages) : [page + 1]).map((n, i) =>
                n === '…' ? (
                  <span key={`e${i}`} className="sa-rp-el" aria-hidden="true">
                    …
                  </span>
                ) : (
                  <button
                    key={n}
                    type="button"
                    className={cn('sa-rp', n === page + 1 && 'is-on')}
                    aria-current={n === page + 1 ? 'page' : undefined}
                    aria-label={`Page ${n}`}
                    // Pages are reached by cursor: only those already passed can be jumped to.
                    disabled={n - 1 > cursors.length - 1}
                    onClick={() => setPage(n - 1)}
                  >
                    {n}
                  </button>
                ),
              )}
              <button
                type="button"
                className="sa-rp sa-rp--arr"
                disabled={!hasNext}
                aria-label="Next page"
                onClick={() => setPage((p) => p + 1)}
              >
                <SaIcon name="arrowr" className="sa-i--sm" />
              </button>
            </nav>
          ) : null}
        </div>
      </div>
      <MenuPop
        anchor={moreBtn}
        onClose={() => setMoreBtn(null)}
        align="end"
        items={[
          { label: 'Export unsummarized data', onClick: onExport },
          { label: 'Save as report', onClick: onSave },
          ...(onSegment ? [{ label: 'Use in segment', onClick: onSegment }] : []),
        ]}
      />
    </SaDialog>
  );
}

/** "Rolling date range" / "Custom date range" (design `rangeModal`). */
export function RangeDialog({
  kind,
  current,
  onApply,
  onClose,
}: {
  kind: 'rolling' | 'custom';
  current: RangeState;
  onApply: (r: RangeState) => void;
  onClose: () => void;
}) {
  const today = new Date();
  const [days, setDays] = useState(String(current.days ?? 30));
  const [from, setFrom] = useState(
    current.from ?? isoDate(new Date(today.getFullYear(), today.getMonth(), today.getDate() - 29)),
  );
  const [to, setTo] = useState(current.to ?? isoDate(today));
  const [err, setErr] = useState<string | null>(null);
  const apply = () => {
    if (kind === 'rolling') {
      const n = parseInt(days, 10);
      if (!n || n < 1 || n > 3650) {
        setErr('Enter a number of days between 1 and 3650.');
        return;
      }
      onApply({ key: 'rolling', days: n });
    } else {
      const a = parseIsoDate(from);
      const b = parseIsoDate(to);
      if (!a || !b) {
        setErr('Choose a start and end date.');
        return;
      }
      if (a > b) {
        setErr('The start date must be before the end date.');
        return;
      }
      onApply({ key: 'custom', from, to });
    }
    onClose();
  };
  return (
    <LpModal
      open
      title={kind === 'rolling' ? 'Rolling date range' : 'Custom date range'}
      className="sa-layer"
      onClose={onClose}
      footer={
        <div className="lp-modal__acts">
          <button type="button" className="lp-btn lp-btn--primary" onClick={apply}>
            Apply
          </button>
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      }
    >
      {kind === 'rolling' ? (
        <div className="lp-field">
          <label htmlFor="saRn">Show the last (days)</label>
          <input
            className="lp-input"
            id="saRn"
            data-autofocus
            type="number"
            min={1}
            max={3650}
            value={days}
            onChange={(e) => setDays(e.target.value)}
          />
        </div>
      ) : (
        <div className="sa-dgrid">
          <div className="lp-field">
            <label htmlFor="saRa">From</label>
            <input
              className="lp-input"
              id="saRa"
              type="date"
              value={from}
              onChange={(e) => setFrom(e.target.value)}
            />
          </div>
          <div className="lp-field">
            <label htmlFor="saRb">To</label>
            <input
              className="lp-input"
              id="saRb"
              type="date"
              value={to}
              onChange={(e) => setTo(e.target.value)}
            />
          </div>
        </div>
      )}
      {err ? (
        <p className="sa-rerr" role="alert">
          {err}
        </p>
      ) : null}
    </LpModal>
  );
}

/**
 * "Edit quick filters" (design `editQuickFilters`): the quick filters added to the report, each
 * changed or removed; the report's own (fixed) ones stay.
 */
export function EditQuickFiltersDialog({
  custom,
  options,
  onDone,
  onClose,
}: {
  custom: string[];
  options: { key: string; label: string }[];
  onDone: (next: string[]) => void;
  onClose: () => void;
}) {
  const [draft, setDraft] = useState<string[]>(custom);
  const [pick, setPick] = useState<{ i: number; el: HTMLElement } | null>(null);
  const labelOf = (k: string) => options.find((o) => o.key === k)?.label;
  return (
    <LpModal
      open
      title="Edit quick filters"
      className="sa-qfmodal sa-layer"
      onClose={onClose}
      footer={
        <div className="lp-modal__acts">
          <button
            type="button"
            className="lp-btn lp-btn--primary"
            onClick={() => {
              onDone([...new Set(draft.filter(Boolean))]);
              onClose();
            }}
          >
            Done
          </button>
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      }
    >
      <p className="sa-qfm__n">Quick filters used: {draft.length}/10</p>
      {draft.map((k, i) => (
        <div className="sa-qfm__row" key={`${i}:${k}`}>
          <button
            type="button"
            className="lp-select sa-qfm__sel"
            aria-haspopup="listbox"
            aria-expanded={pick?.i === i}
            onClick={(e) => setPick(pick ? null : { i, el: e.currentTarget })}
          >
            <span className={k ? undefined : 'lp-muted'}>{labelOf(k) ?? 'Choose a filter'}</span>
            <LpI name="chevd" />
          </button>
          <button
            type="button"
            className="lp-icon-btn"
            aria-label="Remove filter"
            onClick={() => setDraft((d) => d.filter((_, j) => j !== i))}
          >
            <LpI name="trash" />
          </button>
        </div>
      ))}
      <div className="sa-qfm__acts">
        <button
          type="button"
          className="lp-btn lp-btn--outline lp-btn--sm"
          disabled={draft.length >= Math.min(10, options.length)}
          onClick={() => setDraft((d) => [...d, ''])}
        >
          <LpI name="plus" />
          Add quick filter
        </button>
        <button
          type="button"
          className="lp-btn lp-btn--outline lp-btn--sm"
          disabled={!draft.length}
          onClick={() => setDraft([])}
        >
          <LpI name="trash" />
          Delete all quick filters
        </button>
      </div>
      {pick ? (
        <SelectPop
          anchor={pick.el}
          onClose={() => setPick(null)}
          groups={[
            {
              label: '',
              options: options
                .filter((o) => o.key === draft[pick.i] || !draft.includes(o.key))
                .map((o) => ({ value: o.key, label: o.label })),
            },
          ]}
          value={draft[pick.i] || null}
          onPick={(v) => setDraft((d) => d.map((x, j) => (j === pick.i ? v : x)))}
          minWidth={300}
        />
      ) : null}
    </LpModal>
  );
}
