'use client';

/**
 * "Import an opt-out list" (DI-2e): the 6 Nov design's `opt-out-import.php`, drawn with its markup
 * and classes so the design's `opt-out-import.css` applies as written, and the behaviour of its
 * `assets/js/opt-out-import.js`. Full window (`$layout = 'import'`), as `ImportStartView`.
 *
 * DI-2f: "Begin import" sends the list to the API (`beginOptOutImport`) and opens the run's Import
 * details, where the design saves a sample import row in localStorage and opens
 * import-details.php (`opt-out-import.js:468-501`).
 */
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type ChangeEvent,
  type DragEvent,
  type RefObject,
} from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import {
  IMPORT_ACCEPT,
  discardDraftImport,
  getImportRun,
  startOptOutImport,
  uploadImportFile,
} from '@/features/imports/api.client';
import { importableFile } from '@/features/imports/spreadsheet';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { soonClick } from '../importStart';
import {
  OPT_OUT_COLUMN_PLACEHOLDER,
  OPT_OUT_STEPS,
  beginOptOutImport,
  confirmMatches,
  enterAction,
  formatFileSize,
  menuPlacement,
  optOutEmailsInColumn,
  readOptOutFile,
  stepNodeState,
  suggestOptOutEmailColumn,
  type OptOutAction,
  type OptOutList,
  type OptOutStep,
} from '../optOutImport';

type Ready = Record<OptOutAction, boolean>;

/** The stepper (`opt-out-import.php:45-62`); a completed step goes back to it (js:182-190). */
export function OptOutStepper({ step, onStep }: { step: number; onStep: (n: OptOutStep) => void }) {
  return (
    <nav className="opt-stepper" id="optStepper" aria-label="Import progress steps">
      {OPT_OUT_STEPS.map(({ n, label }) => {
        const state = stepNodeState(n, step);
        return (
          <FragmentLine key={n} n={n} step={step}>
            <div
              className={cn(
                'opt-step-node',
                state === 'active' && 'is-active',
                state === 'complete' && 'is-complete is-clickable',
              )}
              data-step-node={n}
              onClick={() => {
                if (n < step) onStep(n);
              }}
            >
              <span className="opt-step-node__indicator">{state === 'complete' ? '✓' : n}</span>
              <span className="opt-step-node__label">{label}</span>
            </div>
          </FragmentLine>
        );
      })}
    </nav>
  );
}

/** A node, then the line after it (none after the last). */
function FragmentLine({
  n,
  step,
  children,
}: {
  n: number;
  step: number;
  children: React.ReactNode;
}) {
  return (
    <>
      {children}
      {n < OPT_OUT_STEPS.length ? (
        <div className={cn('opt-step-line', n < step && 'is-complete')} data-step-line={n} />
      ) : null}
    </>
  );
}

