'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 { createLoggedEmail, type ActivityLink } from '@/features/activities/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 { gmtLabel } from './LogCallDrawer';
import {
  actionErrorText,
  fromLocalInput,
  toLocalInput,
  useOpenCount,
  useUserPrefs,
} from './shared';
import { snippetTargetFor } from '@/features/snippets/model';

/** Manually log an email onto CRM records (POST /activities/emails). HubSpot "Log email" parity. */
export function LogEmailDrawer({
  open,
  onClose,
  link,
  recordName,
  recordSecondary,
  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>;
  /** Who stands for the record when a snippet is filled (a company's or deal's contact). */
  snippetContactId?: string;
}) {
  const toast = useToast();
  const prefs = useUserPrefs();
  const [bodyHtml, setBodyHtml] = useState('');
  const [busy, setBusy] = useState(false);
  const [saved, setSaved] = useState(false);
  const [followUp, setFollowUp] = useState(false);
  const [followDue, setFollowDue] = useState<FollowUpDueKey>('biz3');
  const [customDueDate, setCustomDueDate] = useState('');
  const [taskType, setTaskType] = useState('todo');
  const [occurredAt, setOccurredAt] = useState(() => toLocalInput(new Date(), prefs.timeZone));
  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('');
    setSaved(false);
    setFollowUp(false);
    setFollowDue('biz3');
    setCustomDueDate('');
    setTaskType('todo');
    setOccurredAt(toLocalInput(new Date(), prefs.timeZone));
    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'}`
      : recordSecondary?.trim() || recordName;

  const submit = async () => {
    if (empty || busy) return;
    const when = fromLocalInput(occurredAt, prefs.timeZone);
    if (!when) {
      toast('Enter when the email happened', 'danger');
      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 (!saved) {
        await createLoggedEmail({
          bodyHtml,
          occurredAt: when,
          direction: 'outbound',
          links,
        });
        setSaved(true);
      }
      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(`Email logged, follow-up task failed: ${actionErrorText(taskErr)}`, 'danger', {
            durationMs: 8000,
          });
          onLogged();
          onClose();
          return;
        }
      }
      toast(followUp ? 'Email logged with follow-up task' : 'Email logged');
      onLogged();
      onClose();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  return (
    <DraggablePopup
      id={`${link.type}LogEmailModal`}
      open={open}
      onClose={onClose}
      confirmClose={!empty && !saved}
      composer={composer}
      title="Log Email"
      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()}
        >
          Log email
        </button>
      }
    >
      {composer ? (
        <div className="acx-fields">
          <div className="acx-field">
            <span className="acx-field__label">Contacted</span>
            <AssocForPill
              ref={forPillRef}
              wrap={false}
              composer
              label={forLabel}
              expanded={assocOpen}
              onClick={() => setAssocOpen((o) => !o)}
            />
          </div>
          <div className="acx-field acx-field--grow">
            <span className="acx-field__label">Activity date</span>
            <label className="acx-dt">
              <input
                type="datetime-local"
                value={occurredAt}
                onChange={(e) => setOccurredAt(e.target.value)}
                required
                aria-label="Activity date"
              />
              <span className="acx-dt__tz">{gmtLabel(prefs.timeZone)}</span>
            </label>
          </div>
        </div>
      ) : (
        <>
          <AssocForPill
            ref={forPillRef}
            caption="Contacted"
            label={forLabel}
            expanded={assocOpen}
            onClick={() => setAssocOpen((o) => !o)}
          />

          <label className="field crm-mb-3">
            <span className="field__label">Activity date</span>
            <input
              className="input"
              type="datetime-local"
              value={occurredAt}
              onChange={(e) => setOccurredAt(e.target.value)}
              required
            />
          </label>
        </>
      )}

      <ComposeRichText
        openKey={openCount}
        value={bodyHtml}
        onChange={setBodyHtml}
        label="Email"
        placeholder="Start typing to log an email…"
        minHeight={composer ? 102 : 180}
        plannedTools={Boolean(composer)}
        snippetTarget={snippetTargetFor(link, snippetContactId)}
      />

      <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>
  );
}
