import type { ReactNode } from 'react';
import { channelLabel } from '@/features/activities/api.client';
import { callTypeLabel } from '@/features/activities/callTypes';
import type { TimelineItem } from '@/features/contacts/types';
import type { DescribeField } from '@/features/property-history/describe';
import type { RegionFormat } from '@/features/settings/types';
import { decodeEntities, htmlToPlain } from '@/lib/utils/safe-html';

// HUB-618: the record timeline in plain words, as HubSpot's: "Lifecycle stage changed from Lead
// to Sales Qualified Lead", "Nancy Kelly had a 22 minute call with Greg. Outcome: Connected",
// tasks with their due date in the user's date format. No internal field names, no raw JSON,
// no HTML entities.

/**
 * Field changes worth a line in the main feed (the rest are in History / property history):
 * owner, lifecycle stage, lead status, deal stage, email and name.
 */
export const MEANINGFUL_FIELDS = new Set([
  'ownerId',
  'lifecycleStage',
  'leadStatus',
  'stageId',
  'pipelineId',
  'email',
  'firstName',
  'lastName',
  'name',
  'amount',
  'closeDate',
]);

const LOCALES: Record<RegionFormat, string> = {
  us: 'en-US',
  uk: 'en-GB',
  in: 'en-IN',
  de: 'de-DE',
};

/** The user's date format and time zone (profile preferences), for `formatUserDate`. */
export type DatePrefs = { region: RegionFormat; timeZone: string };

/** QA #352/#368: HubSpot's blank value ("--"), the same on every record page. */
export const BLANK = '--';

/** M-02: Log meeting has no title field; HubSpot shows such a meeting as "Logged meeting" (MT-0). */
export const LOGGED_MEETING_TITLE = 'Logged meeting';

/**
 * A date (and time) in the user's date format and time zone. QA #352/#368: the one date
 * formatter of the record pages (contact, company, deal, custom objects). A date-only value
 * ("2026-11-03", e.g. a deal's close date) stays on its day in every time zone.
 */
export function formatUserDate(
  iso: string | null | undefined,
  opts: DatePrefs & { time?: boolean },
): string {
  if (!iso) return BLANK;
  const dateOnly = /^\d{4}-\d{2}-\d{2}$/.test(iso);
  const date = dateOnly ? new Date(`${iso}T12:00:00Z`) : new Date(iso);
  if (Number.isNaN(date.getTime())) return iso;
  try {
    return new Intl.DateTimeFormat(LOCALES[opts.region] ?? undefined, {
      dateStyle: 'medium',
      ...(opts.time && !dateOnly ? { timeStyle: 'short' } : {}),
      timeZone: dateOnly ? 'UTC' : opts.timeZone,
    }).format(date);
  } catch {
    return iso.slice(0, 10);
  }
}

/** A timeline month heading ("November 2026") in the user's region format and time zone. */
export function formatUserMonthYear(iso: string, opts: DatePrefs): string {
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return iso.slice(0, 7);
  try {
    return new Intl.DateTimeFormat(LOCALES[opts.region] ?? undefined, {
      month: 'long',
      year: 'numeric',
      timeZone: opts.timeZone,
    }).format(date);
  } catch {
    return iso.slice(0, 7);
  }
}

/** B7: a time of day ("3:30 PM") in the user's region format and time zone. */
export function formatUserTime(iso: string, opts: DatePrefs): string {
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return iso;
  try {
    return new Intl.DateTimeFormat(LOCALES[opts.region] ?? undefined, {
      timeStyle: 'short',
      timeZone: opts.timeZone,
    }).format(date);
  } catch {
    return iso.slice(11, 16);
  }
}

export interface ReadableContext {
  /** The record's own name ("Greg Tedesco"), for "had a call with ...". */
  recordName: string;
  /** Field labels and value texts (property history's describer). */
  describe: DescribeField;
  region: RegionFormat;
  timeZone: string;
  /** "Contact" / "Company" / "Deal": "Contact created". */
  objectLabel: string;
}

export interface ReadableItem {
  /** The card's title ("Call", "Email sent", "Lifecycle stage changed"). */
  title: string;
  /** The sentence under it. */
  sentence: ReactNode | null;
  /** Small facts (due date, outcome, status). */
  meta: string[];
  /** The longer text (note, email body, call notes), shown when the card is expanded. */
  body: string | null;
}

