'use client';

import { useEffect, useMemo, useState } from 'react';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { knownPipelineId } from '@/features/pipelines/access';
import { listPipelines, type Pipeline } from '@/features/pipelines/api.client';
import { cn } from '@/lib/utils/cn';
import {
  getActivityReport,
  getForecast,
  getPipelineByStage,
  getSequenceReport,
  getTargetsReport,
  getWonByMonth,
  getWorkflowReport,
  reportExportUrl,
} from '../api.client';
import {
  count,
  currenciesOf,
  dayLabel,
  humanize,
  money,
  monthLabel,
  periodLabel,
  rate,
} from '../format';
import {
  TARGET_TYPE_LABEL,
  type ActivityReportGroupBy,
  type ActivityReportType,
  type ForecastPeriod,
  type OwnerTeamFilter,
  type SalesTargetPeriod,
  type SalesTargetType,
  type SequenceReportGroupBy,
  type TargetsReportRow,
  type WorkflowReportGroupBy,
} from '../types';
import {
  BarRows,
  ColumnChart,
  CurrencyTabs,
  ReportBody,
  ReportCard,
  ReportTable,
  StateMessage,
  useCurrency,
  useReport,
} from './shared';

/** Active pipelines (for the pipeline picker and the pipeline-by-stage default). */
export function usePipelines(): { pipelines: Pipeline[]; loaded: boolean } {
  const [pipelines, setPipelines] = useState<Pipeline[]>([]);
  const [loaded, setLoaded] = useState(false);
  useEffect(() => {
    let alive = true;
    listPipelines().then(
      (all) => {
        if (!alive) return;
        setPipelines(all.filter((p) => !p.archived));
        setLoaded(true);
      },
      () => alive && setLoaded(true),
    );
    return () => {
      alive = false;
    };
  }, []);
  return { pipelines, loaded };
}

/** "Jan 2026", "Feb 2026", … for every month the range touches. */
function monthsBetween(from: string, to: string): string[] {
  const out: string[] = [];
  let [y, m] = from.split('-').map(Number) as [number, number];
  const [ty, tm] = to.split('-').map(Number) as [number, number];
  while ((y < ty || (y === ty && m <= tm)) && out.length < 60) {
    out.push(`${y}-${String(m).padStart(2, '0')}`);
    m += 1;
    if (m > 12) {
      m = 1;
      y += 1;
    }
  }
  return out;
}

type Kpi = { label: string; value: string; tone?: string; title?: string };

/**
 * A money KPI that fits its cell on one line (QA #350/#375/#580): from 100,000 up it is shown
 * compact ($123.5K, $1.2M) with the full amount on hover, so it fits a half-width widget too.
 */
function moneyKpi(label: string, amount: number, currency: string): Kpi {
  const full = money(amount, currency);
  if (Math.abs(amount) < 100_000) return { label, value: full };
  return { label, value: money(amount, currency, true), title: full };
}

function Kpis({ items }: { items: Kpi[] }) {
  return (
    <div
      className="sales-kpis"
      style={{ borderRadius: 0, boxShadow: 'none', borderWidth: '0 0 1px' }}
    >
      {items.map((item) => (
        <div className="sales-kpi" key={item.label}>
          <div className="sales-kpi__label">{item.label}</div>
          <div className={cn('sales-kpi__value', item.tone)} title={item.title ?? item.value}>
            {item.value}
          </div>
        </div>
      ))}
    </div>
  );
}

// --- Deals won by month --------------------------------------------------------------------------

