'use client';

/**
 * The conversation's timeline, as the design draws it (inbox-hs.js renderMessages): a separator
 * per day, one card per email (quoted text behind "···", long ones behind "See more", a menu to
 * reply or forward), internal comments between them, and where the conversation began. HUB-366.
 */
import { Fragment, memo, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { cn } from '@/lib/utils/cn';
import { attachmentUrl } from '../api.client';
import { commentParts, timelineItems } from '../conversation';
import { CHANNELS, dayKey, dayLabel, isLongMessage } from '../design';
import { displayName, htmlToText, lazyImages } from '../format';
import type { InboxComment, InboxMessage } from '../types';
import { IxIcon, IxPopover, ixInitials } from './ix';

const clock = (iso: string) =>
  new Date(iso).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });

/** What happened to an email sent from the CRM: sending, failed, bounced, opened, clicked. */
export function sendNotes(m: InboxMessage): string[] {
  const notes: string[] = [];
  if (m.sendStatus === 'queued' && m.scheduledAt && new Date(m.scheduledAt) > new Date()) {
    notes.push(`Scheduled for ${new Date(m.scheduledAt).toLocaleString()}`);
  } else if (m.sendStatus === 'queued' || m.sendStatus === 'sending') notes.push('Sending…');
  if (m.sendStatus === 'failed') notes.push('Failed to send');
  if (m.sendStatus === 'uncertain') notes.push('May not have been sent');
  if (m.bouncedAt) notes.push('Bounced');
  if (m.tracking && m.tracking.openCount > 0) {
    notes.push(`opened ${m.tracking.openCount} time${m.tracking.openCount === 1 ? '' : 's'}`);
  }
  if (m.tracking && m.tracking.clickCount > 0) {
    notes.push(`${m.tracking.clickCount} click${m.tracking.clickCount === 1 ? '' : 's'}`);
  }
  return notes;
}

/** The email's own text and what it quotes. The HTML is already cleaned by the API. */
function splitQuoted(html: string): { body: string; quoted: string | null } {
  if (typeof DOMParser === 'undefined') return { body: html, quoted: null };
  const doc = new DOMParser().parseFromString(html, 'text/html');
  const quote = doc.body.querySelector('.gmail_quote, blockquote');
  if (!quote) return { body: html, quoted: null };
  const quoted = quote.outerHTML;
  quote.remove();
  // An email that is nothing but a quote is shown as it is.
  if (!doc.body.textContent?.trim() && !doc.body.querySelector('img')) {
    return { body: html, quoted: null };
  }
  return { body: doc.body.innerHTML, quoted };
}

