'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { Field, FormDrawer } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import {
  getSequenceSendUsage,
  listScheduledSequenceEmails,
  listScheduledSequenceSenders,
  rescheduleScheduledSequenceEmail,
  skipScheduledSequenceEmail,
} from '@/features/sequences/api.client';
import type {
  ScheduledSequenceEmail,
  ScheduledSequenceSender,
  SequenceSendUsage,
} from '@/features/sequences/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { addDays, fromZoned, toZoned } from '@/lib/utils/timezone';
import { ChevronDown, DropMenu, type DropMenuItem } from './DropMenu';
import { getSendUsage, type SendUsage } from '@/features/inbox/api.client';

/** Step type names as the Scheduled design writes them. */
const STEP_LABELS: Record<string, string> = {
  automated_email: 'Automated email',
  manual_email: 'Manual email task',
  call_task: 'Call task',
  task: 'Task',
};

const PAGE_LIMIT = 10;

/** Send-date presets, from now. */
const WHEN = [
  { key: '', label: 'Any time', hours: 0 },
  { key: '24h', label: 'Next 24 hours', hours: 24 },
  { key: '7d', label: 'Next 7 days', hours: 24 * 7 },
  { key: '30d', label: 'Next 30 days', hours: 24 * 30 },
] as const;
type WhenKey = (typeof WHEN)[number]['key'];

type SortKey = 'scheduledAt' | 'contact' | 'sequence' | 'step' | 'subject';
type SortDir = 'asc' | 'desc';

/**
 * "14 Oct 2026, 3:30 PM PDT": the send date and time in your profile time zone, the one the
 * sending window uses (QA 14 Oct #48, QA 16 Oct #134); this browser's clock until it is known.
 */
function sendDate(iso: string, timeZone: string | undefined): string {
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return '-';
  return d.toLocaleString(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    timeZoneName: 'short',
    timeZone,
  });
}

/** The `datetime-local` value of an instant, on the wall clock of `timeZone` (or the browser's). */
function toDateTimeLocalValue(iso: string, timeZone: string | undefined): string {
  const parsed = new Date(iso);
  if (Number.isNaN(parsed.getTime())) return '';
  const pad = (n: number) => String(n).padStart(2, '0');
  if (timeZone) {
    const { day, hours } = toZoned(parsed, timeZone);
    const minutes = Math.round(hours * 60);
    return `${day}T${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}`;
  }
  return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())}T${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
}

/** A `datetime-local` value read on the wall clock of `timeZone` (or the browser's). */
function fromDateTimeLocalValue(value: string, timeZone: string | undefined): Date {
  const match = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})/.exec(value);
  if (!timeZone || !match) return new Date(value);
  return fromZoned(match[1]!, Number(match[2]) + Number(match[3]) / 60, timeZone);
}

/** "Today", "Tomorrow", then "Mon 26 Oct", for the usage panel's days. */
function dayLabel(day: string, today: string): string {
  if (day === today) return 'Today';
  if (day === addDays(today, 1)) return 'Tomorrow';
  return new Date(`${day}T12:00:00Z`).toLocaleDateString(undefined, {
    weekday: 'short',
    day: 'numeric',
    month: 'short',
    timeZone: 'UTC',
  });
}

const contactLabel = (row: ScheduledSequenceEmail) =>
  row.contactName ?? row.contactEmail ?? `Contact ${row.contactId.slice(0, 8)}`;

