'use client';

import { useEffect, useId, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { htmlIsEmpty } from '@/components/crm/ComposeRichText';
import { RichNotes } from '@/components/crm/RichNotes';
import { useToast } from '@/components/crm/ToastProvider';
import { createCall, type CallDirection, type CallType } from '@/features/activities/api.client';
import { CALL_TYPE_OPTIONS } from '@/features/activities/callTypes';
import { fromLocalInput, toLocalInput } from '@/features/contacts/ui/actions/shared';
import { callDurationSeconds, logCallBody } from '@/features/contacts/ui/actions/logCall';
import { LpModal } from '@/features/list-page/ui/LpModal';
import { TaskLinksPicker } from '@/features/tasks/ui/TaskLinksPicker';
import type { TaskLink } from '@/features/tasks/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import type { QuickOption } from './CallsQuickFilters';
import { snippetTargetFromLinks } from '@/features/snippets/model';

const field = { display: 'flex', flexDirection: 'column', gap: 6 } as const;

/**
 * Log a call from the Calls page (POST /activities/calls). The design's Calls page logs calls
 * from records; this adds it to the page's ⋮ menu, with the records to associate it with.
 * CGL6 (go-live QA #4 and #6, beyond the design): the records are optional (an inbound call from
 * an unknown number), and the notes are rich text, as the record's Log Call.
 */
export function LogCallModal({
  open,
  onClose,
  outcomes,
  timeZone,
  onLogged,
}: {
  open: boolean;
  onClose: () => void;
  outcomes: QuickOption[];
  timeZone: string;
  onLogged: () => void;
}) {
  const id = useId();
  const toast = useToast();
  const [links, setLinks] = useState<TaskLink[]>([]);
  const [title, setTitle] = useState('');
  const [direction, setDirection] = useState<CallDirection | ''>('');
  const [outcome, setOutcome] = useState('');
  const [callType, setCallType] = useState<CallType | ''>('');
  const [when, setWhen] = useState('');
  const [minutes, setMinutes] = useState('');
  const [seconds, setSeconds] = useState('');
  const [notes, setNotes] = useState('');
  const [openKey, setOpenKey] = useState(0);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    setOpenKey((k) => k + 1);
    setLinks([]);
    setTitle('');
    setDirection('');
    setOutcome('');
    setCallType('');
    setWhen(toLocalInput(new Date(), timeZone));
    setMinutes('');
    setSeconds('');
    setNotes('');
    setError(null);
  }, [open, timeZone]);

  const duration = callDurationSeconds(minutes, seconds);
  const ready = !busy;

  const submit = async () => {
    if (!ready) return;
    const occurredAt = fromLocalInput(when, timeZone);
    if (!occurredAt) {
      setError('Enter the activity date');
      return;
    }
    setBusy(true);
    setError(null);
    try {
      await createCall(
        logCallBody({
          title,
          direction,
          callType,
          outcome,
          durationSeconds: duration,
          bodyHtml: htmlIsEmpty(notes) ? '' : notes,
          occurredAt,
          links: links.map((l) => ({ type: l.objectType, id: l.id })),
        }),
      );
      toast('Call logged');
      onLogged();
      onClose();
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <LpModal
      open={open}
      title="Log call"
      onClose={() => {
        if (!busy) onClose();
      }}
      className="lp-modal--wide"
      footer={
        <div className="lp-modal__acts lp-modal__acts--start">
          <button
            type="button"
            className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
            disabled={!ready}
            onClick={() => void submit()}
          >
            Log call
          </button>
          <button
            type="button"
            className="lp-btn lp-btn--outline"
            disabled={busy}
            onClick={onClose}
          >
            Cancel
          </button>
        </div>
      }
    >
      {error ? <Alert tone="danger">{error}</Alert> : null}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="lp-field">
          <label htmlFor={`${id}-links`}>Associated with</label>
          <TaskLinksPicker id={`${id}-links`} value={links} onChange={setLinks} disabled={busy} />
        </div>
        <div className="lp-field">
          <label htmlFor={`${id}-title`}>Call Title</label>
          <input
            id={`${id}-title`}
            className="lp-input"
            maxLength={500}
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 12 }}>
          <div style={field}>
            <label className="crm-fw-semibold crm-fs-8" htmlFor={`${id}-dir`}>
              Call direction
            </label>
            <select
              id={`${id}-dir`}
              className="lp-input"
              value={direction}
              onChange={(e) => setDirection(e.target.value as CallDirection | '')}
            >
              <option value="">Select call direction</option>
              <option value="inbound">Inbound</option>
              <option value="outbound">Outbound</option>
            </select>
          </div>
          <div style={field}>
            <label className="crm-fw-semibold crm-fs-8" htmlFor={`${id}-out`}>
              Call outcome
            </label>
            <select
              id={`${id}-out`}
              className="lp-input"
              value={outcome}
              onChange={(e) => setOutcome(e.target.value)}
            >
              <option value="">Select an outcome</option>
              {outcomes.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </div>
          <div style={field}>
            <label className="crm-fw-semibold crm-fs-8" htmlFor={`${id}-type`}>
              Call type
            </label>
            <select
              id={`${id}-type`}
              className="lp-input"
              value={callType}
              onChange={(e) => setCallType(e.target.value as CallType | '')}
            >
              <option value="">Select a call type</option>
              {CALL_TYPE_OPTIONS.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </div>
          <div style={field}>
            <label className="crm-fw-semibold crm-fs-8" htmlFor={`${id}-when`}>
              Activity date
            </label>
            <input
              id={`${id}-when`}
              type="datetime-local"
              className="lp-input"
              value={when}
              onChange={(e) => setWhen(e.target.value)}
            />
          </div>
        </div>
        <fieldset className="lp-field">
          <legend>Call duration</legend>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <input
              type="number"
              min={0}
              max={1440}
              className="lp-input lp-input--num"
              style={{ width: 90 }}
              aria-label="Minutes"
              value={minutes}
              onChange={(e) => setMinutes(e.target.value)}
            />
            <span className="crm-text-muted crm-fs-8">min</span>
            <input
              type="number"
              min={0}
              max={59}
              className="lp-input lp-input--num"
              style={{ width: 90 }}
              aria-label="Seconds"
              value={seconds}
              onChange={(e) => setSeconds(e.target.value)}
            />
            <span className="crm-text-muted crm-fs-8">sec</span>
          </div>
        </fieldset>
        <div className="lp-field">
          <span>Call notes</span>
          <RichNotes
            openKey={openKey}
            value={notes}
            onChange={setNotes}
            label="Call notes"
            placeholder="Call notes"
            minHeight={120}
            snippetTarget={snippetTargetFromLinks(links)}
          />
        </div>
      </div>
    </LpModal>
  );
}
