'use client';

/**
 * New email: the design's floating "Compose a message" window (`.ix-compose`), which can be
 * minimised or made large while the Inbox stays usable. Mounted only while open, so each one
 * starts empty with its own idempotency key. HUB-366.
 */
import { useCallback, useEffect, useRef, useState } from 'react';
import { htmlIsEmpty } from '@/components/crm/ComposeRichText';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { attachmentProblem, deleteAttachment, uploadAttachment } from '../api.client';
import { hasAddress, keepInside } from '../compose';
import { newIdempotencyKey } from '../format';
import type { EmailUpload } from '../types';
import { InboxEditor, InboxTools, type InboxEditorHandle, type InsertItem } from './InboxEditor';
import { ChipBox, type RecipientChoice } from './RecipientRows';
import {
  DEFAULT_SEND_CHOICES,
  SchedulePopover,
  SendOptions,
  type SendChoices,
} from './SendOptions';
import { IxIcon, IxPopover, Tri } from './ix';

export interface NewEmail {
  to: string[];
  cc: string[];
  bcc: string[];
  subject: string;
  bodyHtml: string;
  idempotencyKey: string;
  choices: SendChoices;
  /** "Send later". */
  sendAt?: string;
  /** "From" a team inbox; absent: my own Gmail. */
  inboxId?: string;
  /** The email template the text came from, so the send counts as a use of it. */
  template?: { templateId: string; contactId: string; dealId?: string };
  attachmentIds?: string[];
}

/** A template filled in for one recipient, ready to put into a new email. */
export interface ComposeTemplate {
  templateId: string;
  contactId: string;
  dealId?: string;
  /** The recipient whose details it was filled with. */
  address: string;
  subject: string;
  bodyHtml: string;
}

/** What the "Insert" menu knows about the email being written. */
export interface ComposeContext {
  to: string[];
  fillTemplate: (template: ComposeTemplate) => void;
}

/** An address a new email can be sent from; `inboxId` '' is my own Gmail. */
export interface FromChoice {
  inboxId: string;
  label: string;
}