function MessageCard({
  m,
  canReply,
  onReply,
  onForward,
  onCancelScheduled,
}: {
  m: InboxMessage;
  canReply: boolean;
  onReply: (m: InboxMessage) => void;
  onForward: (m: InboxMessage) => void;
  onCancelScheduled: (m: InboxMessage) => void;
}) {
  const scheduled =
    m.sendStatus === 'queued' && !!m.scheduledAt && new Date(m.scheduledAt) > new Date();
  const [expanded, setExpanded] = useState(false);
  const [quoteShown, setQuoteShown] = useState(false);
  const [menu, setMenu] = useState(false);
  const menuRef = useRef<HTMLButtonElement>(null);
  const closeMenu = useCallback(() => setMenu(false), []);

  const html = useMemo(
    () => (m.bodyHtmlSafe ? splitQuoted(lazyImages(m.bodyHtmlSafe)) : null),
    [m.bodyHtmlSafe],
  );
  const long = useMemo(
    () => isLongMessage(html ? htmlToText(html.body) : (m.bodyText ?? '')),
    [html, m.bodyText],
  );
  const files = m.attachments.filter((a) => !a.isInline);
  const from = displayName(m.from);
  const at = m.sentAt;
  const notes = sendNotes(m);

  return (
    <article
      className={cn(
        'ix-msg',
        m.direction === 'outbound' && 'ix-msg--out',
        long && 'is-long',
        long && expanded && 'is-open',
      )}
    >
      <header>
        <span className="ix-av ix-av--sm">{ixInitials(from)}</span>
        <div className="ix-msg__who">
          <strong title={m.from.email}>{from}</strong>
          {m.channel === 'email' ? (
            <span className="ix-msg__to">
              To: {m.to.map(displayName).join(', ') || '—'}
              {m.cc.length ? ` · Cc: ${m.cc.map(displayName).join(', ')}` : ''}
            </span>
          ) : null}
          {/* its own line: "Sending…" or "Failed to send" must never be cut off */}
          {notes.length ? <span className="ix-msg__state">{notes.join(' · ')}</span> : null}
        </div>
        {at ? (
          <time dateTime={at} title={new Date(at).toLocaleString()}>
            {clock(at)}
          </time>
        ) : null}
        <span className="ix-tip ix-msg__ch" data-tip={CHANNELS[m.channel].label}>
          <IxIcon name={CHANNELS[m.channel].icon} className="ix-i--sm" />
        </span>
        {/* a chat message is answered in the box below, and is not an email to forward */}
        <button
          ref={menuRef}
          type="button"
          hidden={m.channel === 'chat'}
          className="ix-icon ix-tip ix-msg__act"
          data-tip="Message actions"
          aria-label="Message actions"
          aria-haspopup="menu"
          aria-expanded={menu}
          onClick={() => setMenu((v) => !v)}
        >
          <IxIcon name="vmore" className="ix-i--sm" />
        </button>
      </header>
      {html ? (
        <div
          className="ix-msg__body"
          style={{ whiteSpace: 'normal', overflowWrap: 'anywhere' }}
          dangerouslySetInnerHTML={{ __html: html.body }}
        />
      ) : (
        <div className="ix-msg__body" style={{ whiteSpace: 'pre-line' }}>
          {m.bodyText}
        </div>
      )}
      {html?.quoted ? (
        <>
          <button
            type="button"
            className="ix-quote-t"
            aria-expanded={quoteShown}
            aria-label={quoteShown ? 'Hide trimmed content' : 'Show trimmed content'}
            onClick={() => setQuoteShown((v) => !v)}
          >
            ···
          </button>
          {quoteShown ? (
            <div className="ix-quote" dangerouslySetInnerHTML={{ __html: html.quoted }} />
          ) : null}
        </>
      ) : null}
      {files.length ? (
        <ul className="ix-atts">
          {files.map((a) => (
            <li key={a.id}>
              <IxIcon name="clip" className="ix-i--xs" />
              <a href={attachmentUrl(m.id, a.id)} target="_blank" rel="noreferrer">
                {a.filename ?? 'attachment'}
              </a>
            </li>
          ))}
        </ul>
      ) : null}
      {scheduled ? (
        <p className="ix-comp__note">
          This email has not been sent yet.{' '}
          <button type="button" className="ix-link" onClick={() => onCancelScheduled(m)}>
            Cancel scheduled email
          </button>
        </p>
      ) : null}
      {long ? (
        <button
          type="button"
          className="ix-seemore"
          aria-expanded={expanded}
          onClick={() => setExpanded((v) => !v)}
        >
          <IxIcon name="chev" className="ix-i--xs" />
          <span>{expanded ? 'See less' : 'See more'}</span>
        </button>
      ) : null}

      {menu ? (
        <IxPopover
          anchor={menuRef.current}
          onClose={closeMenu}
          className="ix-pop--icons"
          label="Message actions"
          align="right"
        >
          <button
            type="button"
            role="menuitem"
            className="ix-mi"
            disabled={!canReply}
            onClick={() => {
              closeMenu();
              onReply(m);
            }}
          >
            <IxIcon name="reply" className="ix-i--sm" />
            Reply
          </button>
          <button
            type="button"
            role="menuitem"
            className="ix-mi"
            disabled={!canReply}
            onClick={() => {
              closeMenu();
              onForward(m);
            }}
          >
            <IxIcon name="fwd" className="ix-i--sm" />
            Forward
          </button>
          <button type="button" role="menuitem" className="ix-mi" disabled title="Coming soon">
            <IxIcon name="link" className="ix-i--sm" />
            Copy link
          </button>
        </IxPopover>
      ) : null}
    </article>
  );
}

