'use client';

/**
 * "Log a call" into a team inbox (HUB-366). The CRM has no phone system connected, so a call
 * arrives when someone writes it down: it is saved as a call on the contact and as a
 * conversation in the inbox.
 */
import { useEffect, useRef, useState } from 'react';
import { Field, FormDrawer } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { listPicklist, type PicklistOption } from '@/features/picklists/api.client';
import { errorText } from '@/lib/api/errors';
import { findContactByEmail, logInboxCall, searchContacts } from '../api.client';
import { SnippetTextarea } from '@/features/snippets/ui/SnippetTextarea';

export function InboxCallDrawer({
  inboxId,
  inboxName,
  contactEmail,
  onClose,
  onLogged,
}: {
  inboxId: string;
  inboxName: string;
  /** The open conversation's contact, to start with. */
  contactEmail: string;
  onClose: () => void;
  onLogged: (threadId: string) => void;
}) {
  const toast = useToast();
  const [outcomes, setOutcomes] = useState<PicklistOption[]>([]);
  const [matches, setMatches] = useState<{ email: string; label: string }[]>([]);
  const searchTimer = useRef<number | undefined>(undefined);

  useEffect(() => {
    listPicklist('activity', 'callOutcome').then(setOutcomes, () => {});
    return () => window.clearTimeout(searchTimer.current);
  }, []);

  const search = (text: string) => {
    window.clearTimeout(searchTimer.current);
    if (text.trim().length < 2) return;
    searchTimer.current = window.setTimeout(() => {
      searchContacts(text.trim()).then(
        (found) =>
          setMatches(
            found.contacts.flatMap((c) =>
              c.email
                ? [
                    {
                      email: c.email,
                      label: [c.displayName, c.companyName].filter(Boolean).join(' · '),
                    },
                  ]
                : [],
            ),
          ),
        () => {},
      );
    }, 250);
  };

  const submit = async (d: Record<string, string>) => {
    try {
      const contact = await findContactByEmail((d.contact ?? '').trim());
      if (!contact) {
        toast('Choose a contact by their email address', 'danger');
        return false;
      }
      const minutes = Number(d.minutes);
      const { threadId } = await logInboxCall(inboxId, {
        contactId: contact.id,
        direction: d.direction === 'outbound' ? 'outbound' : 'inbound',
        notes: (d.notes ?? '').trim(),
        ...(d.outcome ? { outcome: d.outcome } : {}),
        ...(d.minutes && minutes > 0 ? { durationSeconds: Math.round(minutes * 60) } : {}),
      });
      toast('Call logged');
      onLogged(threadId);
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };

  return (
    <FormDrawer
      id="inboxCallModal"
      title={`Log a call in ${inboxName}`}
      submitLabel="Log call"
      open
      onClose={onClose}
      onSubmit={submit}
    >
      <div className="form-grid">
        <Field label="Contact's email" htmlFor="callContact" className="span-2">
          <input
            className="input"
            id="callContact"
            name="contact"
            type="email"
            required
            list="callContactList"
            placeholder="Type a name or email address"
            autoComplete="off"
            defaultValue={contactEmail}
            onChange={(e) => search(e.target.value)}
          />
          <datalist id="callContactList">
            {matches.map((m) => (
              <option key={m.email} value={m.email}>
                {m.label}
              </option>
            ))}
          </datalist>
        </Field>
        <Field label="Direction" htmlFor="callDirection">
          <select className="input" id="callDirection" name="direction" defaultValue="inbound">
            <option value="inbound">They called us</option>
            <option value="outbound">We called them</option>
          </select>
        </Field>
        <Field label="Outcome" htmlFor="callOutcome">
          <select className="input" id="callOutcome" name="outcome" defaultValue="">
            <option value="">Not set</option>
            {outcomes.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
        </Field>
        <Field label="Minutes" htmlFor="callMinutes">
          <input
            className="input"
            id="callMinutes"
            name="minutes"
            type="number"
            min={0}
            max={1440}
          />
        </Field>
        <Field label="What was said" htmlFor="callNotes" className="span-2">
          <SnippetTextarea
            className="input"
            id="callNotes"
            name="notes"
            rows={5}
            required
            maxLength={5000}
          />
        </Field>
      </div>
    </FormDrawer>
  );
}
