'use client';

import { useEffect, useState } from 'react';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import type { EmailTemplate } from '@/features/inbox/types';
import { useReport } from '@/features/reports/ui/shared';
import { getSequenceAnalytics } from '@/features/sequences/api.client';
import type {
  SequenceAnalytics,
  SequenceAnalyticsQuery,
  SequenceAnalyticsStatus,
  SequenceStep,
} from '@/features/sequences/types';
import { cn } from '@/lib/utils/cn';
import { StepIcon } from './DynamicSequenceCanvas';
import { REP_KINDS, repKindOf } from './DynamicStepDrawers';
import { StackedBarChart } from './SequenceCharts';
import { CreateSegmentDialog } from './SequenceEnrollmentsTab';
import {
  Card,
  CompanyInsights,
  EmailEngagement,
  InfoIcon,
  Insights,
  DateRangeFilter,
  EnrolledByFilter,
  PerformanceOverTime,
  STATUS_LABELS,
  Stat,
  StatDrill,
  ValuesFilter,
  pct,
  revenueText,
  usDate,
  type DateRange,
} from './SequencesAnalyzeTab';

/** The status colours of the Enrollments tab's dots. */
const STATUS_COLORS: Record<SequenceAnalyticsStatus, string> = {
  scheduled: '#6b7280',
  in_progress: '#15803d',
  paused: '#c2410c',
  finished: '#2563eb',
  error: '#be123c',
};

type StepRow = SequenceAnalytics['steps'][number];