/** Step 1 (`opt-out-import.php:81-128`). */
export function OptOutUploadStep({
  active,
  file,
  dragover,
  onPick,
  onDragOver,
  onDragLeave,
  onDrop,
  onLearnMore,
  inputRef,
  onInput,
}: {
  active: boolean;
  file: { name: string; size: string } | null;
  dragover: boolean;
  onPick: () => void;
  onDragOver: (e: DragEvent) => void;
  onDragLeave: (e: DragEvent) => void;
  onDrop: (e: DragEvent) => void;
  onLearnMore: (e: { preventDefault: () => void }) => void;
  inputRef: RefObject<HTMLInputElement | null>;
  onInput: (e: ChangeEvent<HTMLInputElement>) => void;
}) {
  const pick = (e: { stopPropagation: () => void }) => {
    e.stopPropagation();
    onPick();
  };
  return (
    <section
      className={cn('opt-step-view', active && 'is-active')}
      id="optStep1"
      aria-label="Step 1: Upload file"
      hidden={!active}
    >
      <h1 className="opt-title">Upload an opt-out list file</h1>
      <p className="opt-desc">
        An opt-out list is a list of contacts who have unsubscribed from your emails or have chosen
        not to receive them. When you import an opt-out list, we&apos;ll make sure those contacts
        never receive an email from you. This will help you avoid spam complaints and high
        unsubscribe rates.{' '}
        <a
          href="#"
          className="opt-link"
          target="_blank"
          rel="noopener noreferrer"
          onClick={onLearnMore}
        >
          Learn more
        </a>
      </p>

      {/* The design's dropzone opens the file picker on any click (js:283-310). */}
      <div
        className={cn('opt-dropzone', dragover && 'is-dragover')}
        id="optDropzone"
        onClick={onPick}
        onDragEnter={onDragOver}
        onDragOver={onDragOver}
        onDragLeave={onDragLeave}
        onDrop={onDrop}
      >
        <div className="opt-dropzone__empty" id="optDropzoneEmpty" hidden={!!file}>
          <div className="opt-dropzone__icon-wrap" aria-hidden="true">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242" />
              <path d="M12 12v9" />
              <path d="m8 16 4-4 4 4" />
            </svg>
          </div>
          <p className="opt-dropzone__prompt">
            Drag and drop a CSV, XLS, or XLSX file here to upload
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--outline opt-dropzone__btn"
            id="optChooseBtn"
            onClick={pick}
          >
            Choose a file
          </button>
        </div>

        <div className="opt-selected-file-state" id="optDropzoneSelected" hidden={!file}>
          <div className="opt-success-icon-wrap" aria-hidden="true">
            <CrmIcon name="check" className="iconSize-24" />
          </div>
          <div className="opt-file-name" id="optFileName">
            {file?.name}
          </div>
          <div className="opt-file-size" id="optFileSize">
            {file?.size}
          </div>
          <button type="button" className="opt-change-link" id="optChangeFileBtn" onClick={pick}>
            Change file
          </button>
        </div>

        <input
          ref={inputRef}
          type="file"
          id="optFileInput"
          accept={IMPORT_ACCEPT}
          hidden
          onChange={onInput}
          // Its own click (from `.click()`) mustn't reach the dropzone and open the picker again.
          onClick={(e) => e.stopPropagation()}
        />
      </div>

      <div className="opt-info-card">
        <h2>Creating an opt-out list file</h2>
        <p>
          Open a spreadsheet and add a column with the header &apos;Email&apos;. In that column,
          input the email addresses you&apos;d like to opt out of receiving your emails. Save the
          file in a CSV format.
        </p>
      </div>
    </section>
  );
}

