'use client';

import { useMemo, useRef, useState, type RefObject } from 'react';
import { ComposeRichText, htmlIsEmpty } from '@/components/crm/ComposeRichText';
import { ComposerSelect } from '@/components/crm/ComposerSelect';
import type { ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import { DraggablePopup } from '@/components/crm/DraggablePopup';
import { useToast } from '@/components/crm/ToastProvider';
import {
  createCall,
  type ActivityLink,
  type CallDirection,
  type CallType,
} from '@/features/activities/api.client';
import { CALL_TYPE_OPTIONS } from '@/features/activities/callTypes';
import type { PicklistOption } from '@/features/picklists/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,
  seedAssociations,
  taskLinksCapped,
  type AssocRecord,
} from './assocTypes';
import { FollowUpTaskControls, followUpDueDate, type FollowUpDueKey } from './FollowUpTaskControls';
import { callDurationSeconds, canLogCall, logCallBody } from './logCall';
import {
  actionErrorText,
  fromLocalInput,
  toLocalInput,
  useOpenCount,
  useUserPrefs,
} from './shared';
import { snippetTargetFor } from '@/features/snippets/model';

const DIRECTIONS = [
  { value: '', label: 'Select call direction' },
  { value: 'inbound', label: 'Inbound' },
  { value: 'outbound', label: 'Outbound' },
];

const isCallType = (v: string): v is CallType => CALL_TYPE_OPTIONS.some((o) => o.value === v);

export function gmtLabel(timeZone: string): string {
  try {
    const name = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'shortOffset' })
      .formatToParts(new Date())
      .find((p) => p.type === 'timeZoneName')?.value;
    return name?.replace(/^UTC/, 'GMT') ?? timeZone;
  } catch {
    return timeZone;
  }
}

/** Who the rep is ringing, and the number to ring from their own phone. */
function CallNumber({ name, phone }: { name: string; phone: string }) {
  return (
    <div className="acx-callnum">
      <strong>{name}</strong>
      {phone ? (
        <a href={`tel:${phone.replace(/[^\d+]/g, '')}`}>{phone}</a>
      ) : (
        <span>No phone number on this record</span>
      )}
      <p>
        Call from your phone and take notes below. &quot;Log call&quot; saves them to the timeline.
      </p>
    </div>
  );
}

/**
 * CGL6 (go-live QA #6): Call Title and Call duration, as the Calls page's Log call asks for them,
 * in the composer's fields (`acx-field`) or the popup's (`field`).
 */
export function CallTitleDurationFields({
  composer,
  title,
  onTitle,
  minutes,
  onMinutes,
  seconds,
  onSeconds,
}: {
  composer: boolean;
  title: string;
  onTitle: (v: string) => void;
  minutes: string;
  onMinutes: (v: string) => void;
  seconds: string;
  onSeconds: (v: string) => void;
}) {
  const wrap = composer ? 'acx-field' : 'field';
  const lbl = composer ? 'acx-field__label' : 'field__label';
  const input = composer ? 'acx-input' : 'input';
  return (
    <>
      <label className={wrap}>
        <span className={lbl}>Call Title</span>
        <input
          className={input}
          maxLength={500}
          value={title}
          onChange={(e) => onTitle(e.target.value)}
          aria-label="Call Title"
        />
      </label>
      <div className={wrap} role="group" aria-label="Call duration">
        <span className={lbl}>Call duration</span>
        <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          <input
            type="number"
            min={0}
            max={1440}
            className={input}
            style={{ width: 72 }}
            aria-label="Minutes"
            value={minutes}
            onChange={(e) => onMinutes(e.target.value)}
          />
          <span>min</span>
          <input
            type="number"
            min={0}
            max={59}
            className={input}
            style={{ width: 72 }}
            aria-label="Seconds"
            value={seconds}
            onChange={(e) => onSeconds(e.target.value)}
          />
          <span>sec</span>
        </span>
      </div>
    </>
  );
}

/**
 * Log a call in the centered activity popup (POST /activities/calls).
 */
