'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CrmModal } from '@/components/crm/FormDrawer';
import type { Sequence } from '@/features/sequences/types';
import { ChevronDown, DropMenu } from '@/features/sequences/ui/DropMenu';
import { EnrollOneContact } from '@/features/sequences/ui/EnrollPreviewDialog';
import { NO_MAILBOX_TEXT as SHARED_NO_MAILBOX_TEXT } from '@/features/sequences/ui/EnrollReview';
import { SortGlyph } from '@/features/sequences/ui/shared';
import {
  ANY_OWNER,
  FIRST_SORT,
  emptyPickerText,
  nextSort,
  ownerChoices,
  pickerRows,
  stepCountLabel,
  type PickerSort,
  type PickerSortKey,
} from './enrollSequence';

const MODAL_ID = 'enrollSequenceModal';

/** Whether the record page's sequence list is still loading, failed, or loaded. */
export type SequencesLoad = 'loading' | 'failed' | 'ready';

export const LOAD_FAILED_TEXT = 'Sequences could not be loaded. Refresh the page and try again.';

/** Master's sentence when the user has no connected mailbox (the Sequences card says the same). */
export const NO_MAILBOX_TEXT = SHARED_NO_MAILBOX_TEXT;

export interface EnrollSequenceSender {
  mailboxId: string | null;
  /** Connected and ready to send. */
  ready: boolean;
  /** "<user name> (<mailbox email>)", the design's one "Send emails from" option (:846). */
  label: string;
}

/**
 * "Enroll in a sequence" from the contact record, as the design's `sequence()`
 * (record-popups-hs.js:822-864): "Select sequence" lists the sequences with search, an Owner filter
 * and sortable columns; picking one shows "Enroll in sequence": the shared enroll review
 * (SEQ-R-B4: start step, time zone, send time, "Send emails from", email preview and edit), as
 * on the Sequences card and the sequence's own Enroll contacts.
 */
export function EnrollSequenceDialog({
  open,
  onClose,
  sequences,
  load,
  contactId,
  contactName,
  contactEmail,
  sender,
  formatDate,
  onEnrolled,
}: {
  open: boolean;
  onClose: () => void;
  /** The active sequences the record page loaded. */
  sequences: readonly Sequence[];
  load: SequencesLoad;
  contactId: string;
  contactName: string;
  contactEmail: string | null;
  sender: EnrollSequenceSender;
  /** A date in the user's format ("--" for none). */
  formatDate: (iso: string | null | undefined) => string;
  onEnrolled: () => void;
}) {
  const bodyRef = useRef<HTMLDivElement>(null);
  const [q, setQ] = useState('');
  const [ownerId, setOwnerId] = useState(ANY_OWNER);
  const [sort, setSort] = useState<PickerSort>(FIRST_SORT);
  const [pick, setPick] = useState<Sequence | null>(null);
  /** An enroll call is on its way: the dialog can't be closed or left until it answers. */
  const [busy, setBusy] = useState(false);
  const busyRef = useRef(false);
  const markBusy = useCallback((value: boolean) => {
    busyRef.current = value;
    setBusy(value);
  }, []);

  // Each opening starts on the list, as the design builds a new dialog each time. Reset on close
  // too, so a reopened dialog never mounts the last pick's enroll step (and its preview call).
  useEffect(() => {
    setQ('');
    setOwnerId(ANY_OWNER);
    setSort(FIRST_SORT);
    setPick(null);
  }, [open]);

  // Escape inside the Owner menu closes only the menu (both listen on the window). Nothing closes
  // while enrolling, as EnrollPreviewDialog.
  const close = useCallback(() => {
    if (busyRef.current || bodyRef.current?.querySelector('.seqm-menu')) return;
    onClose();
  }, [onClose]);
  const back = useCallback(() => {
    if (!busyRef.current) setPick(null);
  }, []);

  return (
    <CrmModal id={MODAL_ID} open={open} onClose={close}>
      <div className="modal__header">
        {pick ? (
          <button
            type="button"
            className="modal__close crm-seqpick__back"
            aria-label="Back"
            onClick={back}
            disabled={busy}
          >
            <CrmIcon name="arrow-left" className="iconSize-20" />
          </button>
        ) : null}
        <h2 className="modal__title" id={`${MODAL_ID}-title`}>
          {pick ? 'Enroll in sequence' : 'Select sequence'}
        </h2>
        <button
          type="button"
          className="modal__close"
          aria-label="Close"
          onClick={close}
          disabled={busy}
        >
          <CrmIcon name="x" className="iconSize-20" />
        </button>
      </div>
      {pick ? (
        <EnrollOneContact
          key={pick.id}
          open={open}
          sequence={pick}
          contact={{ id: contactId, name: contactName, email: contactEmail }}
          sender={sender}
          idPrefix="enrollSequence"
          onBusy={markBusy}
          onBack={back}
          onCancel={close}
          onDone={() => {
            onEnrolled();
            onClose();
          }}
        />
      ) : (
        <div ref={bodyRef} className="modal__body crm-seqpick">
          <SelectSequenceList
            sequences={sequences}
            load={load}
            q={q}
            onSearch={setQ}
            ownerId={ownerId}
            onOwner={setOwnerId}
            sort={sort}
            onSort={(key) => setSort((current) => nextSort(current, key))}
            formatDate={formatDate}
            onPick={setPick}
          />
        </div>
      )}
    </CrmModal>
  );
}