/** Performance tab of one sequence: the Analyze view's numbers for it, and per-step numbers. */
export function SequencePerformanceTab({
  sequenceId,
  steps,
  dynamic,
  templates,
  reloadKey = 0,
}: {
  sequenceId: string;
  /** Bumped when contacts are enrolled from the header: the numbers are read again (QA #50). */
  reloadKey?: number;
  /** The sequence's current steps (step rows are matched to the numbers by position). */
  steps: SequenceStep[];
  dynamic: boolean;
  templates: EmailTemplate[] | null;
}) {
  const me = useCurrentUser();
  const canSeeEveryone = Boolean(me.permissionSet.rules.app.manage_sequences);

  /** Picked companies' names: they stay options when another filter leaves them out. */
  const [companies, setCompanies] = useState<Map<string, string>>(new Map());
  const [companyIds, setCompanyIds] = useState<string[]>([]);
  const [statuses, setStatuses] = useState<string[]>([]);
  // HubSpot starts on your own enrollments (QA 16 Oct #113), with no date range.
  const [enrolledBy, setEnrolledBy] = useState<string[]>(canSeeEveryone ? [me.user.id] : []);
  const [range, setRange] = useState<DateRange | null>(null);
  const [mode, setMode] = useState<'rates' | 'counts'>('rates');
  const [segmentOpen, setSegmentOpen] = useState(false);

  const query: SequenceAnalyticsQuery = {
    ...(range && range),
    sequenceId,
    ...(companyIds.length > 0 && { companyId: companyIds.join(',') }),
    ...(statuses.length > 0 && { status: statuses.join(',') }),
    ...(enrolledBy.length > 0 && { enrolledBy: enrolledBy.join(',') }),
  };
  const state = useReport(`${JSON.stringify(query)}#${reloadKey}`, (signal) =>
    getSequenceAnalytics(query, signal),
  );
  const data = state.data;
  useEffect(() => {
    const options = data?.companyOptions;
    if (!options?.length) return;
    setCompanies((current) => {
      const next = new Map(current);
      for (const c of options) next.set(c.id, c.name);
      return next.size === current.size ? current : next;
    });
  }, [data?.companyOptions]);
  const companyLabel = (id: string) => companies.get(id) ?? 'Selected company';
  // What the stat drill-down names as the filters in force (HubSpot: "Filters (2)").
  const filterNotes = [
    ...(companyIds.length ? [`Company: ${companyIds.map(companyLabel).join(', ')}`] : []),
    ...(statuses.length
      ? [`Status: ${statuses.map((v) => STATUS_LABELS[v as SequenceAnalyticsStatus]).join(', ')}`]
      : []),
    ...(enrolledBy.length ? [`Enrolled by: ${enrolledBy.length} selected`] : []),
    ...(range ? [`Enrollment date: ${usDate(range.from)} to ${usDate(range.to)}`] : []),
  ];

  return (
    <div className="seqa seqp">
      <div className="seqa-filters">
        <ValuesFilter
          label="Company"
          selected={companyIds}
          onChange={setCompanyIds}
          options={[
            ...companyIds
              .filter((id) => !data?.companyOptions?.some((c) => c.id === id))
              .map((id) => ({ value: id, label: companyLabel(id) })),
            ...(data?.companyOptions ?? []).map((c) => ({ value: c.id, label: c.name })),
          ]}
          searchLabel="Search companies"
        />
        <ValuesFilter
          label="Status"
          selected={statuses}
          onChange={setStatuses}
          options={(Object.keys(STATUS_LABELS) as SequenceAnalyticsStatus[]).map((s) => ({
            value: s,
            label: STATUS_LABELS[s],
          }))}
        />
        {canSeeEveryone ? (
          <EnrolledByFilter selected={enrolledBy} onChange={setEnrolledBy} />
        ) : null}
        <DateRangeFilter value={range} onChange={setRange} />
        {/* #85: HubSpot's "Create segment" of the contacts the filters count. */}
        <button
          type="button"
          className="btn-crm btn-crm--ghost btn-crm--sm seqe-bar__end"
          disabled={!data?.contactIds.length}
          title={data?.contactIds.length ? undefined : 'No enrollments to add'}
          onClick={() => setSegmentOpen(true)}
        >
          Create segment
        </button>
      </div>

      {state.forbidden ? (
        <p className="seqm-empty">You do not have permission to see sequence analytics.</p>
      ) : state.error ? (
        <p className="seqm-empty crm-text-danger" role="alert">
          {state.error}{' '}
          <button
            type="button"
            className="btn-crm btn-crm--ghost btn-crm--sm"
            onClick={state.reload}
          >
            Try again
          </button>
        </p>
      ) : !data ? (
        <p className="seqm-empty">Loading performance…</p>
      ) : (
        <StatDrill filters={filterNotes}>
          <div className={cn('seqa-body', state.loading && 'is-loading')} aria-busy={state.loading}>
            {data.capped ? (
              <p className="seqa-note" role="status">
                Only the newest 20,000 enrollments are counted. Narrow the filters for exact
                numbers.
              </p>
            ) : null}
            {dynamic ? (
              <>
                <Funnel data={data} currency={me.business.currency} />
                <div className="seqa-grid-2">
                  <Engagement data={data} />
                  <LeadQuality data={data} />
                </div>
              </>
            ) : (
              <>
                <Insights data={data} currency={me.business.currency} />
                <div className="seqa-grid-2">
                  <EmailEngagement data={data} />
                  <CompanyInsights data={data} />
                </div>
              </>
            )}
            <StepPerformance
              steps={steps}
              rows={data.steps}
              dynamic={dynamic}
              templates={templates}
              mode={mode}
              onMode={setMode}
            />
            <PerformanceOverTime data={data} basicMetrics />
            <StatusByStep steps={steps} data={data} />
          </div>
        </StatDrill>
      )}
      <CreateSegmentDialog
        open={segmentOpen}
        contactIds={data?.contactIds ?? []}
        onClose={() => setSegmentOpen(false)}
      />
    </div>
  );
}

/**
 * "Enrollment status by step" (QA 16 Oct #113): where the enrollments are, per step that is not
 * a wait, by status. An enrollment waiting before a step counts at that step.
 */