const str = (value: unknown): string | null => (typeof value === 'string' && value ? value : null);
/** The `name` of a `{ id, name }` reference (a deal's stages in its timeline). */
const named = (value: unknown): string | null =>
  value && typeof value === 'object' ? str((value as { name?: unknown }).name) : null;
/** A stored key in words: `left_voicemail` → "Left voicemail" (call outcomes, statuses). */
export const words = (value: string | null) =>
  value ? value.replace(/[_-]+/g, ' ').replace(/^./, (c) => c.toUpperCase()) : null;
/** Why a workflow enrollment ended (`endReason`), in words. */
const ENROLLMENT_ENDS: Record<string, string> = {
  completed: 'Completed',
  unenrolled: 'Unenrolled',
  no_longer_matching: 'Unenrolled: no longer met the trigger',
  workflow_turned_off: 'Ended: the workflow was turned off',
  record_deleted: 'Ended: the record was deleted',
  failed: 'Failed',
  loop_guard: 'Stopped: automation loop',
};
/** How a workflow enrollment went, in words: "In progress", "Completed", "Failed"... */
export function enrollmentOutcome(item: TimelineItem): string | null {
  const ended = str(item.endReason);
  if (item.status === 'running' || item.status === 'waiting') return 'In progress';
  return ended ? (ENROLLMENT_ENDS[ended] ?? words(ended)) : words(str(item.status));
}
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const actorOf = (item: TimelineItem): string | null =>
  item.actor && typeof item.actor === 'object' && 'name' in item.actor
    ? String((item.actor as { name: string }).name)
    : null;
/**
 * QA D-12: the named contacts a logged activity was with (the timeline's `contacts`, sent for
 * `?contacts=true`), as the design's "logged … with <contacts>" (`activity-composer.js:1653`).
 * A contact without a name (its email hidden from the viewer) is left out.
 */
const contactNames = (item: TimelineItem): string[] =>
  Array.isArray(item.contacts)
    ? item.contacts.flatMap((contact: unknown) => {
        const name =
          contact && typeof contact === 'object' ? (contact as { name?: unknown }).name : null;
        return typeof name === 'string' && name ? [name] : [];
      })
    : [];
/** Who a logged activity was with: its named contacts, else the record (as before D-12). */
const withWhom = (item: TimelineItem, ctx: ReadableContext): string => {
  const names = contactNames(item);
  return names.length ? names.join(', ') : ctx.recordName;
};
/** A manually logged email (POST /activities/emails): an activity, not a mailbox message. */
const isLoggedEmail = (item: TimelineItem): boolean =>
  Boolean(str(item.activityId)) && !str(item.messageId);

