'use client';

// G9 (issue 708), beyond the design: the badge above the Contacts table for the person's latest
// bulk "Enroll in sequence". It shows the progress while the job runs, then how many were
// enrolled and refused, until dismissed (the dismissed id is kept in this browser).
import { useEffect, useState } from 'react';
import { LpIcon } from '@/features/list-page/ui/LpIcon';
import { LpModal } from '@/features/list-page/ui/LpModal';
import { cn } from '@/lib/utils/cn';
import { getBulkOperation, listBulkOperations, type BulkOperation } from '../api.client';
import {
  ENROLL_BADGE_FAILS,
  dismissedKey,
  enrollBadge,
  readDismissed,
  refusedReasons,
  writeDismissed,
  type EnrollBadge as Badge,
} from '../enrollBadge';

const storage = () => {
  try {
    return window.localStorage;
  } catch {
    return null;
  }
};

export function EnrollBadgeView({
  badge,
  stale,
  onDismiss,
  onRefused,
  onRetry,
}: {
  badge: Badge;
  /** The status checks kept failing. */
  stale: boolean;
  onDismiss: () => void;
  onRefused: () => void;
  onRetry: () => void;
}) {
  return (
    <div className="lp-notes">
      <div className={cn('lp-enroll-badge', `lp-enroll-badge--${badge.tone}`)} role="status">
        <LpIcon name="sequence" />
        <span className="lp-enroll-badge__text">{badge.text}</span>
        {badge.refused > 0 ? (
          <button type="button" className="lp-link lp-enroll-badge__refused" onClick={onRefused}>
            {`${badge.refused.toLocaleString()} refused`}
          </button>
        ) : null}
        {badge.running && badge.percent !== null ? (
          <span className="bulk-bar__meter lp-enroll-badge__meter" aria-hidden>
            <span style={{ width: `${badge.percent}%` }} />
          </span>
        ) : null}
        {stale ? (
          <span className="lp-enroll-badge__stale">
            {"Couldn't check the enrollment. "}
            <button type="button" className="lp-link" onClick={onRetry}>
              Retry
            </button>
          </span>
        ) : null}
        {badge.running ? null : (
          <button
            type="button"
            className="lp-enroll-badge__x"
            aria-label="Dismiss enrollment status"
            onClick={onDismiss}
          >
            <LpIcon name="x" />
          </button>
        )}
      </div>
    </div>
  );
}

export function RefusedReasons({
  reasons,
  more,
}: {
  reasons: Array<{ message: string; count: number }>;
  more: number;
}) {
  return (
    <>
      <ul className="lp-enroll-refused">
        {reasons.map((r) => (
          <li key={r.message}>
            <span>{r.message}</span> <b>{r.count.toLocaleString()}</b>
          </li>
        ))}
      </ul>
      {more ? (
        <p className="lp-enroll-refused__more">{`${more.toLocaleString()} more not listed`}</p>
      ) : null}
    </>
  );
}

/**
 * The badge itself: loads the person's latest enrollment of contacts, follows one the bulk bar
 * just started (`started`), and polls while it runs, as the bar does (1.5 s, 4 s after a failure).
 * A failed load shows nothing: the badge is extra.
 */
export function EnrollBadge({
  userId,
  started,
}: {
  userId: string;
  /** The enrollment the bulk bar just started, if any. */
  started: BulkOperation | null;
}) {
  const key = dismissedKey(userId);
  const [op, setOp] = useState<BulkOperation | null>(null);
  const [fails, setFails] = useState(0);
  const [dismissed, setDismissed] = useState<string | null>(null);
  const [refusedOpen, setRefusedOpen] = useState(false);
  const [now, setNow] = useState(() => new Date());

  useEffect(() => {
    setDismissed(readDismissed(storage(), key));
    let alive = true;
    listBulkOperations({
      objectType: 'contact',
      actions: ['enroll_sequence'],
      mine: true,
      limit: 1,
    }).then(
      (page) => {
        // One the bar started meanwhile is newer.
        if (alive) setOp((cur) => cur ?? page.data[0] ?? null);
      },
      () => {},
    );
    return () => {
      alive = false;
    };
  }, [key]);

  useEffect(() => {
    if (started?.action === 'enroll_sequence') {
      setOp(started);
      setFails(0);
      setNow(new Date());
    }
  }, [started]);

  const running = op?.status === 'queued' || op?.status === 'running';
  useEffect(() => {
    if (!op || !running || fails >= ENROLL_BADGE_FAILS) return;
    let alive = true;
    const timer = window.setTimeout(
      () => {
        getBulkOperation(op.id).then(
          (next) => {
            if (!alive) return;
            setOp(next);
            setFails(0);
            setNow(new Date());
          },
          () => {
            if (alive) setFails((n) => n + 1);
          },
        );
      },
      fails ? 4000 : 1500,
    );
    return () => {
      alive = false;
      window.clearTimeout(timer);
    };
  }, [op, running, fails]);

  const badge = op ? enrollBadge(op, now) : null;
  if (!op || !badge || dismissed === op.id) return null;
  const refused = refusedReasons(op);
  return (
    <>
      <EnrollBadgeView
        badge={badge}
        stale={fails >= ENROLL_BADGE_FAILS}
        onDismiss={() => {
          writeDismissed(storage(), key, op.id);
          setDismissed(op.id);
        }}
        onRefused={() => setRefusedOpen(true)}
        onRetry={() => setFails(0)}
      />
      <LpModal
        open={refusedOpen}
        title="Contacts not enrolled"
        onClose={() => setRefusedOpen(false)}
        className="lp-modal--pick"
      >
        <RefusedReasons reasons={refused.reasons} more={refused.more} />
      </LpModal>
    </>
  );
}