/** Scheduled tab: the emails sequences will send next, with reschedule and skip. */
export function SequencesScheduledTab({
  sequences,
}: {
  sequences: Array<{ id: string; name: string }>;
}) {
  const toast = useToast();
  const { confirm, dialog: confirmDialog } = useConfirm();
  /** The sender's email limits, like HubSpot's panel on this tab (QA 14 Oct #59). */
  const [usage, setUsage] = useState<SendUsage | null>(null);
  /** Your mailbox and its sequence emails per day (QA 16 Oct #121). */
  const [perDay, setPerDay] = useState<SequenceSendUsage | null>(null);
  const [rows, setRows] = useState<ScheduledSequenceEmail[]>([]);
  const [loading, setLoading] = useState(true);
  const timeZone = perDay?.timezone;
  const [error, setError] = useState<string | null>(null);
  const [senders, setSenders] = useState<ScheduledSequenceSender[]>([]);

  const [search, setSearch] = useState('');
  const [query, setQuery] = useState('');
  const [sequenceId, setSequenceId] = useState('');
  const [senderId, setSenderId] = useState('');
  const [when, setWhen] = useState<WhenKey>('');
  // Soonest first, the order the API pages in (sorting only reorders the page shown).
  const [sort, setSort] = useState<{ key: SortKey; dir: SortDir }>({
    key: 'scheduledAt',
    dir: 'asc',
  });

  const [cursor, setCursor] = useState<string | undefined>();
  const [trail, setTrail] = useState<string[]>([]);
  const [nextCursor, setNextCursor] = useState<string | null>(null);
  const [reloadKey, setReloadKey] = useState(0);

  const [busyId, setBusyId] = useState<string | null>(null);
  const [rescheduleTarget, setRescheduleTarget] = useState<ScheduledSequenceEmail | null>(null);
  const [rescheduleError, setRescheduleError] = useState<string | null>(null);

  const resetPaging = () => {
    setCursor(undefined);
    setTrail([]);
  };

  useEffect(() => {
    const timer = window.setTimeout(() => {
      setQuery(search.trim());
      setCursor(undefined);
      setTrail([]);
    }, 250);
    return () => window.clearTimeout(timer);
  }, [search]);

  useEffect(() => {
    let alive = true;
    getSendUsage().then(
      (u) => {
        if (alive) setUsage(u);
      },
      () => {},
    );
    getSequenceSendUsage().then(
      (u) => {
        if (alive) setPerDay(u);
      },
      () => {},
    );
    return () => {
      alive = false;
    };
  }, [reloadKey]);

  useEffect(() => {
    let cancelled = false;
    listScheduledSequenceSenders().then(
      (res) => {
        if (!cancelled) setSenders(res.data);
      },
      () => {
        if (!cancelled) setSenders([]);
      },
    );
    return () => {
      cancelled = true;
    };
  }, [reloadKey]);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    const hours = WHEN.find((w) => w.key === when)?.hours ?? 0;
    const now = Date.now();
    listScheduledSequenceEmails({
      search: query || undefined,
      sequenceId: sequenceId || undefined,
      senderMailboxId: senderId || undefined,
      from: hours ? new Date(now).toISOString() : undefined,
      to: hours ? new Date(now + hours * 3_600_000).toISOString() : undefined,
      limit: PAGE_LIMIT,
      cursor,
    })
      .then((page) => {
        if (cancelled) return;
        setRows(page.data);
        setNextCursor(page.nextCursor);
      })
      .catch((err) => {
        if (cancelled) return;
        setError(errorText(err));
        setRows([]);
        setNextCursor(null);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [query, sequenceId, senderId, when, cursor, reloadKey]);

  // The API pages by send date; the other columns sort the rows of the page.
  const sorted = useMemo(() => {
    const value = (row: ScheduledSequenceEmail): string | number => {
      switch (sort.key) {
        case 'scheduledAt':
          return new Date(row.scheduledAt).getTime();
        case 'contact':
          return contactLabel(row).toLowerCase();
        case 'sequence':
          return row.sequenceName.toLowerCase();
        case 'step':
          return row.stepIndex;
        case 'subject':
          return (row.subject ?? '').toLowerCase();
      }
    };
    const out = [...rows].sort((a, b) => {
      const x = value(a);
      const y = value(b);
      if (x === y) return 0;
      return typeof x === 'string' && typeof y === 'string' ? x.localeCompare(y) : x < y ? -1 : 1;
    });
    return sort.dir === 'desc' ? out.reverse() : out;
  }, [rows, sort]);

  const page = trail.length + 1;
  const goTo = (target: number) => {
    if (target === page + 1 && nextCursor) {
      setTrail((t) => [...t, cursor ?? '']);
      setCursor(nextCursor);
    } else if (target < page) {
      setCursor(target === 1 ? undefined : trail[target - 1] || undefined);
      setTrail((t) => t.slice(0, target - 1));
    }
  };

  const onSkip = async (row: ScheduledSequenceEmail) => {
    if (busyId) return;
    if (
      !(await confirm({
        title: 'Skip email',
        message: 'Skip this scheduled email step? The contact moves on to the next step.',
        confirmLabel: 'Skip',
      }))
    ) {
      return;
    }
    setBusyId(row.enrollmentId);
    try {
      await skipScheduledSequenceEmail(row.enrollmentId);
      toast('Scheduled email skipped.', 'success');
      setReloadKey((n) => n + 1);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusyId(null);
    }
  };

  const onReschedule = async (data: Record<string, string>) => {
    if (!rescheduleTarget) return false;
    const raw = (data.sendAt ?? '').trim();
    const sendAt = fromDateTimeLocalValue(raw, timeZone);
    if (!raw || Number.isNaN(sendAt.getTime())) {
      setRescheduleError('Pick a valid send time.');
      return false;
    }
    try {
      await rescheduleScheduledSequenceEmail(rescheduleTarget.enrollmentId, {
        sendAt: sendAt.toISOString(),
      });
      setRescheduleError(null);
      setRescheduleTarget(null);
      toast('Scheduled email moved.', 'success');
      setReloadKey((n) => n + 1);
      return true;
    } catch (err) {
      setRescheduleError(errorText(err));
      return false;
    }
  };

  const filterMenu = (
    label: string,
    current: string,
    options: Array<{ value: string; label: string }>,
    onPick: (value: string) => void,
    anyLabel: string,
  ) => {
    const picked = options.find((o) => o.value === current);
    const items: DropMenuItem[] = [
      { key: '', label: anyLabel, active: !current, onSelect: () => onPick('') },
      ...options.map((o) => ({
        key: o.value,
        label: o.label,
        active: o.value === current,
        onSelect: () => onPick(o.value),
      })),
    ];
    return (
      <DropMenu
        trigger={
          <>
            {label}
            {picked ? (
              <>
                : <strong>{picked.label}</strong>
              </>
            ) : null}
            <ChevronDown size={12} />
          </>
        }
        triggerClassName={cn('seqa-filter', picked && 'is-set')}
        align="start"
        items={items}
      />
    );
  };

  const th = (key: SortKey, label: string) => {
    const dir = sort.key === key ? sort.dir : null;
    return (
      <th
        scope="col"
        aria-sort={dir === 'asc' ? 'ascending' : dir === 'desc' ? 'descending' : 'none'}
      >
        <button
          type="button"
          className={cn('seqm-sort', dir && 'is-sorted')}
          title={
            key === 'scheduledAt' ? 'Sort by send date' : `Sort this page by ${label.toLowerCase()}`
          }
          onClick={() =>
            setSort({
              key,
              dir:
                dir === 'asc'
                  ? 'desc'
                  : dir === 'desc'
                    ? 'asc'
                    : key === 'scheduledAt'
                      ? 'desc'
                      : 'asc',
            })
          }
        >
          <span>{label}</span>
          <svg className="seqm-sort__icon" viewBox="0 0 24 24" width="13" height="13" aria-hidden>
            {dir === 'asc' ? (
              <path d="M12 19V5m-6 6 6-6 6 6" fill="none" stroke="currentColor" strokeWidth="2" />
            ) : dir === 'desc' ? (
              <path d="M12 5v14m-6-6 6 6 6-6" fill="none" stroke="currentColor" strokeWidth="2" />
            ) : (
              <path
                d="M8 18V6M4 10l4-4 4 4M16 6v12m-4-4 4 4 4-4"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.8"
              />
            )}
          </svg>
        </button>
      </th>
    );
  };

  // Sequences SQ-5 (Q-05): with no connected inbox and nothing scheduled, HubSpot's tab shows
  // only an illustration and its empty text: no intro, filters or table headers.
  if (
    usage &&
    !usage.connected &&
    !loading &&
    !error &&
    rows.length === 0 &&
    !query &&
    !sequenceId &&
    !senderId &&
    !when
  ) {
    return (
      <div className="seqs seqs-empty">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src="/crm/assets/img/sales-upcoming-events.svg" alt="" />
        <p>All emails you schedule to send with a sequence will appear here.</p>
      </div>
    );
  }

  return (
    <div className="seqs">
      {usage?.connected ? (
        <section className="seqs-limits" aria-label="Your email limits">
          {perDay?.email ? (
            <p className="seqs-limits__sender">
              Email limit and usage for <strong>{perDay.email}</strong>
            </p>
          ) : null}
          <div>
            <strong>
              {usage.daily.used.toLocaleString()} of {usage.daily.limit.toLocaleString()}
            </strong>
            <span>emails in the last 24 hours</span>
            <span className="seqs-limits__bar" aria-hidden>
              <span
                style={{
                  width: `${Math.min(100, usage.daily.limit ? (usage.daily.used / usage.daily.limit) * 100 : 0)}%`,
                }}
              />
            </span>
          </div>
          <div>
            <strong>
              {usage.hourly.used.toLocaleString()} of {usage.hourly.limit.toLocaleString()}
            </strong>
            <span>in the last hour</span>
          </div>
          <div>
            <strong>{rows.length.toLocaleString()}</strong>
            <span>scheduled{rows.length >= PAGE_LIMIT ? '+' : ''} (shown here)</span>
          </div>
          {perDay && perDay.days.length ? (
            <table className="seqs-days">
              <caption>Sent and scheduled sequence emails</caption>
              <thead>
                <tr>
                  <th scope="col">
                    <span className="crm-visually-hidden">Day</span>
                  </th>
                  {perDay.days.map((d) => (
                    <th key={d.day} scope="col">
                      {dayLabel(d.day, perDay.days[0]!.day)}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th scope="row">Sent</th>
                  {perDay.days.map((d) => (
                    <td key={d.day}>{d.sent.toLocaleString()}</td>
                  ))}
                </tr>
                <tr>
                  <th scope="row">Scheduled</th>
                  {perDay.days.map((d) => (
                    <td key={d.day}>{d.scheduled.toLocaleString()}</td>
                  ))}
                </tr>
              </tbody>
            </table>
          ) : null}
          <p className="seqs-limits__note">
            Your limits count every email you send: one-to-one, sequences and workflows. Over a
            limit, sequence emails wait until there is room; none are dropped. Contacts who would
            take you over your daily limit won&apos;t enroll in a sequence.
          </p>
        </section>
      ) : null}
      <p className="seqs-intro">
        Emails queued by your sequences, with their send time in your time zone
        {timeZone ? ` (${timeZone})` : ''}. Each sequence sends within its sending window, in the
        contact&apos;s or the sender&apos;s time zone as set in its Settings.
      </p>

      <div className="seqs-toolbar">
        <div className="seqm-search">
          <input
            type="search"
            placeholder="Search contact or sequence"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            aria-label="Search scheduled emails"
          />
          <svg
            className="icon iconSize-16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.8"
            aria-hidden
          >
            <circle cx="11" cy="11" r="7" />
            <path d="m20 20-3.5-3.5" />
          </svg>
        </div>
        {filterMenu(
          'Sequence',
          sequenceId,
          sequences.map((s) => ({ value: s.id, label: s.name })),
          (v) => {
            setSequenceId(v);
            resetPaging();
          },
          'All sequences',
        )}
        {filterMenu(
          'Sender',
          senderId,
          senders.map((s) => ({
            value: s.mailboxId,
            label: s.email ?? s.name ?? `Mailbox ${s.mailboxId.slice(0, 8)}`,
          })),
          (v) => {
            setSenderId(v);
            resetPaging();
          },
          'All senders',
        )}
        {filterMenu(
          'Send date',
          when,
          WHEN.filter((w) => w.key).map((w) => ({ value: w.key, label: w.label })),
          (v) => {
            setWhen(v as WhenKey);
            resetPaging();
          },
          'Any time',
        )}
      </div>

      {error ? <p className="seqm-empty crm-text-danger">{error}</p> : null}

      <div className="seqm-table-wrap seqs-table-wrap">
        <table className="seqm-table seqa-table">
          <thead>
            <tr>
              {th('scheduledAt', 'Send time')}
              {th('contact', 'Contact')}
              {th('sequence', 'Sequence')}
              {th('step', 'Step')}
              {th('subject', 'Subject')}
              <th scope="col">
                <span className="crm-visually-hidden">Actions</span>
              </th>
            </tr>
          </thead>
          <tbody>
            {loading && rows.length === 0 ? (
              <tr>
                <td colSpan={6} className="seqm-empty">
                  Loading scheduled emails…
                </td>
              </tr>
            ) : sorted.length === 0 ? (
              <tr>
                <td colSpan={6} className="seqm-empty">
                  {query || sequenceId || senderId || when
                    ? 'No scheduled emails match these filters.'
                    : // Sequences QA BUG-05: the design's empty text (sequences.js).
                      'All emails you schedule to send with a sequence will appear here.'}
                </td>
              </tr>
            ) : (
              sorted.map((row) => (
                <tr key={row.enrollmentId} className="seqm-row">
                  <td
                    className="crm-text-nowrap"
                    title={new Date(row.scheduledAt).toLocaleString(undefined, { timeZone })}
                  >
                    {sendDate(row.scheduledAt, timeZone)}
                    {row.status === 'queued' ? <div className="seqm-meta">Sending now</div> : null}
                  </td>
                  <td>
                    <Link className="seqa-contact" href={`/contacts/${row.contactId}`}>
                      {contactLabel(row)}
                    </Link>
                    {row.contactEmail ? <div className="seqm-meta">{row.contactEmail}</div> : null}
                  </td>
                  <td>
                    <Link className="seqm-name" href={`/sequences/${row.sequenceId}`}>
                      {row.sequenceName}
                    </Link>
                  </td>
                  <td className="crm-text-nowrap">
                    Step {row.stepNumber ?? row.stepIndex + 1} ·{' '}
                    {STEP_LABELS[row.stepType] ?? row.stepType}
                  </td>
                  <td>{row.subject ?? <span className="crm-text-muted">No subject</span>}</td>
                  <td className="crm-text-end">
                    <div className="seqm-row__tools seqs-tools">
                      <DropMenu
                        trigger={
                          <>
                            Actions <ChevronDown size={12} />
                          </>
                        }
                        triggerClassName="btn-crm btn-crm--outline btn-crm--sm seqm-pill"
                        ariaLabel={`Actions for the email to ${contactLabel(row)}`}
                        items={[
                          {
                            key: 'reschedule',
                            label: 'Reschedule',
                            disabled: !row.canManage || busyId !== null,
                            title: row.canManage ? undefined : 'You cannot change this email',
                            onSelect: () => {
                              setRescheduleError(null);
                              setRescheduleTarget(row);
                            },
                          },
                          {
                            key: 'skip',
                            label: 'Skip email',
                            disabled: !row.canManage || busyId !== null,
                            title: row.canManage ? undefined : 'You cannot change this email',
                            onSelect: () => void onSkip(row),
                          },
                        ]}
                      />
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {page > 1 || nextCursor ? (
        <nav className="seqa-pager" aria-label="Pages">
          <button type="button" disabled={page <= 1 || loading} onClick={() => goTo(page - 1)}>
            ‹ Prev
          </button>
          {/* Cursor paging: the pages seen so far, and the next one. */}
          {Array.from({ length: page + (nextCursor ? 1 : 0) }, (_, i) => i + 1).map((p) => (
            <button
              key={p}
              type="button"
              className={cn(p === page && 'is-current')}
              aria-current={p === page ? 'page' : undefined}
              disabled={loading}
              onClick={() => goTo(p)}
            >
              {p}
            </button>
          ))}
          <button type="button" disabled={!nextCursor || loading} onClick={() => goTo(page + 1)}>
            Next ›
          </button>
        </nav>
      ) : null}

      <FormDrawer
        id="rescheduleSequenceEmail"
        title="Reschedule email"
        submitLabel="Save"
        open={Boolean(rescheduleTarget)}
        onClose={() => {
          setRescheduleTarget(null);
          setRescheduleError(null);
        }}
        onSubmit={onReschedule}
      >
        {rescheduleError ? <Alert tone="danger">{rescheduleError}</Alert> : null}
        <div className="form-grid">
          <Field label="Sequence" htmlFor="rescheduleSequenceName" className="span-2">
            <input
              id="rescheduleSequenceName"
              className="input"
              value={rescheduleTarget?.sequenceName ?? ''}
              readOnly
            />
          </Field>
          <Field label="Contact" htmlFor="rescheduleContactName" className="span-2">
            <input
              id="rescheduleContactName"
              className="input"
              value={rescheduleTarget ? contactLabel(rescheduleTarget) : ''}
              readOnly
            />
          </Field>
          <Field
            label={timeZone ? `Send at (${timeZone})` : 'Send at'}
            htmlFor="rescheduleSendAt"
            className="span-2"
          >
            <input
              id="rescheduleSendAt"
              name="sendAt"
              className="input"
              type="datetime-local"
              required
              defaultValue={
                rescheduleTarget ? toDateTimeLocalValue(rescheduleTarget.scheduledAt, timeZone) : ''
              }
            />
          </Field>
        </div>
      </FormDrawer>
      {confirmDialog}
    </div>
  );
}