const COLUMNS: { key: PickerSortKey; label: string }[] = [
  { key: 'name', label: 'Name' },
  { key: 'owner', label: 'Created By' },
  { key: 'used', label: 'Last Used' },
  { key: 'modified', label: 'Last Modified' },
];

/** The design's list view (record-popups-hs.js:827-839). */
export function SelectSequenceList({
  sequences,
  load = 'ready',
  q,
  onSearch,
  ownerId,
  onOwner,
  sort,
  onSort,
  formatDate,
  onPick,
}: {
  sequences: readonly Sequence[];
  load?: SequencesLoad;
  q: string;
  onSearch: (q: string) => void;
  ownerId: string;
  onOwner: (ownerId: string) => void;
  sort: PickerSort;
  onSort: (key: PickerSortKey) => void;
  formatDate: (iso: string | null | undefined) => string;
  onPick: (sequence: Sequence) => void;
}) {
  const owners = ownerChoices(sequences);
  const ownerName = owners.find((owner) => owner.id === ownerId)?.name ?? 'Any owner';
  const rows = pickerRows(sequences, { q, ownerId, sort });

  return (
    <>
      <div className="crm-seqpick__bar">
        <label className="crm-seqpick__search">
          <input
            type="search"
            placeholder="Search sequences"
            aria-label="Search sequences"
            value={q}
            onChange={(e) => onSearch(e.target.value)}
          />
          <CrmIcon name="search" className="iconSize-16" />
        </label>
        <span className="crm-seqpick__filter">
          <span className="crm-seqpick__filter-l">Owner:</span>
          <DropMenu
            trigger={
              <>
                {ownerName}
                <ChevronDown />
              </>
            }
            triggerClassName="crm-seqpick__filter-b"
            ariaLabel={`Owner: ${ownerName}`}
            align="start"
            searchable
            items={owners.map((owner) => ({
              key: owner.id || 'any',
              label: owner.name,
              active: owner.id === ownerId,
              onSelect: () => onOwner(owner.id),
            }))}
          />
        </span>
      </div>
      {load === 'loading' ? (
        <p className="crm-text-body-secondary crm-mb-0">Loading…</p>
      ) : load === 'failed' ? (
        <Alert tone="danger">{LOAD_FAILED_TEXT}</Alert>
      ) : rows.length > 0 ? (
        <div className="crm-seqpick__tablewrap">
          <table className="crm-seqpick__table">
            <thead>
              <tr>
                {COLUMNS.map((column) => {
                  const dir = sort.key === column.key ? sort.dir : 0;
                  return (
                    <th
                      key={column.key}
                      scope="col"
                      aria-sort={dir === 1 ? 'ascending' : dir === -1 ? 'descending' : 'none'}
                    >
                      <button
                        type="button"
                        className="crm-seqpick__sort"
                        onClick={() => onSort(column.key)}
                      >
                        {column.label}
                        <SortGlyph dir={dir === 1 ? 'asc' : dir === -1 ? 'desc' : null} />
                      </button>
                    </th>
                  );
                })}
              </tr>
            </thead>
            <tbody>
              {rows.map((row) => (
                <tr key={row.id}>
                  <td>
                    <button type="button" className="crm-seqpick__name" onClick={() => onPick(row)}>
                      {row.name}
                    </button>
                    <span className="crm-seqpick__sub">{stepCountLabel(row.steps)}</span>
                  </td>
                  <td>{row.ownerName ?? '--'}</td>
                  <td>{formatDate(row.lastUsedAt ?? null)}</td>
                  <td>{formatDate(row.updatedAt)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="crm-seqpick__empty">
          <div>
            <h3>{emptyPickerText(sequences.length)}</h3>
            <p>Expecting to see new sequences? Try changing your filters, or refresh the page.</p>
            <a className="link" href="/sequences" target="_blank" rel="noopener">
              Go to sequences
            </a>
          </div>
          <svg viewBox="0 0 160 120" aria-hidden="true">
            <path d="M20 90 80 60l60 30-60 30z" fill="#eef2f7" />
            <circle cx="80" cy="45" r="22" fill="none" stroke="#c9d3df" strokeWidth="5" />
            <path d="m96 61 18 18" stroke="#c9d3df" strokeWidth="7" strokeLinecap="round" />
          </svg>
        </div>
      )}
    </>
  );
}