function StatusByStep({ steps, data }: { steps: SequenceStep[]; data: SequenceAnalytics }) {
  const actions = steps.flatMap((step, index) => (step.type === 'wait' ? [] : [index]));
  const statuses = Object.keys(STATUS_LABELS) as SequenceAnalyticsStatus[];
  const byAction = new Map<number, Record<SequenceAnalyticsStatus, number>>();
  for (const row of data.stepStatus ?? []) {
    const at = actions.find((index) => index >= row.stepIndex) ?? actions.at(-1);
    if (at === undefined) continue;
    const sum = byAction.get(at) ?? {
      scheduled: 0,
      in_progress: 0,
      paused: 0,
      finished: 0,
      error: 0,
    };
    for (const s of statuses) sum[s] += row[s];
    byAction.set(at, sum);
  }
  return (
    <Card title="Enrollment status by step">
      {byAction.size === 0 ? (
        <p className="seqm-empty">
          There is no data to show in this time frame. Try changing the date range.
        </p>
      ) : (
        <StackedBarChart
          ariaLabel="Enrollments per step by status"
          xTitle="Enrollments"
          yTitle="Step"
          legend={statuses.map((s) => ({
            key: s,
            label: STATUS_LABELS[s],
            color: STATUS_COLORS[s],
          }))}
          rows={actions.map((index, n) => ({
            key: String(index),
            label: String(n + 1),
            segments: statuses.map((s) => ({
              key: s,
              label: STATUS_LABELS[s],
              color: STATUS_COLORS[s],
              value: byAction.get(index)?.[s] ?? 0,
            })),
          }))}
        />
      )}
    </Card>
  );
}

/** Dynamic sequences: total revenue, then enrolled → … → deals closed as falling bars. */
function Funnel({ data, currency }: { data: SequenceAnalytics; currency: string }) {
  const i = data.insights;
  const revenue = i.revenue.find((r) => r.currency === currency) ?? i.revenue[0];
  const others = i.revenue.filter((r) => r !== revenue);
  const stages = [
    ['Enrolled', i.enrollments],
    ['Opened', data.email.opened],
    ['Clicked', data.email.clicked],
    ['Replied', i.replies],
    ['Meetings', i.meetings],
    ['Deals created', i.dealsCreated],
    ['Deals closed', i.dealsClosed],
  ] as const;
  return (
    <Card title="Insights">
      <div className="seqp-funnel">
        <div className="seqp-funnel__revenue">
          <strong>{revenueText(revenue?.amount ?? 0, revenue?.currency ?? currency)}</strong>
          <span>
            Total Revenue
            {others.length ? (
              <InfoIcon
                hint={`Also: ${others.map((r) => revenueText(r.amount, r.currency)).join(', ')}.`}
              />
            ) : null}
          </span>
        </div>
        <ol className="seqp-funnel__stages">
          {stages.map(([label, value], index) => (
            <li
              key={label}
              className="seqp-funnel__stage"
              // Each stage a little lower than the one before (design: a descending funnel).
              style={{ height: `${100 - index * 7}%` }}
            >
              <span>{label}</span>
              <strong>{value.toLocaleString()}</strong>
            </li>
          ))}
        </ol>
      </div>
    </Card>
  );
}

function Engagement({ data }: { data: SequenceAnalytics }) {
  const i = data.insights;
  const none = Math.max(0, i.enrollments - i.engaged);
  return (
    <Card title="Engagement">
      <div className="seqa-stats seqa-stats--3">
        <Stat
          label="Engaged rate"
          hint="Enrollments that opened, clicked or replied to one of their emails."
          value={pct(i.engaged, i.enrollments)}
          sub={`${i.engaged.toLocaleString()} Contacts`}
        />
        <Stat
          label="No engagement"
          value={pct(none, i.enrollments)}
          sub={`${none.toLocaleString()} Contacts`}
        />
        <Stat
          label="No response"
          value={pct(i.noResponse, i.enrollments)}
          sub={`${i.noResponse.toLocaleString()} No Response`}
        />
      </div>
    </Card>
  );
}

function LeadQuality({ data }: { data: SequenceAnalytics }) {
  const e = data.email;
  return (
    <Card title="Lead quality">
      <div className="seqa-stats seqa-stats--3">
        <Stat
          label="Bounce rate"
          value={pct(e.bounced, e.emailed)}
          sub={`${e.bounced.toLocaleString()} Bounced`}
        />
        <Stat
          label="Unsubscribe rate"
          value={pct(e.unsubscribed, e.emailed)}
          sub={`${e.unsubscribed.toLocaleString()} Unsubscribes`}
        />
        <Stat
          label="Leads reached"
          hint="Enrollments sent at least one email."
          value={pct(e.emailed, data.insights.enrollments)}
          sub={`${e.emailed.toLocaleString()} Contacts`}
        />
      </div>
    </Card>
  );
}

