'use client';

/**
 * The choices beside Send (HUB-366), for a reply and for New email: open and click tracking,
 * "Log to CRM" with the records to show the email on, and the time picker of "Schedule send".
 */
import { useCallback, useRef, useState } from 'react';
import { defaultSendLater, localInput } from '../design';
import type { SendEmailRecordLink } from '../types';
import { IxPopover, Tri } from './ix';

export interface SendChoices {
  trackOpens: boolean;
  trackClicks: boolean;
  logToCrm: boolean;
  /** Records to show the email on besides the ones found by address, as "type:id". */
  records: string[];
}

export const DEFAULT_SEND_CHOICES: SendChoices = {
  trackOpens: true,
  trackClicks: true,
  logToCrm: true,
  records: [],
};

export interface RecordChoice {
  type: string;
  id: string;
  label: string;
}

const keyOf = (r: { type: string; id: string }) => `${r.type}:${r.id}`;

/** The picked records as the API takes them (ten at most, none when not logging). */
export function recordLinks(choices: SendChoices): SendEmailRecordLink[] {
  if (!choices.logToCrm) return [];
  return choices.records.slice(0, 10).map((key) => {
    const at = key.indexOf(':');
    return { type: key.slice(0, at), id: key.slice(at + 1) };
  });
}

/** The request fields of these choices. */
export function sendFields(choices: SendChoices) {
  const links = recordLinks(choices);
  return {
    track: choices.trackOpens,
    trackClicks: choices.trackClicks,
    logToCrm: choices.logToCrm,
    ...(links.length ? { links } : {}),
  };
}

/** What Send will do, in a few words, so the choices need not be open to be known. */
export function sendSummary(choices: SendChoices): string {
  const { trackOpens, trackClicks, logToCrm } = choices;
  const tracking =
    trackOpens && trackClicks
      ? 'Tracking on'
      : trackOpens
        ? 'Tracking opens'
        : trackClicks
          ? 'Tracking clicks'
          : 'Tracking off';
  return `${tracking} · ${logToCrm ? 'Logged to CRM' : 'Not logged to CRM'}`;
}

function Check({
  label,
  checked,
  onChange,
}: {
  label: string;
  checked: boolean;
  onChange: (on: boolean) => void;
}) {
  return (
    <label className="ix-mi">
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
      {label}
    </label>
  );
}

/**
 * Tracking and "Log to CRM", behind one button beside Send: three checkboxes and a records link
 * in a row wrapped onto several lines and crowded out the email above.
 */
export function SendOptions({
  value,
  onChange,
  records = [],
}: {
  value: SendChoices;
  onChange: (next: SendChoices) => void;
  /** The records "Log to CRM" can name; none: no picker. */
  records?: RecordChoice[];
}) {
  const [open, setOpen] = useState(false);
  const button = useRef<HTMLButtonElement>(null);
  const close = useCallback(() => setOpen(false), []);
  const summary = sendSummary(value);

  return (
    <>
      <button
        ref={button}
        type="button"
        className="ix-sendopt"
        aria-label={`Tracking and CRM logging: ${summary}`}
        aria-haspopup="dialog"
        aria-expanded={open}
        title={summary}
        onClick={() => setOpen((v) => !v)}
      >
        <span className="ix-sendopt__t">{summary}</span>
        <Tri />
      </button>
      {open ? (
        <IxPopover
          anchor={button.current}
          onClose={close}
          role="dialog"
          label="Tracking and CRM logging"
        >
          <Check
            label="Track opens"
            checked={value.trackOpens}
            onChange={(trackOpens) => onChange({ ...value, trackOpens })}
          />
          <Check
            label="Track clicks"
            checked={value.trackClicks}
            onChange={(trackClicks) => onChange({ ...value, trackClicks })}
          />
          <Check
            label="Log to CRM"
            checked={value.logToCrm}
            onChange={(logToCrm) => onChange({ ...value, logToCrm })}
          />
          {records.length && value.logToCrm ? (
            <>
              <p className="ix-pop__h">Also show this email on</p>
              {records.map((record) => {
                const key = keyOf(record);
                return (
                  <Check
                    key={key}
                    label={record.label}
                    checked={value.records.includes(key)}
                    onChange={(on) =>
                      onChange({
                        ...value,
                        records: on
                          ? [...value.records, key]
                          : value.records.filter((k) => k !== key),
                      })
                    }
                  />
                );
              })}
            </>
          ) : null}
        </IxPopover>
      ) : null}
    </>
  );
}

/** "Schedule send": when to send, from now on. */
export function SchedulePopover({
  anchor,
  onClose,
  onSchedule,
}: {
  anchor: HTMLElement | null;
  onClose: () => void;
  onSchedule: (sendAt: string) => void;
}) {
  const [when, setWhen] = useState(() => defaultSendLater());
  const [error, setError] = useState<string | null>(null);

  const schedule = () => {
    const at = new Date(when);
    if (Number.isNaN(at.getTime()) || at.getTime() <= Date.now()) {
      setError('Choose a time in the future');
      return;
    }
    onClose();
    onSchedule(at.toISOString());
  };

  return (
    <IxPopover anchor={anchor} onClose={onClose} role="dialog" label="Schedule send">
      {/* not a <form>: the composer around it may be one */}
      <div
        className="ix-linkf"
        style={{ padding: '6px 14px', width: 280 }}
        onKeyDown={(e) => {
          if (e.key !== 'Enter') return;
          e.preventDefault();
          schedule();
        }}
      >
        <label className="ix-f">
          <span>Send on</span>
          <input
            className="input"
            type="datetime-local"
            min={localInput(new Date())}
            value={when}
            onChange={(e) => {
              setWhen(e.target.value);
              setError(null);
            }}
          />
          {error ? <small className="crm-text-danger">{error}</small> : null}
        </label>
        <div className="ix-linkf__a">
          <button type="button" className="btn-crm btn-crm--primary btn-crm--sm" onClick={schedule}>
            Schedule
          </button>
          <button type="button" className="btn-crm btn-crm--outline btn-crm--sm" onClick={onClose}>
            Cancel
          </button>
        </div>
      </div>
    </IxPopover>
  );
}