export function WonByMonthPanel({
  from,
  to,
  pipelineId,
  ownerId,
  ownerIds,
  teamIds,
  title = 'Deals won by month',
}: {
  from: string;
  to: string;
  pipelineId?: string;
  ownerId?: string;
  title?: string;
} & OwnerTeamFilter) {
  const me = useCurrentUser();
  const key = JSON.stringify([from, to, pipelineId, ownerId, ownerIds, teamIds]);
  const state = useReport(key, (signal) =>
    getWonByMonth({ from, to, pipelineId, ownerId, ownerIds, teamIds }, { signal }),
  );
  const currencies = useMemo(
    () => currenciesOf(state.data ?? [], me.business.currency),
    [state.data, me.business.currency],
  );
  const [currency, setCurrency] = useCurrency(currencies);

  return (
    <ReportCard
      title={title}
      subtitle={`${dayLabel(from)} – ${dayLabel(to)} · by close date`}
      actions={<CurrencyTabs currencies={currencies} value={currency} onChange={setCurrency} />}
    >
      <ReportBody state={state} isEmpty={(d) => d.length === 0} empty="No deals won in this range.">
        {(rows) => {
          const mine = rows.filter((r) => r.currency === currency);
          const byMonth = new Map(mine.map((r) => [r.period, r]));
          const total = mine.reduce((sum, r) => sum + Number(r.amount), 0);
          const deals = mine.reduce((sum, r) => sum + r.count, 0);
          return (
            <>
              <Kpis
                items={[
                  moneyKpi(`Won (${currency})`, total, currency),
                  { label: 'Deals won', value: count(deals) },
                  deals
                    ? moneyKpi('Average deal', total / deals, currency)
                    : { label: 'Average deal', value: '—' },
                ]}
              />
              <ColumnChart
                ariaLabel={`Amount won per month in ${currency}`}
                rows={monthsBetween(from, to).map((period) => {
                  const row = byMonth.get(period);
                  const amount = row ? Number(row.amount) : 0;
                  return {
                    key: period,
                    label: monthLabel(period).replace(/ \d{2}(\d{2})$/, " '$1"),
                    value: amount,
                    display: money(amount, currency, true),
                    hint: `${monthLabel(period)}: ${money(amount, currency)} · ${row?.count ?? 0} deal${row?.count === 1 ? '' : 's'}`,
                  };
                })}
              />
            </>
          );
        }}
      </ReportBody>
    </ReportCard>
  );
}

// --- Open pipeline by stage ----------------------------------------------------------------------