function StepPerformance({
  steps,
  rows,
  dynamic,
  templates,
  mode,
  onMode,
}: {
  steps: SequenceStep[];
  rows: StepRow[];
  dynamic: boolean;
  templates: EmailTemplate[] | null;
  mode: 'rates' | 'counts';
  onMode: (mode: 'rates' | 'counts') => void;
}) {
  const byIndex = new Map(rows.map((r) => [r.stepIndex, r]));
  const actions = steps.flatMap((step, index) => (step.type === 'wait' ? [] : [{ step, index }]));
  const auto = dynamic ? actions.filter((a) => a.step.lane !== 'rep') : actions;
  const rep = dynamic ? actions.filter((a) => a.step.lane === 'rep') : [];

  const value = (part: number, whole: number) =>
    mode === 'counts' ? part.toLocaleString() : pct(part, whole, 0);

  const row = ({ step, index }: (typeof actions)[number], n: number) => {
    const r = byIndex.get(index);
    const done = r?.done ?? 0;
    const isEmail = step.type === 'automated_email';
    const kind = isEmail ? null : repKindOf(step);
    const meta = kind ? REP_KINDS.find((k) => k.key === kind) : null;
    const template =
      step.type === 'automated_email' || step.type === 'manual_email'
        ? (templates?.find((t) => t.id === step.templateId) ?? null)
        : null;
    const title =
      step.type === 'automated_email'
        ? template?.subject || step.subject || 'Automated email'
        : step.type === 'manual_email'
          ? step.title || template?.subject || step.subject || 'Manual email task'
          : 'title' in step && step.title
            ? step.title
            : (meta?.label ?? 'Task');
    const cells: Array<[string, string]> = isEmail
      ? [
          [done.toLocaleString(), 'Sent'],
          [value(r?.meetings ?? 0, done), 'Meetings'],
          [value(r?.opened ?? 0, done), 'Opens'],
          [value(r?.clicked ?? 0, done), 'Clicks'],
          [value(r?.replied ?? 0, done), 'Replies'],
          // #85: HubSpot's "Personalized" (tooltip "Emails personalized"): edited per contact.
          [value(r?.personalized ?? 0, done), 'Personalized'],
        ]
      : [
          [done.toLocaleString(), 'Created'],
          [value(r?.completed ?? 0, done), 'Completed'],
          [value(r?.meetings ?? 0, done), 'Meetings'],
        ];
    return (
      <li key={index} className="seqp-step">
        <StepIcon kind={isEmail ? 'send' : (kind ?? 'todo')} />
        <div className="seqp-step__name">
          <span>
            <strong>Step {n}</strong> {isEmail ? 'Automated email' : (meta?.label ?? 'Task')}
          </span>
          <span className="seqp-step__title">{title}</span>
        </div>
        {cells.map(([v, label]) => (
          <div key={label} className="seqp-step__cell">
            <strong>{v}</strong>
            <span>{label}</span>
          </div>
        ))}
      </li>
    );
  };

  return (
    <Card
      title="Step performance"
      className="seqp-steps"
      actions={
        <div className="seqa-toggle" role="group" aria-label="Show">
          {(['rates', 'counts'] as const).map((m) => (
            <button
              key={m}
              type="button"
              className={cn(mode === m && 'is-active')}
              aria-pressed={mode === m}
              onClick={() => onMode(m)}
            >
              {m === 'rates' ? 'Rates' : 'Counts'}
            </button>
          ))}
        </div>
      }
    >
      {actions.length === 0 ? (
        <p className="seqm-empty">This sequence has no steps yet.</p>
      ) : dynamic ? (
        <>
          <div className="seqp-lane seqp-lane--auto">Automated outreach</div>
          <ol className="seqp-list">{auto.map((a, i) => row(a, i + 1))}</ol>
          <div className="seqp-lane seqp-lane--rep">Rep-led outreach</div>
          {rep.length ? (
            <ol className="seqp-list">{rep.map((a, i) => row(a, i + 1))}</ol>
          ) : (
            <p className="seqm-empty">No rep-led steps yet.</p>
          )}
        </>
      ) : (
        <ol className="seqp-list">{actions.map((a, i) => row(a, i + 1))}</ol>
      )}
    </Card>
  );
}
