'use client';

import { useMemo, useRef, useState, type RefObject } from 'react';
import { ComposeRichText, htmlIsEmpty } from '@/components/crm/ComposeRichText';
import type { ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import { DraggablePopup } from '@/components/crm/DraggablePopup';
import { useToast } from '@/components/crm/ToastProvider';
import { createNote, type ActivityLink } from '@/features/activities/api.client';
import { MAX_FILE_BYTES, uploadRecordFile } from '@/features/files/api.client';
import { createTask } from '@/features/tasks/api.client';
import { cn } from '@/lib/utils/cn';
import { AssociatedRecordsPanel, AssocForPill } from './AssociatedRecordsPanel';
import { MAX_NOTE_MEETING_LINKS, taskLinksCapped, type AssocRecord } from './assocTypes';
import { FollowUpTaskControls, followUpDueDate, type FollowUpDueKey } from './FollowUpTaskControls';
import { actionErrorText, useOpenCount, useUserPrefs } from './shared';
import { snippetTargetFor } from '@/features/snippets/model';

/** Log a note linked to one or more records (POST /activities/notes). */
export function LogNoteDrawer({
  open,
  onClose,
  link,
  recordName,
  recordSecondary,
  /** Extra records to pre-check (e.g. contact's companies / deal's contacts). */
  initialAssociations,
  onLogged,
  composer,
  snippetContactId,
}: {
  open: boolean;
  onClose: () => void;
  link: ActivityLink;
  recordName: string;
  recordSecondary?: string | null;
  initialAssociations?: AssocRecord[];
  onLogged: () => void;
  /** Contacts: the design's floating window. */
  composer?: RefObject<ComposerWindowHandle | null>;
  /**
   * CQS1 #715 (Companies, Deals): the contact a snippet is filled for when the note isn't on a
   * contact (the API fills snippets for a contact). Without one, a note on another record has no
   * snippets.
   */
  snippetContactId?: string;
}) {
  const toast = useToast();
  const prefs = useUserPrefs();
  const [bodyHtml, setBodyHtml] = useState('');
  const [busy, setBusy] = useState(false);
  /** After createNote succeeds, retries must not post another note. */
  const [noteSaved, setNoteSaved] = useState(false);
  /** HUB-325: files to attach, uploaded on the note once it is saved. */
  const [files, setFiles] = useState<File[]>([]);
  const fileInput = useRef<HTMLInputElement>(null);
  const [followUp, setFollowUp] = useState(false);
  const [followDue, setFollowDue] = useState<FollowUpDueKey>('biz3');
  const [customDueDate, setCustomDueDate] = useState('');
  const [taskType, setTaskType] = useState('todo');
  const primary: AssocRecord = useMemo(
    () => ({
      type: link.type,
      id: link.id,
      displayName: recordName,
      subtitle: recordSecondary ?? null,
    }),
    [link.type, link.id, recordName, recordSecondary],
  );
  const seedAssoc = useMemo(() => {
    const seen = new Set<string>([`${primary.type}:${primary.id}`]);
    const extra: AssocRecord[] = [];
    for (const a of initialAssociations ?? []) {
      const key = `${a.type}:${a.id}`;
      if (seen.has(key)) continue;
      seen.add(key);
      extra.push(a);
    }
    return [primary, ...extra].slice(0, MAX_NOTE_MEETING_LINKS);
  }, [primary, initialAssociations]);
  const [assoc, setAssoc] = useState<AssocRecord[]>(seedAssoc);
  const [assocOpen, setAssocOpen] = useState(false);
  const forPillRef = useRef<HTMLButtonElement>(null);

  const openCount = useOpenCount(open, () => {
    setBodyHtml('');
    setNoteSaved(false);
    setFiles([]);
    setFollowUp(false);
    setFollowDue('biz3');
    setCustomDueDate('');
    setTaskType('todo');
    setAssoc(seedAssoc);
    setAssocOpen(false);
  });

  const empty = useMemo(() => htmlIsEmpty(bodyHtml), [bodyHtml]);
  const forLabel =
    assoc.length > 1
      ? `${recordName} and ${assoc.length - 1} record${assoc.length === 2 ? '' : 's'}`
      : recordName;

  const addFiles = (picked: File[]) => {
    if (busy || noteSaved) return;
    const big = picked.filter((file) => file.size > MAX_FILE_BYTES);
    if (big.length) toast(`${big.map((b) => b.name).join(', ')}: over 25 MB`, 'danger');
    setFiles((cur) => [...cur, ...picked.filter((file) => file.size <= MAX_FILE_BYTES)]);
  };

  const submit = async () => {
    if (empty || busy) return;
    const links = assoc.map((a) => ({ type: a.type, id: a.id })).slice(0, MAX_NOTE_MEETING_LINKS);
    if (!links.length) {
      toast('Associate at least one record', 'danger');
      return;
    }
    setBusy(true);
    try {
      if (!noteSaved) {
        const note = await createNote({ bodyHtml, links });
        setNoteSaved(true);
        // The files go on the note, so they show on every record it is on (HUB-325).
        const failed: string[] = [];
        for (const file of files) {
          try {
            await uploadRecordFile({ type: 'activity', id: note.id }, file);
          } catch (err) {
            failed.push(`${file.name} (${actionErrorText(err)})`);
          }
        }
        if (failed.length) {
          // Named, with the reason, so they can be attached again from the note.
          toast(
            `Note saved, but these attachments could not be uploaded: ${failed.join('; ')}`,
            'danger',
            {
              durationMs: 12000,
            },
          );
        }
      }
      if (followUp) {
        try {
          const taskSafe = taskLinksCapped(assoc);
          if (!taskSafe.length) {
            throw new Error('Follow-up needs a contact, company, or deal association');
          }
          await createTask({
            title: `Follow up with ${recordName}`,
            taskType,
            dueDate: followUpDueDate(followDue, prefs.timeZone, customDueDate),
            links: taskSafe,
          });
        } catch (taskErr) {
          toast(`Note saved, follow-up task failed: ${actionErrorText(taskErr)}`, 'danger', {
            durationMs: 8000,
          });
          onLogged();
          onClose();
          return;
        }
      }
      toast(followUp ? 'Note created with follow-up task' : 'Note logged');
      onLogged();
      onClose();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  return (
    <DraggablePopup
      composer={composer}
      id={`${link.type}NoteModal`}
      open={open}
      onClose={onClose}
      confirmClose={!empty && !noteSaved}
      title="Note"
      size="md"
      footer={
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          disabled={empty || busy}
          aria-busy={busy}
          onClick={() => void submit()}
        >
          Create note
        </button>
      }
    >
      <AssocForPill
        ref={forPillRef}
        label={forLabel}
        expanded={assocOpen}
        composer={Boolean(composer)}
        onClick={() => setAssocOpen((o) => !o)}
      />

      <ComposeRichText
        openKey={openCount}
        value={bodyHtml}
        onChange={setBodyHtml}
        label="Note"
        placeholder="Start typing to leave a note…"
        minHeight={composer ? 102 : 180}
        plannedTools={Boolean(composer)}
        snippetTarget={snippetTargetFor(link, snippetContactId)}
        onAttachFiles={composer ? addFiles : undefined}
        attachDisabled={Boolean(composer) && (busy || noteSaved)}
      />

      <div className="note-attachments">
        {composer ? null : (
          <>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              disabled={busy || noteSaved}
              onClick={() => fileInput.current?.click()}
            >
              Attach files
            </button>
            <input
              ref={fileInput}
              type="file"
              multiple
              className="crm-visually-hidden"
              tabIndex={-1}
              aria-hidden
              onChange={(e) => {
                const picked = Array.from(e.target.files ?? []);
                e.target.value = '';
                addFiles(picked);
              }}
            />
          </>
        )}
        {files.length ? (
          <ul className="note-attachments__list">
            {files.map((file, i) => (
              <li key={`${file.name}-${i}`}>
                <span>{file.name}</span>
                <button
                  type="button"
                  className="note-attachments__remove"
                  aria-label={`Remove ${file.name}`}
                  disabled={busy || noteSaved}
                  onClick={() => setFiles((cur) => cur.filter((_, j) => j !== i))}
                >
                  ×
                </button>
              </li>
            ))}
          </ul>
        ) : null}
      </div>

      <AssociatedRecordsPanel
        className={composer ? 'acx-row' : undefined}
        value={assoc}
        onChange={setAssoc}
        locked={primary}
        maxSelected={MAX_NOTE_MEETING_LINKS}
        open={assocOpen}
        onOpenChange={setAssocOpen}
        extraAnchorRef={forPillRef}
      />

      <FollowUpTaskControls
        enabled={followUp}
        onEnabledChange={setFollowUp}
        taskType={taskType}
        onTaskTypeChange={setTaskType}
        dueKey={followDue}
        onDueKeyChange={setFollowDue}
        customDate={customDueDate}
        onCustomDateChange={setCustomDueDate}
        timeZone={prefs.timeZone}
        composer={Boolean(composer)}
      />
    </DraggablePopup>
  );
}