export function PipelineByStagePanel({
  pipelineId,
  ownerId,
  ownerIds,
  teamIds,
  title = 'Open pipeline by stage',
}: {
  /** Missing: the first active pipeline. */
  pipelineId?: string;
  ownerId?: string;
  title?: string;
} & OwnerTeamFilter) {
  const me = useCurrentUser();
  const { pipelines, loaded } = usePipelines();
  // DL15a: a saved pipeline the viewer may not use (limited to others) shows their first one.
  const savedId = loaded ? knownPipelineId(pipelineId ?? '', pipelines) : (pipelineId ?? '');
  const pipeline = pipelines.find((p) => p.id === savedId) ?? (savedId ? null : pipelines[0]);
  const effectiveId = savedId || pipelines[0]?.id || '';
  const key = effectiveId ? JSON.stringify([effectiveId, ownerId, ownerIds, teamIds]) : null;
  const state = useReport(key, (signal) =>
    getPipelineByStage({ pipelineId: effectiveId, ownerId, ownerIds, teamIds }, { signal }),
  );
  const openRows = useMemo(
    () => (state.data ?? []).filter((r) => r.stageType === 'open'),
    [state.data],
  );
  const currencies = useMemo(
    () => currenciesOf(openRows, me.business.currency),
    [openRows, me.business.currency],
  );
  const [currency, setCurrency] = useCurrency(currencies);

  if (loaded && !effectiveId) {
    return (
      <ReportCard title={title}>
        <StateMessage>No pipelines yet.</StateMessage>
      </ReportCard>
    );
  }

  return (
    <ReportCard
      title={title}
      subtitle={pipeline ? `${pipeline.name} · open deals now` : 'Open deals now'}
      actions={<CurrencyTabs currencies={currencies} value={currency} onChange={setCurrency} />}
    >
      <ReportBody
        state={state}
        isEmpty={() => openRows.length === 0}
        empty="No open deals in this pipeline."
      >
        {() => {
          const mine = openRows.filter((r) => r.currency === currency);
          // Stage order as the API returns it (pipeline order); one row per stage.
          const stages = new Map<
            string,
            { name: string; count: number; amount: number; weighted: number }
          >();
          for (const r of mine) {
            const s = stages.get(r.stageId) ?? {
              name: r.stageName,
              count: 0,
              amount: 0,
              weighted: 0,
            };
            s.count += r.count;
            s.amount += Number(r.amount);
            s.weighted += Number(r.weightedAmount);
            stages.set(r.stageId, s);
          }
          const all = [...stages.values()];
          const total = all.reduce((sum, s) => sum + s.amount, 0);
          const weighted = all.reduce((sum, s) => sum + s.weighted, 0);
          const deals = all.reduce((sum, s) => sum + s.count, 0);
          return (
            <>
              <Kpis
                items={[
                  moneyKpi(`Open (${currency})`, total, currency),
                  moneyKpi('Weighted', weighted, currency),
                  { label: 'Open deals', value: count(deals) },
                ]}
              />
              <BarRows
                ariaLabel={`Open amount per stage in ${currency}`}
                rows={[...stages.entries()].map(([id, s]) => ({
                  key: id,
                  label: (
                    <>
                      {s.name} <span className="crm-text-muted">· {s.count}</span>
                    </>
                  ),
                  value: s.amount,
                  display: money(s.amount, currency),
                  hint: `${s.name}: ${money(s.amount, currency)} (weighted ${money(s.weighted, currency)}) · ${s.count} deal${s.count === 1 ? '' : 's'}`,
                }))}
              />
            </>
          );
        }}
      </ReportBody>
    </ReportCard>
  );
}

// --- Forecast ------------------------------------------------------------------------------------

export function ForecastPanel({
  period,
  pipelineId,
  ownerId,
  ownerIds,
  teamIds,
  title = 'Forecast',
}: {
  period: ForecastPeriod;
  pipelineId?: string;
  ownerId?: string;
  title?: string;
} & OwnerTeamFilter) {
  const me = useCurrentUser();
  const key = JSON.stringify([period, pipelineId, ownerId, ownerIds, teamIds]);
  const state = useReport(key, (signal) =>
    getForecast({ period, pipelineId, ownerId, ownerIds, teamIds }, { signal }),
  );
  const currencies = useMemo(
    () => currenciesOf(state.data ?? [], me.business.currency),
    [state.data, me.business.currency],
  );
  const [currency, setCurrency] = useCurrency(currencies);

  return (
    <ReportCard
      title={title}
      subtitle={`Next ${period === 'month' ? '6 months' : '4 quarters'} by close date · committed ≥ 80%, best case ≥ 50%`}
      actions={<CurrencyTabs currencies={currencies} value={currency} onChange={setCurrency} />}
    >
      <ReportBody
        state={state}
        isEmpty={(d) => d.length === 0}
        empty="No open or won deals with a close date in the coming periods."
      >
        {(rows) => {
          const mine = rows
            .filter((r) => r.currency === currency)
            .sort((a, b) => a.periodStart.localeCompare(b.periodStart));
          return (
            <ReportTable
              label={`Forecast in ${currency}`}
              head={
                <tr>
                  <th scope="col">Period</th>
                  <th scope="col" className="crm-text-end">
                    Committed
                  </th>
                  <th scope="col" className="crm-text-end">
                    Best case
                  </th>
                  <th scope="col" className="crm-text-end">
                    Weighted
                  </th>
                </tr>
              }
            >
              {mine.map((r) => (
                <tr key={r.periodStart}>
                  <td className="crm-text-nowrap">{periodLabel(r.periodStart, r.periodEnd)}</td>
                  <td className="crm-text-end">{money(r.committedAmount, currency)}</td>
                  <td className="crm-text-end">{money(r.bestCaseAmount, currency)}</td>
                  <td className="crm-text-end crm-fw-semibold">
                    {money(r.weightedAmount, currency)}
                  </td>
                </tr>
              ))}
            </ReportTable>
          );
        }}
      </ReportBody>
    </ReportCard>
  );
}