export function ComposeWindow({
  fromChoices,
  defaultFrom,
  suggest,
  insert,
  onInvalid,
  onProblem,
  onSend,
  onClose,
}: {
  fromChoices: FromChoice[];
  /** The inbox that is open: its address is chosen first, when it can send. */
  defaultFrom: string;
  suggest: (query: string) => Promise<RecipientChoice[]>;
  /** The "Insert" menu, for the editor it puts things into. */
  insert: (editor: () => InboxEditorHandle | null, email: ComposeContext) => InsertItem[];
  onInvalid: (text: string) => void;
  /** Something that went wrong with a file, to show as a message. */
  onProblem: (message: string) => void;
  /** False: not sent, so the window stays as it is. */
  onSend: (email: NewEmail) => Promise<boolean>;
  onClose: () => void;
}) {
  const [size, setSize] = useState<'normal' | 'min' | 'big'>('normal');
  const [from, setFrom] = useState(() =>
    fromChoices.some((c) => c.inboxId === defaultFrom)
      ? defaultFrom
      : (fromChoices[0]?.inboxId ?? ''),
  );
  const [to, setTo] = useState<string[]>([]);
  const [cc, setCc] = useState<string[]>([]);
  const [bcc, setBcc] = useState<string[]>([]);
  const [showCc, setShowCc] = useState(false);
  const [subject, setSubject] = useState('');
  const [html, setHtml] = useState('');
  const [sending, setSending] = useState(false);
  const [choices, setChoices] = useState<SendChoices>(DEFAULT_SEND_CHOICES);
  const [menu, setMenu] = useState<'send' | 'schedule' | null>(null);
  const menuButton = useRef<HTMLButtonElement>(null);
  const closeMenu = useCallback(() => setMenu(null), []);
  const [key] = useState(newIdempotencyKey);
  const editor = useRef<InboxEditorHandle>(null);
  const [template, setTemplate] = useState<ComposeTemplate | null>(null);
  const [uploads, setUploads] = useState<EmailUpload[]>([]);
  const [uploading, setUploading] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);
  /* an upload that finishes after the window closed is thrown away */
  const open = useRef(true);
  useEffect(() => {
    open.current = true;
    return () => {
      open.current = false;
    };
  }, []);

  const ready = to.length > 0 && !htmlIsEmpty(html) && !sending && !uploading;

  const fillTemplate = (picked: ComposeTemplate) => {
    editor.current?.insertHtml(picked.bodyHtml);
    setSubject((typed) => (typed.trim() ? typed : picked.subject));
    setTemplate(picked);
  };

  const addFiles = async (files: File[]) => {
    if (!files.length) return;
    setUploading(true);
    let bytes = uploads.reduce((n, u) => n + u.sizeBytes, 0);
    for (const file of files) {
      const problem = attachmentProblem(file, bytes);
      if (problem) {
        onProblem(`${file.name}: ${problem}`);
        continue;
      }
      try {
        const up = await uploadAttachment(file);
        if (!open.current) {
          void deleteAttachment(up.attachmentId).catch(() => {});
          continue;
        }
        bytes += up.sizeBytes;
        setUploads((list) => [...list, up]);
      } catch (err) {
        onProblem(`${file.name}: ${errorText(err)}`);
      }
    }
    setUploading(false);
  };

  const removeUpload = (id: string) => {
    setUploads((list) => list.filter((u) => u.attachmentId !== id));
    void deleteAttachment(id).catch(() => {});
  };

  const send = async (sendAt?: string) => {
    if (!ready) return;
    let used = template;
    if (used && !hasAddress(to, used.address)) {
      // the text still carries that person's details
      const goOn = window.confirm(
        `The template was filled in for ${used.address}, who is not in To. Send it anyway?`,
      );
      if (!goOn) return;
      used = null;
    }
    setSending(true);
    const sent = await onSend({
      to,
      cc,
      bcc,
      subject,
      bodyHtml: html,
      idempotencyKey: key,
      choices,
      sendAt,
      inboxId: from || undefined,
      ...(used
        ? {
            template: {
              templateId: used.templateId,
              contactId: used.contactId,
              dealId: used.dealId,
            },
          }
        : {}),
      ...(uploads.length ? { attachmentIds: uploads.map((u) => u.attachmentId) } : {}),
    });
    if (sent) onClose();
    else setSending(false);
  };

  const hasContent =
    !!(to.length || cc.length || bcc.length || subject.trim() || uploads.length) ||
    !htmlIsEmpty(html);
  const dismiss = () => {
    if (hasContent && !window.confirm('Discard this email?')) return;
    for (const u of uploads) void deleteAttachment(u.attachmentId).catch(() => {});
    onClose();
  };
  const boxRef = useRef<HTMLDivElement>(null);
  /* the window can be dragged by its title bar, off the reply box it opens over */
  const [moved, setMoved] = useState({ x: 0, y: 0 });
  const drag = useRef<{ x: number; y: number; from: { x: number; y: number } } | null>(null);
  const onDragStart = (e: React.PointerEvent<HTMLElement>) => {
    if (size === 'big' || (e.target as HTMLElement).closest('button')) return;
    drag.current = { x: e.clientX, y: e.clientY, from: moved };
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onDragMove = (e: React.PointerEvent<HTMLElement>) => {
    const box = boxRef.current;
    const area = box?.offsetParent;
    if (!drag.current || !box || !area) return;
    const wanted = {
      x: drag.current.from.x + e.clientX - drag.current.x,
      y: drag.current.from.y + e.clientY - drag.current.y,
    };
    // never outside the inbox: offsetLeft and offsetTop are where it opened
    setMoved(
      keepInside(wanted, {
        left: box.offsetLeft,
        top: box.offsetTop,
        right: area.clientWidth - box.offsetLeft - box.offsetWidth,
        bottom: area.clientHeight - box.offsetTop - box.offsetHeight,
      }),
    );
  };
  const onDragEnd = () => {
    drag.current = null;
  };
  const onFiles = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.currentTarget.files ?? []);
    e.currentTarget.value = '';
    void addFiles(files);
  };

  /* the window takes the keyboard, so Escape reaches it at once */
  useEffect(() => boxRef.current?.focus(), []);

  return (
    <div
      ref={boxRef}
      tabIndex={-1}
      className={cn('ix-compose', size === 'min' && 'is-min', size === 'big' && 'is-big')}
      role="dialog"
      aria-label="Compose a message"
      style={
        size !== 'big' && (moved.x || moved.y)
          ? { transform: `translate(${moved.x}px, ${moved.y}px)` }
          : undefined
      }
      onKeyDown={(e) => {
        // a menu or list inside closes first, and says so
        if (e.key !== 'Escape' || e.defaultPrevented || menu) return;
        // an open menu (Insert, emoji, link) closes itself after this: only that closes
        if (document.querySelector('.ix-pop')) return;
        e.preventDefault();
        e.stopPropagation();
        dismiss();
      }}
    >
      <header
        className="ix-cx__h"
        title={size === 'big' ? undefined : 'Drag to move'}
        onPointerDown={onDragStart}
        onPointerMove={onDragMove}
        onPointerUp={onDragEnd}
        onPointerCancel={onDragEnd}
      >
        <h2>Compose a message</h2>
        <span>
          <button
            type="button"
            className="ix-icon"
            title={size === 'min' ? 'Restore' : 'Minimize'}
            aria-label={size === 'min' ? 'Restore' : 'Minimize'}
            onClick={() => setSize((s) => (s === 'min' ? 'normal' : 'min'))}
          >
            <IxIcon name="minus" className="ix-i--sm" />
          </button>
          <button
            type="button"
            className="ix-icon"
            title={size === 'big' ? 'Exit full screen' : 'Full screen'}
            aria-label={size === 'big' ? 'Exit full screen' : 'Full screen'}
            onClick={() => setSize((s) => (s === 'big' ? 'normal' : 'big'))}
          >
            <IxIcon name={size === 'big' ? 'shrink' : 'expand'} className="ix-i--sm" />
          </button>
          <button
            type="button"
            className="ix-icon"
            title="Close"
            aria-label="Close"
            onClick={dismiss}
          >
            <IxIcon name="x" className="ix-i--sm" />
          </button>
        </span>
      </header>

      {/* kept while minimised, so nothing typed is lost */}
      <div className="ix-cx__b" hidden={size === 'min'}>
        <div className="ix-cx__row">
          <span>To</span>
          <ChipBox
            field="to"
            values={to}
            disabled={sending}
            onChange={setTo}
            onInvalid={onInvalid}
            suggest={suggest}
          />
          <button
            type="button"
            className="ix-comp__cc-btn"
            aria-expanded={showCc}
            onClick={() => setShowCc((v) => !v)}
          >
            Cc / Bcc
          </button>
        </div>
        {showCc ? (
          <>
            <div className="ix-cx__row">
              <span>Cc</span>
              <ChipBox
                field="cc"
                values={cc}
                disabled={sending}
                onChange={setCc}
                onInvalid={onInvalid}
                suggest={suggest}
              />
            </div>
            <div className="ix-cx__row">
              <span>Bcc</span>
              <ChipBox
                field="bcc"
                values={bcc}
                disabled={sending}
                onChange={setBcc}
                onInvalid={onInvalid}
                suggest={suggest}
              />
            </div>
          </>
        ) : null}
        <div className="ix-cx__row">
          <span>From</span>
          <span className="ix-select ix-select--plain">
            <select
              aria-label="From"
              value={from}
              disabled={sending}
              onChange={(e) => setFrom(e.target.value)}
            >
              {fromChoices.map((c) => (
                <option key={c.inboxId} value={c.inboxId}>
                  {c.label}
                </option>
              ))}
            </select>
            <Tri />
          </span>
        </div>
        <div className="ix-cx__row">
          <span>Subject</span>
          <input
            type="text"
            aria-label="Subject"
            maxLength={998}
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
          />
        </div>
        <InboxEditor
          ref={editor}
          resetKey={key}
          value=""
          onChange={(value) => {
            setHtml(value);
            if (htmlIsEmpty(value)) setTemplate(null);
          }}
          label="Message"
          placeholder="Write a message"
          className="ix-ed--cx"
          // A new email has no CRM record yet: contact fields need a fallback in the snippet.
          snippetTarget={{}}
        />
        <input ref={fileRef} type="file" multiple hidden aria-label="Files" onChange={onFiles} />
        {uploads.length || uploading ? (
          <ul className="ix-atts ix-atts--draft">
            {uploads.map((u) => (
              <li key={u.attachmentId}>
                <IxIcon name="clip" className="ix-i--xs" />
                {u.filename}
                <button
                  type="button"
                  aria-label={`Remove ${u.filename}`}
                  disabled={sending}
                  onClick={() => removeUpload(u.attachmentId)}
                >
                  <IxIcon name="x" className="ix-i--xs" />
                </button>
              </li>
            ))}
            {uploading ? <li>Uploading…</li> : null}
          </ul>
        ) : null}
        <div className="ix-cx__opts">
          <SendOptions value={choices} onChange={setChoices} />
        </div>
        <div className="ix-cx__f">
          <InboxTools
            editor={editor}
            disabled={sending}
            onAttach={() => fileRef.current?.click()}
            insert={insert(() => editor.current, { to, fillTemplate })}
          />
          <span className="ix-split ix-tipw">
            <button
              type="button"
              className="ix-split__main"
              disabled={!ready}
              onClick={() => void send()}
            >
              {sending ? 'Sending…' : 'Send'}
            </button>
            <button
              ref={menuButton}
              type="button"
              className="ix-split__chv"
              aria-label="More send options"
              aria-haspopup="menu"
              aria-expanded={menu !== null}
              disabled={!ready}
              onClick={() => setMenu((m) => (m ? null : 'send'))}
            >
              <Tri />
            </button>
            {!ready && !sending ? (
              <span className="ix-tipbox ix-tipbox--up ix-tipbox--r" role="tooltip">
                Add a recipient and a message to send
              </span>
            ) : null}
          </span>
        </div>
      </div>
      {menu === 'send' ? (
        <IxPopover
          anchor={menuButton.current}
          onClose={closeMenu}
          className="ix-pop--sm"
          label="More send options"
          align="right"
        >
          <button
            type="button"
            role="menuitem"
            className="ix-mi"
            onClick={() => setMenu('schedule')}
          >
            Schedule send
          </button>
        </IxPopover>
      ) : null}
      {menu === 'schedule' ? (
        <SchedulePopover
          anchor={menuButton.current}
          onClose={closeMenu}
          onSchedule={(sendAt) => void send(sendAt)}
        />
      ) : null}
    </div>
  );
}
