'use client';

import { Field, FormDrawer } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import {
  COMMUNICATION_CHANNELS,
  createCommunication,
  type ActivityLink,
  type CommunicationChannel,
} from '@/features/activities/api.client';
import {
  actionErrorText,
  fromLocalInput,
  TEXTAREA_STYLE,
  toLocalInput,
  useOpenCount,
} from './shared';
import { SnippetTextarea } from '@/features/snippets/ui/SnippetTextarea';
import { snippetTargetFor } from '@/features/snippets/model';

/**
 * Log an SMS, WhatsApp or LinkedIn message linked to a contact, company or deal
 * (POST /activities/communications, HUB-327).
 */
export function LogCommunicationDrawer({
  open,
  onClose,
  link,
  snippetContactId,
  recordName,
  timeZone,
  onLogged,
  channel = 'linkedin_message',
}: {
  open: boolean;
  onClose: () => void;
  link: ActivityLink;
  /** Who stands for the record when a snippet is filled (a company's or deal's contact). */
  snippetContactId?: string;
  recordName: string;
  timeZone: string;
  onLogged: () => void;
  /**
   * R2: the channel picked when the drawer opens: the record pages' More items "Log SMS",
   * "Log a LinkedIn message" and "Log a WhatsApp message" (record-popups-hs.js:982-984).
   * Default: LinkedIn, as before.
   */
  channel?: CommunicationChannel;
}) {
  const toast = useToast();
  const openCount = useOpenCount(open);

  const onSubmit = async (d: Record<string, string>) => {
    const body = (d.body ?? '').trim();
    if (!body) return false;
    const occurredAt = fromLocalInput(d.occurredAt ?? '', timeZone);
    if (!occurredAt) {
      toast('Enter when the message was sent or received', 'danger');
      return false;
    }
    const channel = COMMUNICATION_CHANNELS.find((c) => c.value === d.channel)?.value;
    if (!channel) {
      toast('Pick a channel', 'danger');
      return false;
    }
    try {
      await createCommunication({
        channel: channel as CommunicationChannel,
        body,
        occurredAt,
        links: [link],
      });
      toast('Communication logged');
      onLogged();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id={`${link.type}CommunicationModal`}
      title={`Log a communication with ${recordName}`}
      size="wide"
      submitLabel="Log communication"
      open={open}
      onClose={onClose}
      onSubmit={onSubmit}
    >
      <div className="form-grid" key={openCount}>
        <Field label="Channel" htmlFor="communicationChannel">
          <select className="input" id="communicationChannel" name="channel" defaultValue={channel}>
            {COMMUNICATION_CHANNELS.map((c) => (
              <option key={c.value} value={c.value}>
                {c.label}
              </option>
            ))}
          </select>
        </Field>
        <Field label="Date and time" htmlFor="communicationAt">
          <input
            className="input"
            id="communicationAt"
            type="datetime-local"
            name="occurredAt"
            required
            defaultValue={toLocalInput(new Date(), timeZone)}
          />
        </Field>
        <Field
          label="Message"
          htmlFor="communicationBody"
          className="span-2"
          error="Write the message first."
        >
          <SnippetTextarea
            className="input"
            id="communicationBody"
            name="body"
            rows={6}
            required
            maxLength={50_000}
            style={TEXTAREA_STYLE}
            placeholder="What was said?"
            snippetTarget={snippetTargetFor(link, snippetContactId)}
          />
        </Field>
      </div>
      <p className="crm-fs-8 crm-text-muted crm-mt-3">Times are in {timeZone}.</p>
    </FormDrawer>
  );
}