// --- Targets vs actual ---------------------------------------------------------------------------

function targetValue(row: TargetsReportRow, amount: string): string {
  return row.targetType === 'revenue_won' && row.currency
    ? money(amount, row.currency)
    : count(Number(amount));
}

export function TargetsPanel({
  from,
  to,
  period,
  type,
  assigneeId,
  assigneeIds,
  teamIds,
  title = 'Targets vs actual',
}: {
  from: string;
  to: string;
  period: SalesTargetPeriod;
  type?: SalesTargetType;
  assigneeId?: string;
  /** Dashboard Owners / Teams quick filters. */
  assigneeIds?: string[];
  teamIds?: string[];
  title?: string;
}) {
  const key = JSON.stringify([from, to, period, type, assigneeId, assigneeIds, teamIds]);
  const state = useReport(key, (signal) =>
    getTargetsReport({ from, to, period, type, assigneeId, assigneeIds, teamIds }, { signal }),
  );
  return (
    <ReportCard title={title} subtitle={`${dayLabel(from)} – ${dayLabel(to)}`}>
      <ReportBody state={state} isEmpty={(d) => d.length === 0} empty="No targets in this range.">
        {(rows) => (
          <ul className="progress-list" aria-label="Targets">
            {rows.map((row) => {
              const pct = Number.isFinite(row.percent) ? row.percent : 0;
              const hit = pct >= 100;
              return (
                <li className="progress-row" key={`${row.targetId}-${row.periodStart}`}>
                  <div className="progress-row__head">
                    <span className="progress-row__label">
                      {TARGET_TYPE_LABEL[row.targetType]}
                      {row.currency && row.targetType === 'revenue_won'
                        ? ` (${row.currency})`
                        : ''}{' '}
                      <span className="crm-text-muted crm-fw-normal">
                        · {row.assigneeName ?? (row.assigneeId ? 'Former member' : 'Whole team')} ·{' '}
                        {periodLabel(row.periodStart, row.periodEnd)}
                      </span>
                    </span>
                    <span className="progress-row__amount crm-text-nowrap">
                      {targetValue(row, row.actualAmount)} / {targetValue(row, row.targetAmount)}{' '}
                      <span className={cn('badge', hit ? 'badge--success' : 'badge--brand')}>
                        {Math.round(pct)}%{hit ? ' · hit' : ''}
                      </span>
                    </span>
                  </div>
                  <div
                    className="progress"
                    role="progressbar"
                    aria-label={TARGET_TYPE_LABEL[row.targetType]}
                    aria-valuemin={0}
                    aria-valuemax={100}
                    aria-valuenow={Math.min(100, Math.round(pct))}
                  >
                    <span
                      className="progress__bar is-in"
                      style={
                        {
                          '--p': `${Math.min(100, Math.max(0, pct))}%`,
                          background: hit ? 'var(--success)' : undefined,
                        } as React.CSSProperties
                      }
                    />
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </ReportBody>
    </ReportCard>
  );
}

// --- Activity ------------------------------------------------------------------------------------

export function ActivityPanel({
  from,
  to,
  groupBy = 'user',
  types,
  ownerId,
  ownerIds,
  teamIds,
  title = 'Activity by rep',
}: {
  from: string;
  to: string;
  groupBy?: ActivityReportGroupBy;
  types?: ActivityReportType[];
  ownerId?: string;
  title?: string;
} & OwnerTeamFilter) {
  const key = JSON.stringify([from, to, groupBy, types, ownerId, ownerIds, teamIds]);
  const state = useReport(key, (signal) =>
    getActivityReport({ from, to, groupBy, types, ownerId, ownerIds, teamIds }, { signal }),
  );
  return (
    <ReportCard
      title={title}
      subtitle={
        state.data
          ? `${dayLabel(from)} – ${dayLabel(to)} · days in ${state.data.timezone}`
          : `${dayLabel(from)} – ${dayLabel(to)}`
      }
    >
      <ReportBody
        state={state}
        isEmpty={(d) => d.data.length === 0}
        empty="No activity in this range."
      >
        {(report) => {
          const has = (t: ActivityReportType) => report.types.includes(t);
          const sum = (pick: (r: (typeof report.data)[number]) => number | undefined) =>
            report.data.reduce((s, r) => s + (pick(r) ?? 0), 0);
          const kpis = [
            has('calls') && { label: 'Calls logged', value: count(sum((r) => r.calls?.logged)) },
            has('emails') && { label: 'Emails sent', value: count(sum((r) => r.emails?.sent)) },
            has('meetings') && {
              label: 'Meetings booked',
              value: count(sum((r) => r.meetings?.booked)),
            },
            has('tasks') && {
              label: 'Tasks completed',
              value: count(sum((r) => r.tasks?.completed)),
            },
          ].filter(Boolean) as Array<{ label: string; value: string }>;
          return (
            <>
              <Kpis items={kpis} />
              <ReportTable
                label="Activity per rep"
                head={
                  <tr>
                    <th scope="col">Rep</th>
                    {report.groupBy !== 'user' ? (
                      <th scope="col">{report.groupBy === 'day' ? 'Day' : 'Week of'}</th>
                    ) : null}
                    {has('calls') ? (
                      <th scope="col" className="crm-text-end">
                        Calls
                      </th>
                    ) : null}
                    {has('emails') ? (
                      <>
                        <th scope="col" className="crm-text-end">
                          Emails sent
                        </th>
                        <th scope="col" className="crm-text-end">
                          Opened
                        </th>
                        <th scope="col" className="crm-text-end">
                          Replied
                        </th>
                      </>
                    ) : null}
                    {has('meetings') ? (
                      <>
                        <th scope="col" className="crm-text-end">
                          Meetings booked
                        </th>
                        <th scope="col" className="crm-text-end">
                          Held
                        </th>
                      </>
                    ) : null}
                    {has('tasks') ? (
                      <>
                        <th scope="col" className="crm-text-end">
                          Tasks created
                        </th>
                        <th scope="col" className="crm-text-end">
                          Completed
                        </th>
                        <th scope="col" className="crm-text-end">
                          Overdue
                        </th>
                      </>
                    ) : null}
                  </tr>
                }
              >
                {report.data.map((r) => (
                  <tr key={`${r.ownerId ?? 'none'}-${r.period ?? ''}`}>
                    <td className="crm-text-nowrap">
                      {r.ownerName ?? (r.ownerId ? 'Former member' : 'No owner')}
                    </td>
                    {report.groupBy !== 'user' ? (
                      <td className="crm-text-nowrap">{r.period ? dayLabel(r.period) : '—'}</td>
                    ) : null}
                    {has('calls') ? (
                      <td
                        className="crm-text-end"
                        title={
                          r.calls?.byOutcome.length
                            ? r.calls.byOutcome
                                .map(
                                  (o) =>
                                    `${o.outcome ? humanize(o.outcome) : 'No outcome'}: ${o.count}`,
                                )
                                .join('\n')
                            : undefined
                        }
                      >
                        {count(r.calls?.logged ?? 0)}
                      </td>
                    ) : null}
                    {has('emails') ? (
                      <>
                        <td className="crm-text-end">{count(r.emails?.sent ?? 0)}</td>
                        <td className="crm-text-end">{count(r.emails?.opened ?? 0)}</td>
                        <td className="crm-text-end">{count(r.emails?.replied ?? 0)}</td>
                      </>
                    ) : null}
                    {has('meetings') ? (
                      <>
                        <td className="crm-text-end">{count(r.meetings?.booked ?? 0)}</td>
                        <td className="crm-text-end">{count(r.meetings?.held ?? 0)}</td>
                      </>
                    ) : null}
                    {has('tasks') ? (
                      <>
                        <td className="crm-text-end">{count(r.tasks?.created ?? 0)}</td>
                        <td className="crm-text-end">{count(r.tasks?.completed ?? 0)}</td>
                        <td
                          className={cn(
                            'crm-text-end',
                            (r.tasks?.overdue ?? 0) > 0 && 'crm-text-warning',
                          )}
                        >
                          {count(r.tasks?.overdue ?? 0)}
                        </td>
                      </>
                    ) : null}
                  </tr>
                ))}
              </ReportTable>
            </>
          );
        }}
      </ReportBody>
    </ReportCard>
  );
}

// --- Workflows -----------------------------------------------------------------------------------

export function WorkflowsPanel({
  from,
  to,
  groupBy = 'workflow',
  workflowId,
  ownerId,
  ownerIds,
  teamIds,
  title = 'Workflow performance',
  showExport = false,
}: {
  from: string;
  to: string;
  groupBy?: WorkflowReportGroupBy;
  workflowId?: string;
  ownerId?: string;
  title?: string;
  showExport?: boolean;
} & OwnerTeamFilter) {
  const query = { from, to, groupBy, workflowId, ownerId, ownerIds, teamIds };
  const key = JSON.stringify(query);
  const state = useReport(key, (signal) => getWorkflowReport(query, { signal }));
  return (
    <ReportCard
      title={title}
      subtitle={`${dayLabel(from)} – ${dayLabel(to)}`}
      actions={
        showExport && state.data ? (
          <a
            className="btn-crm btn-crm--outline btn-crm--sm"
            href={reportExportUrl('workflows', query)}
            download
          >
            Export CSV
          </a>
        ) : null
      }
    >
      <ReportBody
        state={state}
        isEmpty={(d) => d.data.length === 0}
        empty="No workflows yet."
        forbiddenText="Workflow reports need the Manage workflows permission."
      >
        {(report) => (
          <ReportTable
            label="Workflow performance"
            head={
              <tr>
                <th scope="col">Workflow</th>
                {report.groupBy !== 'workflow' ? (
                  <th scope="col">{report.groupBy === 'day' ? 'Day' : 'Week of'}</th>
                ) : null}
                <th scope="col" className="crm-text-end">
                  Enrolled
                </th>
                <th scope="col" className="crm-text-end">
                  Completed
                </th>
                <th scope="col" className="crm-text-end">
                  Failed
                </th>
                <th scope="col" className="crm-text-end">
                  Unenrolled
                </th>
              </tr>
            }
          >
            {report.data.map((r) => (
              <tr key={`${r.workflowId}-${r.period ?? ''}`}>
                <td>{r.workflowName}</td>
                {report.groupBy !== 'workflow' ? (
                  <td className="crm-text-nowrap">{r.period ? dayLabel(r.period) : '—'}</td>
                ) : null}
                <td className="crm-text-end">{count(r.enrolled)}</td>
                <td className="crm-text-end">{count(r.completed)}</td>
                <td className={cn('crm-text-end', r.failed > 0 && 'crm-text-danger')}>
                  {count(r.failed)}
                </td>
                <td
                  className="crm-text-end"
                  title={
                    r.unenrolledByReason.length
                      ? r.unenrolledByReason
                          .map((x) => `${humanize(x.reason)}: ${x.count}`)
                          .join('\n')
                      : undefined
                  }
                >
                  {count(r.unenrolled)}
                </td>
              </tr>
            ))}
          </ReportTable>
        )}
      </ReportBody>
    </ReportCard>
  );
}

// --- Sequences -----------------------------------------------------------------------------------

export function SequencesPanel({
  from,
  to,
  groupBy = 'sequence',
  sequenceId,
  ownerId,
  ownerIds,
  teamIds,
  title = 'Sequence performance',
  showExport = false,
}: {
  from: string;
  to: string;
  groupBy?: SequenceReportGroupBy;
  sequenceId?: string;
  ownerId?: string;
  title?: string;
  showExport?: boolean;
} & OwnerTeamFilter) {
  const query = { from, to, groupBy, sequenceId, ownerId, ownerIds, teamIds };
  const key = JSON.stringify(query);
  const state = useReport(key, (signal) => getSequenceReport(query, { signal }));
  return (
    <ReportCard
      title={title}
      // #577 / HUB-310: contacts enrolled in the range (as the sequence's Performance tab); the
      // meeting rate is of enrollments (HubSpot), the other rates of emails sent.
      subtitle={`Enrolled ${dayLabel(from)} – ${dayLabel(to)} · meeting rate is a share of enrollments, other rates of emails sent`}
      actions={
        showExport && state.data ? (
          <a
            className="btn-crm btn-crm--outline btn-crm--sm"
            href={reportExportUrl('sequences', query)}
            download
          >
            Export CSV
          </a>
        ) : null
      }
    >
      <ReportBody
        state={state}
        isEmpty={(d) => d.data.length === 0}
        empty="No sequences yet."
        forbiddenText="Sequence reports need the Use sequences or Manage sequences permission."
      >
        {(report) => (
          <ReportTable
            label="Sequence performance"
            head={
              <tr>
                <th scope="col">Sequence</th>
                {report.groupBy === 'step' ? <th scope="col">Step</th> : null}
                {report.groupBy === 'rep' ? <th scope="col">Rep</th> : null}
                {report.groupBy !== 'step' ? (
                  <th scope="col" className="crm-text-end">
                    Enrolled
                  </th>
                ) : null}
                <th scope="col" className="crm-text-end">
                  Sent
                </th>
                <th scope="col" className="crm-text-end">
                  Open rate
                </th>
                <th scope="col" className="crm-text-end">
                  Reply rate
                </th>
                <th scope="col" className="crm-text-end">
                  Bounce rate
                </th>
                <th scope="col" className="crm-text-end">
                  Meetings
                </th>
                {report.groupBy !== 'step' ? (
                  <th scope="col" className="crm-text-end">
                    Meeting rate
                  </th>
                ) : null}
              </tr>
            }
          >
            {report.data.map((r) => (
              <tr key={`${r.sequenceId}-${r.stepIndex ?? ''}-${r.repId ?? ''}`}>
                <td>{r.sequenceName}</td>
                {report.groupBy === 'step' ? (
                  <td>{r.stepIndex === null ? '—' : `Step ${r.stepIndex + 1}`}</td>
                ) : null}
                {report.groupBy === 'rep' ? <td>{r.repName ?? '—'}</td> : null}
                {report.groupBy !== 'step' ? (
                  <td className="crm-text-end">{r.enrolled === null ? '—' : count(r.enrolled)}</td>
                ) : null}
                <td className="crm-text-end">{count(r.sent)}</td>
                <td className="crm-text-end" title={`${r.opened} opened`}>
                  {rate(r.openRate)}
                </td>
                <td className="crm-text-end" title={`${r.replied} replied`}>
                  {rate(r.replyRate)}
                </td>
                <td className="crm-text-end" title={`${r.bounced} bounced`}>
                  {rate(r.bounceRate)}
                </td>
                <td className="crm-text-end">{count(r.meetingsBooked)}</td>
                {report.groupBy !== 'step' ? (
                  <td className="crm-text-end">{rate(r.meetingRate)}</td>
                ) : null}
              </tr>
            ))}
          </ReportTable>
        )}
      </ReportBody>
    </ReportCard>
  );
}
