'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { SnippetMenu } from '@/features/snippets/ui/SnippetMenu';
import { useEditableSnippetHash } from '@/features/snippets/ui/useSnippetHash';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  addTaskComment,
  COMMENT_FILE_MAX_BYTES,
  COMMENT_FILES_MAX,
  commentAgo,
  commentFileUrl,
  fileSizeText,
  snippetTargetOf,
  uploadCommentFile,
  type CommentFile,
  deleteTaskComment,
  listTaskComments,
  mentionHits,
  mentionQueryOf,
  postedText,
  type TaskComment,
  type CommentOn,
} from '../comments';

const initials = (name: string | null | undefined) =>
  (name ?? '')
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0]!.toUpperCase())
    .join('') || '?';

/** Images inlined in a comment, as the design (activity.js:583): under 600 KB. */
const MAX_IMAGE_BYTES = 600_000;

type Member = { userId: string; name: string };

/** The comments of a task: loaded with the page for the button's count, and after each change. */
export function useTaskComments(taskId: string, on: CommentOn = 'task') {
  const [comments, setComments] = useState<TaskComment[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const reload = useCallback(async () => {
    setError(null);
    try {
      setComments((await listTaskComments(taskId, undefined, on)).data);
    } catch (err) {
      setError(errorText(err));
    }
  }, [taskId, on]);
  useEffect(() => {
    void reload();
  }, [reload]);
  return { comments, error, reload, setComments };
}

/**
 * TK3b (Tasks parity #674): the design's "All comments" side panel (activity.php:323-364,
 * activity.js:476-600): a comment box with formatting, links, images and @mentions that notify
 * the people named; the comments newest first, each deletable by its author or an admin.
 * TK3c: Insert snippet fills one of the person's snippets for the task's first contact (the
 * design only inserts a fixed sentence); Attach file uploads files to the comment (the design only
 * inserts the file's name), shown under it and downloaded by whoever may view the task.
 */
export function TaskCommentsPanel({
  taskId,
  on = 'task',
  open,
  onClose,
  state,
  canComment,
  members,
  meName,
  links,
}: {
  taskId: string;
  /** CL10: a call's comments (the call page), else a task's. */
  on?: CommentOn;
  open: boolean;
  onClose: () => void;
  state: ReturnType<typeof useTaskComments>;
  /** Members who may create records (not read-only). */
  canComment: boolean;
  /** People an @mention offers. */
  members: Member[];
  meName: string;
  /** The task's linked records: snippets fill for its first contact. */
  links: ReadonlyArray<{ objectType: string; id: string }>;
}) {
  const toast = useToast();
  const { comments, error, reload, setComments } = state;
  const [editing, setEditing] = useState(false);
  const [hasText, setHasText] = useState(false);
  const [posting, setPosting] = useState(false);
  const [moreOpen, setMoreOpen] = useState(false);
  const [mention, setMention] = useState<{ query: string; hits: Member[]; active: number } | null>(
    null,
  );
  const textRef = useRef<HTMLDivElement>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  // TK3c: snippets (the task's records fill their fields) and attached files.
  const snippetTarget = snippetTargetOf(links);
  // HUB-417: "#shortcut" while typing a comment.
  const commentHash = useEditableSnippetHash(textRef, { target: snippetTarget });
  const snippetRef = useRef<HTMLButtonElement>(null);
  const [snippetOpen, setSnippetOpen] = useState(false);
  const savedRange = useRef<Range | null>(null);
  const attachRef = useRef<HTMLInputElement>(null);
  const [files, setFiles] = useState<CommentFile[]>([]);
  const [uploading, setUploading] = useState(0);
  const phRef = useRef<HTMLButtonElement>(null);

  const closeEditor = () => {
    if (textRef.current) textRef.current.innerHTML = '';
    setEditing(false);
    setHasText(false);
    setMention(null);
    setMoreOpen(false);
    setSnippetOpen(false);
    commentHash.close();
    setFiles([]);
  };

  // Escape closes the panel (or the mention list first); the design keeps typed text open.
  useEffect(() => {
    if (!open) return;
    const key = (e: KeyboardEvent) => {
      if (e.key !== 'Escape' || mention) return;
      const typing = document.activeElement === textRef.current && textHas(textRef.current);
      if (!typing) onClose();
    };
    document.addEventListener('keydown', key);
    return () => document.removeEventListener('keydown', key);
  }, [open, mention, onClose]);
  useEffect(() => {
    if (open) phRef.current?.focus();
    else closeEditor();
  }, [open]);
  useEffect(() => {
    if (editing) textRef.current?.focus();
  }, [editing]);

  const refresh = () => setHasText(textHas(textRef.current));
  const run = (cmd: string) => {
    textRef.current?.focus();
    document.execCommand(cmd, false);
    setMoreOpen(false);
    refresh();
  };
  const insertHtml = (html: string) => {
    textRef.current?.focus();
    document.execCommand('insertHTML', false, html);
    refresh();
  };
  /** The caret in the box before a popover takes focus, to insert there afterwards. */
  const keepRange = () => {
    const sel = window.getSelection();
    const r = sel?.rangeCount ? sel.getRangeAt(0) : null;
    savedRange.current = r && textRef.current?.contains(r.startContainer) ? r.cloneRange() : null;
  };
  const insertAtSaved = (html: string) => {
    const box = textRef.current;
    if (!box) return; // the box closed while the snippet loaded
    box.focus();
    const sel = window.getSelection();
    if (savedRange.current && sel) {
      sel.removeAllRanges();
      sel.addRange(savedRange.current);
    }
    insertHtml(html);
  };
  const attach = async (picked: FileList | null) => {
    const list = [...(picked ?? [])];
    if (!list.length) return;
    if (files.length + uploading + list.length > COMMENT_FILES_MAX) {
      toast(`Attach up to ${COMMENT_FILES_MAX} files to one comment`, 'danger');
      return;
    }
    for (const file of list) {
      if (file.size > COMMENT_FILE_MAX_BYTES) {
        toast(`${file.name} is larger than 25 MB`, 'danger');
        continue;
      }
      setUploading((n) => n + 1);
      try {
        const saved = await uploadCommentFile(taskId, file, on);
        setFiles((cur) => [...cur, saved]);
      } catch (err) {
        toast(`${file.name}: ${errorText(err)}`, 'danger', { durationMs: 8000 });
      } finally {
        setUploading((n) => n - 1);
      }
    }
  };
  const download = async (commentId: string, f: CommentFile) => {
    try {
      window.location.assign(await commentFileUrl(taskId, commentId, f.id, on));
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };
  const link = () => {
    const txt = window.getSelection()?.toString() ?? '';
    const href = /^(https?:\/\/|www\.)/i.test(txt)
      ? /^www\./i.test(txt)
        ? `https://${txt}`
        : txt
      : '';
    if (href) {
      textRef.current?.focus();
      document.execCommand('createLink', false, href);
      refresh();
    } else toast('Select a web address in your comment, then click Link', 'info');
  };

  /** The text before the caret in the editor's current text node, for the mention list. */
  const paintMention = () => {
    const sel = window.getSelection();
    const node = sel?.rangeCount ? sel.getRangeAt(0).startContainer : null;
    if (!sel || !node || node.nodeType !== 3 || !textRef.current?.contains(node)) {
      setMention(null);
      return;
    }
    const query = mentionQueryOf((node.textContent ?? '').slice(0, sel.getRangeAt(0).startOffset));
    const hits = query === null ? [] : mentionHits(members, query);
    setMention(query !== null && hits.length ? { query, hits, active: 0 } : null);
  };
  const pickMention = (person: Member) => {
    const sel = window.getSelection();
    if (!mention || !sel?.rangeCount) return;
    const range = sel.getRangeAt(0);
    const node = range.startContainer;
    const end = range.startOffset;
    const start = end - mention.query.length - 1;
    const r = document.createRange();
    r.setStart(node, Math.max(0, start));
    r.setEnd(node, end);
    sel.removeAllRanges();
    sel.addRange(r);
    document.execCommand(
      'insertHTML',
      false,
      `<span class="act-com__at" data-user-id="${escAttr(person.userId)}">@${escText(person.name)}</span>&nbsp;`,
    );
    setMention(null);
    refresh();
  };

  const post = async () => {
    const box = textRef.current;
    if (!box || (!textHas(box) && !files.length) || posting || uploading) return;
    const chips = [...box.querySelectorAll<HTMLElement>('.act-com__at[data-user-id]')];
    const ids = [...new Set(chips.map((c) => c.dataset.userId!).filter(Boolean))];
    const names = [...new Set(chips.map((c) => (c.textContent ?? '').replace(/^@/, '')))];
    setPosting(true);
    try {
      const saved = await addTaskComment(
        taskId,
        {
          body: box.innerHTML,
          mentionUserIds: ids,
          fileIds: files.map((f) => f.id),
        },
        on,
      );
      setComments((cur) => [saved, ...(cur ?? [])]);
      closeEditor();
      phRef.current?.focus();
      toast(postedText(names));
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setPosting(false);
    }
  };

  const remove = async (c: TaskComment) => {
    try {
      await deleteTaskComment(taskId, c.id, on);
      setComments((cur) => (cur ?? []).filter((x) => x.id !== c.id));
      toast('Comment deleted');
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    }
  };

  const onImage = (file: File | undefined) => {
    if (!file) return;
    if (!/^image\/(png|jpe?g|gif|webp)$/.test(file.type) || file.size >= MAX_IMAGE_BYTES) {
      toast('Pick a PNG, JPG, GIF or WebP image under 600 KB', 'danger');
      return;
    }
    const reader = new FileReader();
    reader.onload = () => insertHtml(`<img src="${escAttr(String(reader.result))}" alt="">`);
    reader.readAsDataURL(file);
  };

  if (!open) return null;
  return (
    <aside
      className="act-panel act-panel--comments is-open"
      role="dialog"
      aria-modal="false"
      aria-labelledby="actComT"
    >
      <header className="act-panel__head">
        <h2 id="actComT">All comments</h2>
        <button type="button" className="act-icon" aria-label="Close" onClick={onClose}>
          <CrmIcon name="x" className="iconSize-18" />
        </button>
      </header>
      <div className="act-panel__body act-com">
        {canComment ? (
          <div className="act-com__new">
            <span className="act-av act-av--sm" aria-hidden="true">
              {initials(meName)}
            </span>
            <div className={cn('act-com__box', editing && 'is-open')}>
              <button
                ref={phRef}
                type="button"
                className="act-com__ph"
                hidden={editing}
                onClick={() => setEditing(true)}
              >
                Leave a comment and mention a teammate using @
              </button>
              <div className="act-com__editor" hidden={!editing}>
                <div
                  ref={textRef}
                  className="act-com__text"
                  contentEditable
                  suppressContentEditableWarning
                  role="textbox"
                  aria-multiline="true"
                  aria-label="Comment"
                  data-placeholder="Leave a comment and mention a teammate using @"
                  onInput={() => {
                    refresh();
                    paintMention();
                    commentHash.track();
                  }}
                  onBlur={commentHash.close}
                  onKeyDown={(e) => {
                    if (mention) {
                      if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
                        e.preventDefault();
                        const n = mention.hits.length;
                        setMention({
                          ...mention,
                          active: (mention.active + (e.key === 'ArrowDown' ? 1 : -1) + n) % n,
                        });
                        return;
                      }
                      if (e.key === 'Enter' || e.key === 'Tab') {
                        e.preventDefault();
                        pickMention(mention.hits[mention.active]!);
                        return;
                      }
                      if (e.key === 'Escape') {
                        e.preventDefault();
                        setMention(null);
                        return;
                      }
                    }
                    if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
                      e.preventDefault();
                      void post();
                      return;
                    }
                    if (commentHash.onKeyDown(e)) e.preventDefault();
                  }}
                />
                {commentHash.list}
                {/* The toolbar keeps the editor's selection (activity.js:546). */}
                <div
                  className="act-com__tools"
                  role="toolbar"
                  aria-label="Formatting"
                  onMouseDown={(e) => {
                    if ((e.target as HTMLElement).closest('button')) e.preventDefault();
                  }}
                >
                  <ToolButton
                    label="Bold"
                    icon="M7 5h6a3.5 3.5 0 0 1 0 7H7zM7 12h7a3.5 3.5 0 0 1 0 7H7z"
                    onClick={() => run('bold')}
                  />
                  <ToolButton
                    label="Italic"
                    icon="M14 5h-4M14 19h-4M14 5l-4 14"
                    onClick={() => run('italic')}
                  />
                  <ToolButton
                    label="Underline"
                    icon="M7 4v7a5 5 0 0 0 10 0V4M5 20h14"
                    onClick={() => run('underline')}
                  />
                  <ToolButton
                    label="Clear formatting"
                    icon="M6 5h12M12 5l-3 14M15 15l5 5M20 15l-5 5"
                    onClick={() => run('removeFormat')}
                  />
                  <span className="act-com__more">
                    <button
                      type="button"
                      aria-haspopup="menu"
                      aria-expanded={moreOpen}
                      onClick={() => setMoreOpen((o) => !o)}
                    >
                      More
                      <svg className="act-tri" viewBox="0 0 10 6" aria-hidden="true">
                        <path d="M0 0h10L5 6z" fill="currentColor" />
                      </svg>
                    </button>
                    <span className="act-com__moremenu" role="menu" hidden={!moreOpen}>
                      <button type="button" role="menuitem" onClick={() => run('strikeThrough')}>
                        Strikethrough
                      </button>
                      <button
                        type="button"
                        role="menuitem"
                        onClick={() => run('insertUnorderedList')}
                      >
                        Bulleted list
                      </button>
                      <button
                        type="button"
                        role="menuitem"
                        onClick={() => run('insertOrderedList')}
                      >
                        Numbered list
                      </button>
                    </span>
                  </span>
                  <span className="act-com__sep" aria-hidden="true" />
                  <ToolButton
                    label="Insert link"
                    icon="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"
                    onClick={link}
                  />
                  <ToolButton
                    label="Insert image"
                    icon="M3 5h18v14H3zM3 16l5-5 4 4 3-3 6 6"
                    onClick={() => fileRef.current?.click()}
                  />
                  <button
                    ref={snippetRef}
                    type="button"
                    aria-label="Insert snippet"
                    aria-haspopup="dialog"
                    aria-expanded={snippetOpen}
                    title="Insert snippet"
                    onClick={() => {
                      keepRange();
                      setSnippetOpen((o) => !o);
                    }}
                  >
                    <svg viewBox="0 0 24 24" aria-hidden="true">
                      <path d="M4 9l8-4 8 4-8 4zM8 11v4c0 1.5 2 3 4 3s4-1.5 4-3v-4" />
                    </svg>
                  </button>
                  <ToolButton
                    label="Indent"
                    icon="M4 5h16M10 10h10M10 14h10M4 19h16M4 9l3 3-3 3"
                    onClick={() => run('indent')}
                  />
                  <ToolButton
                    label="Attach file"
                    icon="m20 11-8.5 8.5a5 5 0 0 1-7-7L13 4a3.5 3.5 0 0 1 5 5l-8.5 8.5a2 2 0 0 1-3-3L14 7"
                    onClick={() => attachRef.current?.click()}
                  />
                  <input
                    ref={attachRef}
                    type="file"
                    multiple
                    hidden
                    onChange={(e) => {
                      void attach(e.target.files);
                      e.target.value = '';
                    }}
                  />
                  <input
                    ref={fileRef}
                    type="file"
                    accept="image/png,image/jpeg,image/gif,image/webp"
                    hidden
                    onChange={(e) => {
                      onImage(e.target.files?.[0]);
                      e.target.value = '';
                    }}
                  />
                </div>
                <SnippetMenu
                  open={snippetOpen}
                  anchorRef={snippetRef}
                  onClose={() => setSnippetOpen(false)}
                  target={snippetTarget}
                  onInsert={insertAtSaved}
                />
                {files.length || uploading ? (
                  <ul className="act-com__files" aria-label="Attached files">
                    {files.map((f) => (
                      <li key={f.id}>
                        <span>
                          📎 {f.name} · {fileSizeText(f.sizeBytes)}
                        </span>
                        <button
                          type="button"
                          aria-label={`Remove ${f.name}`}
                          onClick={() => setFiles((cur) => cur.filter((x) => x.id !== f.id))}
                        >
                          ×
                        </button>
                      </li>
                    ))}
                    {uploading ? <li className="crm-text-muted">Uploading…</li> : null}
                  </ul>
                ) : null}
                {mention ? (
                  <div className="act-com__mention" role="listbox" aria-label="Mention a teammate">
                    {mention.hits.map((p, i) => (
                      <button
                        key={p.userId}
                        type="button"
                        role="option"
                        aria-selected={i === mention.active}
                        onMouseDown={(e) => e.preventDefault()}
                        onClick={() => pickMention(p)}
                      >
                        <span className="act-av act-av--sm">{initials(p.name)}</span>
                        {p.name}
                      </button>
                    ))}
                  </div>
                ) : null}
              </div>
              {editing ? (
                <div className="act-com__acts">
                  <button
                    type="button"
                    className={cn('btn-crm btn-crm--primary btn-crm--sm', posting && 'is-loading')}
                    disabled={(!hasText && !files.length) || posting || uploading > 0}
                    onClick={() => void post()}
                  >
                    Comment
                  </button>
                  <button
                    type="button"
                    className="act-com__cancel"
                    onClick={() => {
                      closeEditor();
                      phRef.current?.focus();
                    }}
                  >
                    Cancel
                  </button>
                </div>
              ) : null}
            </div>
          </div>
        ) : null}

        {error ? (
          <p className="act-com__error" role="alert">
            Comments couldn&rsquo;t load: {error}{' '}
            <button type="button" className="act-link" onClick={() => void reload()}>
              Try again
            </button>
          </p>
        ) : comments === null ? (
          <p className="crm-text-muted">Loading comments…</p>
        ) : comments.length ? (
          <ul className="act-com__list">
            {comments.map((c) => (
              <li key={c.id} className="act-com__item">
                <span className="act-av act-av--sm" aria-hidden="true">
                  {initials(c.author?.name)}
                </span>
                <div className="act-com__main">
                  <div className="act-com__meta">
                    <strong>{c.author?.name ?? 'Automation'}</strong>
                    <time dateTime={c.createdAt}>{commentAgo(c.createdAt)}</time>
                  </div>
                  {/* Cleaned by the API to the design's allow-list (no scripts or styles). */}
                  <div className="act-com__body" dangerouslySetInnerHTML={{ __html: c.body }} />
                  {c.attachments.length ? (
                    <ul className="act-com__files" aria-label="Attachments">
                      {c.attachments.map((f) => (
                        <li key={f.id}>
                          <button
                            type="button"
                            className="act-link"
                            title={`Download ${f.name}`}
                            onClick={() => void download(c.id, f)}
                          >
                            📎 {f.name}
                          </button>{' '}
                          <small className="crm-text-muted">{fileSizeText(f.sizeBytes)}</small>
                        </li>
                      ))}
                    </ul>
                  ) : null}
                  {c.canDelete ? (
                    <button type="button" className="act-com__del" onClick={() => void remove(c)}>
                      Delete
                    </button>
                  ) : null}
                </div>
              </li>
            ))}
          </ul>
        ) : (
          <div className="act-com__empty">
            {/* The design's empty-state art (activity.php:362). */}
            <svg className="act-com__art" viewBox="0 0 120 110" aria-hidden="true">
              <path d="M74 40 104 92" stroke="#e8603c" strokeWidth="2" fill="none" />
              <path d="M60 60 92 92" stroke="#e8603c" strokeWidth="2" fill="none" />
              <circle
                cx="46"
                cy="38"
                r="34"
                fill="var(--surface)"
                stroke="#e8603c"
                strokeWidth="2"
              />
              <path d="M14 46A34 34 0 0 1 30 8" stroke="#1f5b5b" strokeWidth="2.5" fill="none" />
              <path d="M46 4A34 34 0 0 1 80 38" stroke="#7a1450" strokeWidth="2.5" fill="none" />
              <path
                d="M34 18h16l8 8v28H34z"
                fill="var(--surface)"
                stroke="#7a1450"
                strokeWidth="2"
              />
              <path d="M50 18v8h8z" fill="#e8603c" />
              <path d="M40 32l12 12M52 32 40 44" stroke="#e8603c" strokeWidth="1.8" />
              <rect
                x="98"
                y="86"
                width="12"
                height="12"
                fill="#7a1450"
                stroke="#e8603c"
                strokeWidth="2"
              />
            </svg>
            <h3>No comments yet</h3>
            <p>
              {canComment ? (
                <>
                  Leave a comment above and notify a coworker using <strong>@mentions.</strong>
                </>
              ) : (
                `Nobody has commented on this ${on}.`
              )}
            </p>
          </div>
        )}
      </div>
    </aside>
  );
}

function ToolButton({
  label,
  icon,
  onClick,
  disabledTitle,
}: {
  label: string;
  icon: string;
  onClick?: () => void;
  /** Drawn off, with this reason. */
  disabledTitle?: string;
}) {
  return (
    <button
      type="button"
      aria-label={label}
      title={disabledTitle ?? label}
      disabled={Boolean(disabledTitle)}
      onClick={onClick}
    >
      <svg viewBox="0 0 24 24" aria-hidden="true">
        <path d={icon} />
      </svg>
    </button>
  );
}

function textHas(el: HTMLElement | null): boolean {
  return Boolean(el && ((el.textContent ?? '').trim() || el.querySelector('img')));
}

function escText(value: string): string {
  return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function escAttr(value: string): string {
  return escText(value).replace(/"/g, '&quot;');
}