/** Step 2 (`opt-out-import.php:133-162`; options and value: js:330-349). */
export function OptOutDetailsStep({
  active,
  headers,
  selected,
  open,
  above,
  maxHeight,
  onToggle,
  onSelect,
  wrapRef,
  triggerRef,
}: {
  active: boolean;
  headers: string[];
  selected: string;
  open: boolean;
  above: boolean;
  maxHeight: number | undefined;
  onToggle: () => void;
  onSelect: (col: string) => void;
  wrapRef: RefObject<HTMLDivElement | null>;
  triggerRef: RefObject<HTMLButtonElement | null>;
}) {
  return (
    <section
      className={cn('opt-step-view', active && 'is-active')}
      id="optStep2"
      aria-label="Step 2: Import details"
      hidden={!active}
    >
      <h1 className="opt-title">Import details</h1>

      <div className="opt-details-grid">
        <div className="opt-details-col-left">
          <label className="opt-label" htmlFor="optEmailColTrigger">
            Email field column header
          </label>
          <div
            className={cn('opt-dropdown-wrap', open && 'is-open')}
            id="optEmailColDropdown"
            ref={wrapRef}
          >
            <button
              ref={triggerRef}
              type="button"
              className={cn('opt-dropdown-trigger', selected && 'has-value')}
              id="optEmailColTrigger"
              aria-haspopup="listbox"
              aria-expanded={open}
              onClick={onToggle}
            >
              <span className="opt-select-value" id="optEmailColValue">
                {selected || OPT_OUT_COLUMN_PLACEHOLDER}
              </span>
              <span className="opt-select-caret" aria-hidden="true">
                <CrmIcon name="chevron-down" className="iconSize-14" />
              </span>
            </button>

            <div
              className={cn('opt-dropdown-menu', above && 'is-open-above')}
              id="optEmailColMenu"
              role="listbox"
              hidden={!open}
              style={open && maxHeight !== undefined ? { maxHeight: `${maxHeight}px` } : undefined}
            >
              <div id="optEmailColOptions">
                {headers.map((col, i) => {
                  const isSelected = selected === col;
                  return (
                    <button
                      // Two columns may share a header.
                      key={`${i}:${col}`}
                      type="button"
                      className={cn('opt-dropdown-option', isSelected && 'is-selected')}
                      data-col={col}
                      role="option"
                      aria-selected={isSelected}
                      onClick={() => onSelect(col)}
                    >
                      <span>{col}</span>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        <div className="opt-details-col-right">
          <p className="opt-helper-text">
            What&apos;s the column header of the column in your file that has the email data? The
            contents of this field will go into your blacklist.
          </p>
        </div>
      </div>
    </section>
  );
}

/** Step 3 (`opt-out-import.php:167-183`). */
export function OptOutConfirmStep({
  active,
  count,
  value,
  onChange,
  inputRef,
}: {
  active: boolean;
  count: number;
  value: string;
  onChange: (value: string) => void;
  inputRef: RefObject<HTMLInputElement | null>;
}) {
  return (
    <section
      className={cn('opt-step-view', active && 'is-active')}
      id="optStep3"
      aria-label="Step 3: Confirm your opt-out"
      hidden={!active}
    >
      <h1 className="opt-title">Confirm your opt-out</h1>
      <p className="opt-warning-text">
        All <strong id="optConfirmCount">{count}</strong> contacts in this list will no longer
        receive any emails from your organization. Please be extraordinarily sure.
      </p>

      <label className="opt-label" htmlFor="optConfirmInput">
        Confirm this action by entering the number of contacts to opt out.
      </label>
      <div className="opt-input-wrap">
        <input
          ref={inputRef}
          type="text"
          id="optConfirmInput"
          className="input opt-input"
          placeholder=""
          autoComplete="off"
          aria-describedby="optConfirmHintText"
          value={value}
          onChange={(e) => onChange(e.target.value)}
        />
      </div>
      <p className="opt-confirm-hint" id="optConfirmHintText">
        Type the number to import this list: <strong id="optExpectedNumber">{count}</strong>
      </p>
    </section>
  );
}

/** The fixed action bar (`opt-out-import.php:191-220`; which buttons show: js:162-169). */
export function OptOutFooter({
  step,
  ready,
  starting = false,
  onBack,
  onUpload,
  onNext,
  onBegin,
}: {
  step: number;
  ready: Ready;
  /** DI-2f: Begin import was clicked and the API hasn't answered (js:486-487). */
  starting?: boolean;
  onBack: () => void;
  onUpload: () => void;
  onNext: () => void;
  onBegin: () => void;
}) {
  return (
    <footer className="opt-footer" id="optFooter">
      <div className="opt-footer__left">
        <button
          type="button"
          className="btn-crm btn-crm--outline"
          id="optBackBtn"
          hidden={step === 1}
          onClick={onBack}
        >
          Back
        </button>
        <Link href="/data-integration" className="btn-crm btn-crm--outline" id="optCancelBtn">
          Cancel
        </Link>
      </div>

      <div className="opt-footer__right">
        <span className="opt-footer-tip" id="optFooterTip">
          Tip: press Ret to continue
        </span>

        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="optUploadBtn"
          hidden={step !== 1}
          disabled={!ready.upload}
          onClick={onUpload}
        >
          Upload
        </button>

        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="optNextBtn"
          hidden={step !== 2}
          disabled={!ready.next}
          onClick={onNext}
        >
          <span>Next, confirm your choice</span>
          <CrmIcon name="chevron-right" className="iconSize-14" />
        </button>

        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="optBeginBtn"
          hidden={step !== 3}
          disabled={!ready.begin || starting}
          onClick={onBegin}
        >
          {starting ? 'Beginning import...' : 'Begin import'}
        </button>
      </div>
    </footer>
  );
}

export function OptOutImportView() {
  const toast = useToast();
  const router = useRouter();
  const soon = (label: string) => soonClick((m) => toast(m), label);

  const [step, setStep] = useState<OptOutStep>(1);
  const [file, setFile] = useState<{ name: string; size: string } | null>(null);
  const [list, setList] = useState<OptOutList | null>(null);
  // DI-2f: the file as read (an Excel file's CSV), sent on Begin import.
  const [source, setSource] = useState<File | null>(null);
  const [starting, setStarting] = useState(false);
  const [selected, setSelected] = useState('');
  const [open, setOpen] = useState(false);
  const [placement, setPlacement] = useState<{ above: boolean; maxHeight: number } | null>(null);
  const [confirm, setConfirm] = useState('');
  const [dragover, setDragover] = useState(false);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const wrapRef = useRef<HTMLDivElement>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const confirmRef = useRef<HTMLInputElement>(null);
  // The latest file chosen: a slower read of an earlier one is dropped.
  const readSeq = useRef(0);

  const emails = list && selected ? optOutEmailsInColumn(list, selected) : [];
  const count = emails.length;
  const ready: Ready = {
    upload: list !== null,
    next: selected !== '' && count > 0,
    begin: list !== null && source !== null && count > 0 && confirmMatches(confirm, count),
  };

  // Reads the file in the browser (`readOptOutFile`). An unreadable file shows why and leaves the
  // dropzone empty.
  const handleFile = async (f: File) => {
    const seq = ++readSeq.current;
    setFile({ name: f.name, size: formatFileSize(f.size) });
    setList(null);
    setSource(null);
    try {
      let read: File | null = null;
      const next = await readOptOutFile(f, async (x) => (read = await importableFile(x)));
      if (seq !== readSeq.current) return;
      setList(next);
      setSource(read);
      setSelected((s) => (next.headers.includes(s) ? s : suggestOptOutEmailColumn(next.headers)));
    } catch (err) {
      if (seq !== readSeq.current) return;
      toast(err instanceof Error && !('status' in err) ? err.message : errorText(err), 'danger');
      setFile(null);
    }
  };

  const goTo = useCallback((n: OptOutStep) => {
    setStep(n);
    setOpen(false);
    if (n === 3) setConfirm('');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []);

  // The design focuses the count box 80ms after step 3 opens (js:451).
  useEffect(() => {
    if (step !== 3) return;
    const t = setTimeout(() => confirmRef.current?.focus(), 80);
    return () => clearTimeout(t);
  }, [step]);

  const place = useCallback(() => {
    const el = triggerRef.current;
    if (el) setPlacement(menuPlacement(el.getBoundingClientRect(), window.innerHeight));
  }, []);

  // Open menu: a click outside closes it; a resize places it again (js:417-427).
  useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('click', onDoc);
    window.addEventListener('resize', place, { passive: true });
    return () => {
      document.removeEventListener('click', onDoc);
      window.removeEventListener('resize', place);
    };
  }, [open, place]);

  const upload = () => {
    if (ready.upload) goTo(2);
  };
  const next = () => {
    if (!selected) {
      toast('Select the email column', 'danger');
      return;
    }
    if (!list || emails.length === 0) {
      toast(
        'That column has no valid email addresses. Choose the column that contains emails.',
        'danger',
      );
      return;
    }
    if (emails.length < list.rowCount) {
      toast(
        `Using ${emails.length} valid email${emails.length === 1 ? '' : 's'} of ${list.rowCount} rows (non-email values were skipped).`,
        'info',
      );
    }
    if (ready.next) goTo(3);
  };
  // DI-2f: the button says "Beginning import..." until the API answers (js:486-487); a refusal
  // shows the API's message and the button can be used again.
  const begin = async () => {
    if (!ready.begin || starting || !source) return;
    setStarting(true);
    try {
      const href = await beginOptOutImport(
        {
          upload: (f) => uploadImportFile(f, 'contact', 'opt_out'),
          start: startOptOutImport,
          discard: discardDraftImport,
          status: async (id) => (await getImportRun(id)).status,
        },
        { file: source, emailColumn: selected, count },
      );
      router.push(href);
    } catch (err) {
      toast(errorText(err), 'danger');
      setStarting(false);
    }
  };
  const actions: Record<OptOutAction, () => void> = {
    upload,
    next,
    begin: () => void begin(),
  };

  // Enter continues (js:518-534).
  const keyRef = useRef({ step, ready, actions });
  keyRef.current = { step, ready, actions };
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Enter' || e.shiftKey || e.ctrlKey) return;
      const cur = keyRef.current;
      const action = enterAction(cur.step, cur.ready, document.activeElement?.tagName);
      if (!action) return;
      e.preventDefault();
      cur.actions[action]();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  const stopDrag = (e: DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    // As `ImportStartView`: Lexend comes from the layout's `next/font` class, so the root inherits it.
    <div className="layout-import" style={{ fontFamily: 'inherit' }}>
      <div className="opt-root">
        <header className="opt-header" id="optHeader">
          <div className="opt-header__left">
            <Link
              href="/data-integration/import"
              className="opt-header__back"
              aria-label="Back to import options"
            >
              <CrmIcon name="chevron-left" className="iconSize-14" />
              <span>Opt out list</span>
            </Link>
          </div>

          <OptOutStepper step={step} onStep={goTo} />

          <div className="opt-header__right">
            <div className="opt-step-count" id="optStepCount">
              Step {step} of 3
            </div>
            <Link
              href="/data-integration"
              className="opt-header__exit"
              title="Exit import"
              aria-label="Exit import"
            >
              <CrmIcon name="x" className="iconSize-16" />
            </Link>
          </div>
        </header>

        <main className="opt-main" id="optMain">
          <div className="opt-container">
            <OptOutUploadStep
              active={step === 1}
              file={file}
              dragover={dragover}
              onPick={() => fileInputRef.current?.click()}
              onDragOver={(e) => {
                stopDrag(e);
                setDragover(true);
              }}
              onDragLeave={(e) => {
                stopDrag(e);
                setDragover(false);
              }}
              onDrop={(e) => {
                stopDrag(e);
                setDragover(false);
                const f = e.dataTransfer?.files?.[0];
                if (f) void handleFile(f);
              }}
              onLearnMore={soon('Learn more')}
              inputRef={fileInputRef}
              onInput={(e) => {
                const f = e.target.files?.[0];
                // Cleared so the same file can be chosen again after an error.
                e.target.value = '';
                if (f) void handleFile(f);
              }}
            />

            <OptOutDetailsStep
              active={step === 2}
              headers={list?.headers ?? []}
              selected={selected}
              open={open}
              above={placement?.above ?? false}
              maxHeight={placement?.maxHeight}
              onToggle={() => {
                if (!open) place();
                setOpen(!open);
              }}
              onSelect={(col) => {
                setSelected(col);
                setOpen(false);
              }}
              wrapRef={wrapRef}
              triggerRef={triggerRef}
            />

            <OptOutConfirmStep
              active={step === 3}
              count={count}
              value={confirm}
              onChange={setConfirm}
              inputRef={confirmRef}
            />
          </div>
        </main>

        <OptOutFooter
          step={step}
          ready={ready}
          starting={starting}
          onBack={() => {
            if (step > 1) goTo((step - 1) as OptOutStep);
          }}
          onUpload={upload}
          onNext={next}
          onBegin={() => void begin()}
        />
      </div>
    </div>
  );
}
