'use client';

/**
 * "Create ticket" from a conversation (inbox-hs.js createTicket / OBJ.tickets): the Tickets
 * object's create drawer, started with the conversation's subject as the ticket name, its latest
 * received email as the description, Email as the source, and its contact (and the contact's
 * company) to link to. The new ticket then gets the conversation's emails on its timeline, and
 * shows in the sidebar as "This conversation". Mounted only when opened: the object's fields and
 * pipelines load then.
 */
import { useEffect, useMemo } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  CreateRecordDrawer,
  type CreateRecordPrefill,
} from '@/features/objects/ui/CreateRecordDrawer';
import { useObjectSchema } from '@/features/objects/useObjectSchema';
import { errorText } from '@/lib/api/errors';
import { linkThread } from '../api.client';
import { ticketPrefill } from '../conversation';
import { htmlToText } from '../format';
import type { ContactDetail, InboxMessage, InboxThreadDetail } from '../types';

const TICKET = 'ticket';

const textOf = (m: InboxMessage) =>
  m.bodyText ?? (m.bodyHtmlSafe ? htmlToText(m.bodyHtmlSafe) : '');

export function InboxTicketDrawer({
  thread,
  contact,
  timeZone,
  onClose,
  onCreated,
}: {
  thread: InboxThreadDetail;
  contact: ContactDetail | null;
  timeZone: string;
  onClose: () => void;
  onCreated: () => void;
}) {
  const toast = useToast();
  const state = useObjectSchema(TICKET);

  useEffect(() => {
    if (state.status === 'missing') {
      toast('This business has no Tickets object yet', 'danger');
      onClose();
    } else if (state.status === 'error') {
      toast(state.error, 'danger');
      onClose();
    }
  }, [state, toast, onClose]);

  const prefill = useMemo<CreateRecordPrefill>(() => {
    const values = ticketPrefill(thread, textOf);
    const name = contact
      ? [contact.firstName, contact.lastName].filter(Boolean).join(' ') ||
        contact.email ||
        'Contact'
      : '';
    const company = contact?.companies[0];
    return {
      values,
      contact: contact
        ? { id: contact.id, type: 'contact', title: name, subtitle: contact.email }
        : null,
      company: company
        ? { id: company.id, type: 'company', title: company.name, subtitle: null }
        : null,
    };
  }, [thread, contact]);

  if (state.status !== 'ready') return null;
  return (
    <CreateRecordDrawer
      open
      onClose={onClose}
      schema={state.schema}
      timeZone={timeZone}
      prefill={prefill}
      onCreated={(record, warning) => {
        void (async () => {
          let linkWarning: string | null = null;
          try {
            await linkThread(thread.id, { type: TICKET, id: record.id });
          } catch (err) {
            linkWarning = `Ticket created, but the conversation could not be added to it: ${errorText(err)}`;
          }
          const problem = warning ?? linkWarning;
          toast(
            problem ?? `Ticket “${record.displayName || 'Ticket'}” created from this conversation`,
            problem ? 'danger' : 'success',
            { durationMs: problem ? 8000 : 4000 },
          );
          onCreated();
        })();
      }}
    />
  );
}