/** An internal comment: never emailed or shown to a visitor. It says who can see it. */
function CommentNote({ comment, team }: { comment: InboxComment; team: boolean }) {
  return (
    <article className="ix-msg ix-msg--note">
      <header>
        <span className="ix-av ix-av--sm">{ixInitials(comment.author.name)}</span>
        <div className="ix-msg__who">
          <strong>{comment.author.name}</strong>
          <span className="ix-msg__to">
            Comment &middot; not emailed, only visible to {team ? 'your team' : 'you'}
          </span>
        </div>
        <time dateTime={comment.createdAt} title={new Date(comment.createdAt).toLocaleString()}>
          {clock(comment.createdAt)}
        </time>
      </header>
      <div className="ix-msg__body" style={{ whiteSpace: 'pre-line' }}>
        {commentParts(comment.body, comment.mentions).map((part, i) =>
          part.mention ? (
            <span key={i} className="ix-at">
              {part.text}
            </span>
          ) : (
            <span key={i}>{part.text}</span>
          ),
        )}
      </div>
    </article>
  );
}

type InboxMessagesProps = Parameters<typeof Timeline>[0];

/**
 * The timeline redraws only when what it shows changes. The page redraws on every key typed in
 * a reply, and a heavy email (nested tables) is slow to go through again each time.
 */
const MemoTimeline = memo(Timeline);

export function InboxMessages(props: InboxMessagesProps) {
  const latest = useRef(props);
  useLayoutEffect(() => {
    latest.current = props;
  });
  const onReply = useCallback((m: InboxMessage) => latest.current.onReply(m), []);
  const onForward = useCallback((m: InboxMessage) => latest.current.onForward(m), []);
  const onCancelScheduled = useCallback(
    (m: InboxMessage) => latest.current.onCancelScheduled(m),
    [],
  );
  return (
    <MemoTimeline
      messages={props.messages}
      comments={props.comments}
      mailboxAddress={props.mailboxAddress}
      team={props.team}
      canReply={props.canReply}
      onReply={onReply}
      onForward={onForward}
      onCancelScheduled={onCancelScheduled}
    />
  );
}

function Timeline({
  messages,
  comments,
  mailboxAddress,
  team,
  canReply,
  onReply,
  onForward,
  onCancelScheduled,
}: {
  messages: InboxMessage[];
  comments: InboxComment[];
  /** Where the conversation arrived: an address, or a team inbox's name. */
  mailboxAddress: string | null;
  /** It is in a team inbox. */
  team: boolean;
  canReply: boolean;
  onReply: (m: InboxMessage) => void;
  onForward: (m: InboxMessage) => void;
  onCancelScheduled: (m: InboxMessage) => void;
}) {
  // An email still being sent has no time yet: it counts as now.
  const now = new Date().toISOString();
  let day = '';
  const first = messages[0];

  return (
    <>
      {timelineItems(messages, comments).map((item) => {
        const at = item.kind === 'comment' ? item.comment.createdAt : (item.message.sentAt ?? now);
        const key = dayKey(at);
        const newDay = key !== day;
        day = key;
        const id = item.kind === 'comment' ? `c-${item.comment.id}` : item.message.id;
        return (
          <Fragment key={id}>
            {newDay ? (
              <div className="ix-day">
                <span>{dayLabel(at)}</span>
              </div>
            ) : null}
            {item.kind === 'comment' ? (
              <CommentNote comment={item.comment} team={team} />
            ) : (
              <MessageCard
                m={item.message}
                canReply={canReply}
                onReply={onReply}
                onForward={onForward}
                onCancelScheduled={onCancelScheduled}
              />
            )}
          </Fragment>
        );
      })}
      {first?.sentAt ? (
        <p className="ix-sys">
          Conversation created from {CHANNELS[first.channel].from} via {mailboxAddress}
          <br />
          at {clock(first.sentAt)}.
        </p>
      ) : null}
    </>
  );
}