export function LogCallDrawer({
  open,
  onClose,
  link,
  recordName,
  recordSecondary,
  initialAssociations,
  outcomes,
  timeZone,
  onLogged,
  composer,
  snippetContactId,
  dial = null,
  callFields = false,
}: {
  open: boolean;
  onClose: () => void;
  link: ActivityLink;
  recordName: string;
  recordSecondary?: string | null;
  initialAssociations?: AssocRecord[];
  outcomes: PicklistOption[];
  timeZone: string;
  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;
  /**
   * Opened from the record's quick "Call": who to ring and their number, above the same form, so
   * the notes (with snippets: call scripts) are there during the call (go-live QA). Calling from
   * the CRM is not part of go-live, so the number is a tel: link for the rep's own phone.
   */
  dial?: { name: string; phone: string | null } | null;
  /**
   * CGL6 (go-live QA #6, beyond the design, whose Log Call has neither): Call Title and Call
   * duration, as the Calls page's Log call. Contacts and Companies pass it; other records don't.
   */
  callFields?: boolean;
}) {
  const toast = useToast();
  const prefs = useUserPrefs();
  const tz = timeZone || prefs.timeZone;
  const [bodyHtml, setBodyHtml] = useState('');
  const [busy, setBusy] = useState(false);
  const [saved, setSaved] = useState(false);
  const [direction, setDirection] = useState<CallDirection | ''>('');
  const [callType, setCallType] = useState<CallType | ''>('');
  const [outcome, setOutcome] = useState('');
  const [occurredAt, setOccurredAt] = useState(() => toLocalInput(new Date(), tz));
  const [followUp, setFollowUp] = useState(false);
  const [followDue, setFollowDue] = useState<FollowUpDueKey>('biz3');
  const [customDueDate, setCustomDueDate] = useState('');
  const [taskType, setTaskType] = useState('todo');
  const [title, setTitle] = useState('');
  const [minutes, setMinutes] = useState('');
  const [seconds, setSeconds] = useState('');
  const primary: AssocRecord = useMemo(
    () => ({
      type: link.type,
      id: link.id,
      displayName: recordName,
      subtitle: recordSecondary ?? null,
    }),
    [link.type, link.id, recordName, recordSecondary],
  );
  const seedAssoc = useMemo(
    () => seedAssociations(primary, initialAssociations).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);
    // A call the rep is making is outbound.
    setDirection(dial ? 'outbound' : '');
    setCallType('');
    setOutcome('');
    setOccurredAt(toLocalInput(new Date(), tz));
    setFollowUp(false);
    setFollowDue('biz3');
    setCustomDueDate('');
    setTaskType('todo');
    setTitle('');
    setMinutes('');
    setSeconds('');
    setAssoc(seedAssoc);
    setAssocOpen(false);
  });

  const empty = useMemo(() => htmlIsEmpty(bodyHtml), [bodyHtml]);
  const contacted =
    assoc.length > 1
      ? assoc.map((a) => a.displayName).join(', ')
      : (!composer && recordSecondary?.trim()) || recordName;
  // QA D-11: the Contacts composer needs only a note, as the design; the popup keeps the direction.
  const canSubmit = canLogCall({ empty, busy, direction, directionOptional: Boolean(composer) });

  const submit = async () => {
    if (!canSubmit) return;
    const when = fromLocalInput(occurredAt, tz);
    if (!when) {
      toast('Enter when the call 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 createCall(
          logCallBody({
            ...(callFields && {
              title,
              durationSeconds: callDurationSeconds(minutes, seconds),
            }),
            direction,
            callType,
            outcome,
            bodyHtml,
            occurredAt: when,
            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, tz, customDueDate),
            links: taskSafe,
          });
        } catch (taskErr) {
          toast(`Call logged, follow-up task failed: ${actionErrorText(taskErr)}`, 'danger', {
            durationMs: 8000,
          });
          onLogged();
          onClose();
          return;
        }
      }
      toast(followUp ? 'Call logged with follow-up task' : 'Call logged');
      onLogged();
      onClose();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  return (
    <DraggablePopup
      composer={composer}
      id={`${link.type}CallModal`}
      open={open}
      onClose={onClose}
      confirmClose={!empty && !saved}
      title={dial ? 'Call' : 'Log Call'}
      size="md"
      footer={
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          disabled={!canSubmit}
          aria-busy={busy}
          onClick={() => void submit()}
        >
          Log call
        </button>
      }
    >
      {dial ? <CallNumber name={dial.name} phone={dial.phone?.trim() ?? ''} /> : null}
      {composer ? (
        <div className="acx-fields">
          <div className="acx-field">
            <span className="acx-field__label">Contacted</span>
            <AssocForPill
              ref={forPillRef}
              wrap={false}
              composer
              label={contacted}
              expanded={assocOpen}
              onClick={() => setAssocOpen((o) => !o)}
            />
          </div>
          <div className="acx-field">
            <span className="acx-field__label">Call outcome</span>
            <ComposerSelect
              label="Call outcome"
              placeholder="Select call outcome"
              value={outcome}
              options={[
                { value: '', label: 'Select call outcome' },
                ...outcomes.map((o) => ({ value: o.value, label: o.label })),
              ]}
              onChange={setOutcome}
              search
            />
          </div>
          <div className="acx-field">
            <span className="acx-field__label">Call type</span>
            <ComposerSelect
              label="Call type"
              placeholder="Select call type"
              value={callType}
              // The design's six only, no "clear" row (`activity-composer.js:1200`, `:305-310`).
              options={CALL_TYPE_OPTIONS}
              onChange={(next) => setCallType(isCallType(next) ? next : '')}
              search
            />
          </div>
          <div className="acx-field">
            <span className="acx-field__label">Call direction</span>
            <ComposerSelect
              label="Call direction"
              placeholder="Select call direction"
              value={direction}
              options={DIRECTIONS}
              onChange={(next) =>
                setDirection(next === 'inbound' || next === 'outbound' ? next : '')
              }
            />
          </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(tz)}</span>
            </label>
          </div>
          {callFields ? (
            <CallTitleDurationFields
              composer
              title={title}
              onTitle={setTitle}
              minutes={minutes}
              onMinutes={setMinutes}
              seconds={seconds}
              onSeconds={setSeconds}
            />
          ) : null}
        </div>
      ) : (
        <div className="activity-popup__fields">
          <div className="field">
            <span className="field__label">Contacted</span>
            <AssocForPill
              ref={forPillRef}
              wrap={false}
              label={contacted}
              expanded={assocOpen}
              onClick={() => setAssocOpen((o) => !o)}
            />
          </div>
          <label className="field">
            <span className="field__label">Call outcome</span>
            <select
              className="input"
              value={outcome}
              onChange={(e) => setOutcome(e.target.value)}
              aria-label="Call outcome"
            >
              <option value="">Select call outcome</option>
              {outcomes.map((o) => (
                <option key={o.id} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </label>
          <label className="field">
            <span className="field__label">Call direction</span>
            <select
              className="input"
              value={direction}
              onChange={(e) => {
                const next = e.target.value;
                setDirection(next === 'inbound' || next === 'outbound' ? next : '');
              }}
              aria-label="Call direction"
              required
            >
              <option value="">Select call direction</option>
              <option value="outbound">Outbound</option>
              <option value="inbound">Inbound</option>
            </select>
          </label>
          <label className="field">
            <span className="field__label">Activity date</span>
            <span className="activity-popup__dt">
              <input
                className="input"
                type="datetime-local"
                value={occurredAt}
                onChange={(e) => setOccurredAt(e.target.value)}
                required
                aria-label="Activity date"
              />
              <span className="activity-popup__tz">{gmtLabel(tz)}</span>
            </span>
          </label>
          {callFields ? (
            <CallTitleDurationFields
              composer={false}
              title={title}
              onTitle={setTitle}
              minutes={minutes}
              onMinutes={setMinutes}
              seconds={seconds}
              onSeconds={setSeconds}
            />
          ) : null}
        </div>
      )}

      <ComposeRichText
        openKey={openCount}
        value={bodyHtml}
        onChange={setBodyHtml}
        label="Call notes"
        placeholder="Start typing to log a call…"
        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={tz}
        composer={Boolean(composer)}
      />
    </DraggablePopup>
  );
}