/** The item in plain words. */
export function readable(item: TimelineItem, ctx: ReadableContext): ReadableItem {
  const actor = actorOf(item);
  const who = actor ?? 'Someone';
  const date = (iso: unknown, time = true) =>
    formatUserDate(str(iso), { region: ctx.region, timeZone: ctx.timeZone, time });
  switch (item.type) {
    case 'note': {
      const text = typeof item.bodyHtml === 'string' ? htmlToPlain(item.bodyHtml) : '';
      return {
        title: 'Note',
        sentence: (
          <>
            <strong>{who}</strong> left a note
            {text ? `: ${text.length > 140 ? `${text.slice(0, 140)}…` : text}` : '.'}
          </>
        ),
        meta: [],
        body: text.length > 140 ? text : null,
      };
    }
    case 'call': {
      const seconds = typeof item.durationSeconds === 'number' ? item.durationSeconds : null;
      const minutes = seconds !== null ? Math.max(1, Math.round(seconds / 60)) : null;
      const outcome = words(str(item.outcome));
      // QA D-11: after the outcome, as the design's meta (`activity-composer.js:1214-1215`).
      const callType = callTypeLabel(str(item.callType));
      const direction = str(item.direction);
      const notes = str(item.notes) ? htmlToPlain(str(item.notes)!) : null;
      return {
        title: direction === 'inbound' ? 'Inbound call' : 'Call',
        sentence: (
          <>
            <strong>{who}</strong> had {minutes ? `a ${minutes} minute call` : 'a call'} with{' '}
            {withWhom(item, ctx)}.{outcome ? ' Outcome: ' : ''}
            {outcome ? <strong>{outcome}</strong> : null}
            {outcome ? '.' : ''}
            {callType ? ' Type: ' : ''}
            {callType ? <strong>{callType}</strong> : null}
            {callType ? '.' : ''}
          </>
        ),
        meta: [],
        body: notes,
      };
    }
    case 'email': {
      const subject = str(item.subject) ? decodeEntities(str(item.subject)!) : '(No subject)';
      const direction = str(item.direction);
      const text =
        typeof item.bodyHtml === 'string' && item.bodyHtml
          ? htmlToPlain(item.bodyHtml)
          : str(item.snippet)
            ? decodeEntities(str(item.snippet)!)
            : null;
      // QA D-12: logged by hand, not sent (activity-composer.js:1104-1105).
      if (isLoggedEmail(item)) {
        return {
          title: 'Logged email',
          sentence: (
            <>
              <strong>{who}</strong> logged an email with {withWhom(item, ctx)}.
            </>
          ),
          meta: [],
          body: text,
        };
      }
      return {
        title: direction === 'inbound' ? 'Email received' : 'Email sent',
        sentence:
          direction === 'inbound' ? (
            <>
              {ctx.recordName} sent the email <strong>{subject}</strong>
              {actor ? ` to ${actor}` : ''}.
            </>
          ) : (
            <>
              <strong>{who}</strong> sent the email <strong>{subject}</strong> to {ctx.recordName}.
            </>
          ),
        meta: [],
        body: text,
      };
    }
    case 'meeting': {
      // MT-7: an untitled logged meeting is stored as "Logged meeting"; read it as "logged a meeting".
      const stored = str(item.title);
      const untitled = !stored || stored === LOGGED_MEETING_TITLE;
      const title = untitled ? 'a meeting' : stored;
      const cancelled = item.status === 'cancelled';
      const verb = cancelled ? 'cancelled' : item.origin === 'logged' ? 'logged' : 'scheduled';
      // QA D-12: a logged meeting is with its contacts; others keep the record.
      const contacts = item.origin === 'logged' ? contactNames(item) : [];
      const whom = contacts.length ? contacts : [ctx.recordName];
      // Whole words only, so contact "Al" is still named in "Final review".
      const inTitle = (name: string) =>
        Boolean(name) &&
        new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(name)}(?![\\p{L}\\p{N}])`, 'iu').test(title);
      // The default title ("Meeting with Acme", ScheduleMeetingDrawer) already names the record,
      // or a typed one every contact: no second "with …".
      const named = inTitle(ctx.recordName) || whom.every(inTitle);
      const notes = str(item.body) ? htmlToPlain(str(item.body)!) : null;
      const description = str(item.description);
      return {
        title: cancelled ? 'Meeting cancelled' : 'Meeting',
        sentence: (
          <>
            <strong>{who}</strong> {verb} {untitled ? title : <strong>{title}</strong>}
            {named ? '' : ` with ${whom.join(', ')}`}
            {str(item.startsAt) ? ` on ${date(item.startsAt)}` : ''}.
          </>
        ),
        // The outcome first, as the card's badge; notes (else the invitation text) when expanded.
        meta: [words(str(item.outcome)), str(item.location), str(item.meetingUrl)].filter(
          (x): x is string => Boolean(x),
        ),
        body: notes ?? description,
      };
    }
    case 'task': {
      const title = str(item.title) ?? 'a task';
      const done = item.status === 'completed';
      const due = str(item.dueAt) ?? str(item.dueDate);
      const assignee =
        item.assignee && typeof item.assignee === 'object'
          ? String((item.assignee as { name: string }).name)
          : null;
      return {
        title: done ? 'Task completed' : 'Task',
        sentence: (
          <>
            <strong>{who}</strong> created the task <strong>{title}</strong>
            {assignee && assignee !== actor ? ` for ${assignee}` : ''}.
          </>
        ),
        meta: [
          done ? 'Completed' : 'Open',
          due ? `Due ${date(due, Boolean(str(item.dueAt)))}` : '',
          words(str(item.taskType)) ?? '',
        ].filter(Boolean),
        body: null,
      };
    }
    case 'communication': {
      const channel = channelLabel(item.channel);
      return {
        title: `${channel} message`,
        sentence: (
          <>
            <strong>{who}</strong> logged a {channel} message with {withWhom(item, ctx)}.
          </>
        ),
        meta: [],
        body: str(item.body),
      };
    }
    case 'postal_mail':
      return {
        title: 'Postal mail',
        sentence: (
          <>
            <strong>{who}</strong> logged postal mail to {withWhom(item, ctx)}.
          </>
        ),
        meta: [],
        body: str(item.body),
      };
    case 'field_change': {
      const field = String(item.field ?? '');
      const info = ctx.describe(field);
      // HUB-620: a field the page has no definition for (an archived or HubSpot system field)
      // would show its key ("custom.hs_user_ids_…") and raw ids: the API's labels read better.
      const known = info.label !== field && info.label !== field.replace(/^custom\./, '');
      const label = known ? info.label : (str(item.fieldLabel) ?? info.label);
      const from = known ? info.text(item.from) : (str(item.fromLabel) ?? info.text(item.from));
      const to = known ? info.text(item.to) : (str(item.toLabel) ?? info.text(item.to));
      const empty = (v: string) => !v || v === '--';
      return {
        title: `${label} changed`,
        sentence: (
          <>
            {label}{' '}
            {empty(from) ? (
              <>
                set to <strong>{to}</strong>
              </>
            ) : empty(to) ? (
              <>
                cleared (was <strong>{from}</strong>)
              </>
            ) : (
              <>
                changed from <strong>{from}</strong> to <strong>{to}</strong>
              </>
            )}
            {actor ? ` by ${actor}` : ''}.
          </>
        ),
        meta: [],
        body: null,
      };
    }
    case 'stage_change': {
      // QA #367: a deal's stages come as `{ id, name }`.
      const from = str(item.fromStage) ?? named(item.fromStage);
      const to = str(item.toStage) ?? named(item.toStage) ?? str(item.stageName);
      return {
        title: 'Stage changed',
        sentence: (
          <>
            {actor ? <strong>{actor}</strong> : 'The record'} moved {ctx.recordName || 'it'}
            {from ? (
              <>
                {' '}
                from <strong>{from}</strong>
              </>
            ) : null}{' '}
            to <strong>{to ?? 'a new stage'}</strong>.
          </>
        ),
        meta: [],
        body: null,
      };
    }
    case 'workflow_enrollment': {
      // HUB-243 (QA #605): enrolled in a workflow, and how it went. Null `workflow`: the viewer
      // may not see workflows.
      const workflow = named(item.workflow);
      const outcome = enrollmentOutcome(item);
      return {
        title: 'Workflow enrollment',
        sentence: (
          <>
            {actor ? `${actor} enrolled` : 'Enrolled'} {ctx.recordName || 'this record'} in{' '}
            {workflow ? <strong>{workflow}</strong> : 'a workflow'}.
          </>
        ),
        meta: [outcome].filter((m): m is string => Boolean(m)),
        body: null,
      };
    }
    case 'merged': {
      // CB8 (CT-05, HubSpot): a record merged into this one; its email (contacts) or domain
      // (companies) is kept here as additional. `value` is null when hidden from the viewer.
      const merged = (item.merged ?? null) as { name?: unknown; value?: unknown } | null;
      const name = str(merged?.name) ?? `a ${ctx.objectLabel.toLowerCase()}`;
      const value = str(merged?.value);
      return {
        title: `${ctx.objectLabel} merged`,
        sentence: (
          <>
            {actor ? `${actor} merged` : 'Merged'} <strong>{name}</strong>
            {value ? ` (${value})` : ''} into {ctx.recordName || 'this record'}.
          </>
        ),
        meta: [],
        body: null,
      };
    }
    case 'created':
      return {
        title: `${ctx.objectLabel} created`,
        sentence: (
          <>
            This {ctx.objectLabel.toLowerCase()} was created
            {actor ? ` by ${actor}` : ''}.
          </>
        ),
        meta: [],
        body: null,
      };
    default:
      return {
        title: words(String(item.type)) ?? 'Activity',
        sentence: null,
        meta: [],
        body: null,
      };
  }
}
