'use client';

import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import type {
  EnrollmentRefusal,
  Sequence,
  SequenceProblem,
  SequenceSettings,
  SequenceStep,
  SequenceStepType,
} from '@/features/sequences/types';
import { isApiError } from '@/lib/api/errors';

export function stepTypeLabel(type: SequenceStepType): string {
  if (type === 'automated_email') return 'Automatic email';
  if (type === 'manual_email') return 'Manual email';
  if (type === 'call_task') return 'Call task';
  if (type === 'task') return 'To-do task';
  return 'Wait';
}

export function stepTitle(step: SequenceStep): string {
  if (step.type === 'automated_email' || step.type === 'manual_email') {
    if (step.threadAsReply) return 'Reply in the same thread';
    return step.subject?.trim() || (step.templateId ? 'Email from a template' : 'Email step');
  }
  if (step.type === 'call_task') return step.title?.trim() || 'Call the contact';
  if (step.type === 'task') return step.title?.trim() || 'Follow-up task';
  return `Wait ${step.amount} ${step.unit.replace('_', ' ')}`;
}

export const REFUSAL_LABELS: Record<EnrollmentRefusal, string> = {
  no_access: 'You cannot see this contact.',
  no_email: 'The contact has no email address.',
  unsubscribed: 'The contact unsubscribed from emails.',
  bounced: "Emails to this contact's address bounced.",
  already_enrolled: 'The contact is already in a sequence.',
  // Sequences: HubSpot "If a user exceeds their daily send limit, the contact won't enroll".
  send_limit: "You've reached your daily send limit, so this contact won't enroll in the sequence.",
};

const FIELD_LABELS: Record<string, string> = {
  subject: 'subject',
  bodyHtml: 'email body',
  templateId: 'template',
  threadAsReply: 'reply in thread',
  taskType: 'task type',
  title: 'title',
  notes: 'notes',
  amount: 'wait',
  unit: 'wait',
  // Sequences #34: a problem in an A/B test's version B (`steps[0].variantB.subject`).
  variantB: 'version B',
};

/** The step a problem points at (`steps[2].bodyHtml` or `body.steps.2.title`), if any. */
export function problemStepIndex(field: string): number | null {
  const match = /steps(?:\[(\d+)\]|\.(\d+))/.exec(field);
  if (!match) return null;
  return Number(match[1] ?? match[2]);
}

/**
 * "Step 2 · email body" for a problem in `steps[2].bodyHtml`, numbered as the builder shows
 * when given the steps it was found in; settings and other fields as they are.
 */
export function problemLabel(field: string, steps?: SequenceStep[]): string {
  const index = problemStepIndex(field);
  if (index === null) {
    if (field === 'steps') return 'Steps';
    return field.replace(/^body\./, '');
  }
  const n = displayStepNumber(steps, index);
  const isWait = steps?.[index]?.type === 'wait';
  const rest = /steps(?:\[\d+\]|\.\d+)\.?(\w+)?/.exec(field)?.[1];
  const part = rest ? (FIELD_LABELS[rest] ?? rest) : null;
  if (isWait) return `Delay after step ${n}`;
  return part ? `Step ${n} · ${part}` : `Step ${n}`;
}

/**
 * The number the builder shows for `steps[index]`: waits are not numbered, so it counts the
 * other steps up to it (QA 14 Oct #45: "Step 3" was the array index of what shows as Step 2).
 * Without the steps, the index + 1.
 */
export function displayStepNumber(steps: SequenceStep[] | undefined, index: number): number {
  if (!steps?.length) return index + 1;
  return steps.slice(0, index + 1).filter((s) => s.type !== 'wait').length || 1;
}

/** The `{ field, message }` list of a 400 (request validation). */
export function problemsFromError(err: unknown): SequenceProblem[] | null {
  if (!isApiError(err) || err.status !== 400 || !err.details?.length) return null;
  const problems = err.details.flatMap((d) => {
    if (typeof d !== 'object' || d === null) return [];
    const { field, message } = d as Record<string, unknown>;
    if (typeof field !== 'string' || typeof message !== 'string') return [];
    return [{ field, message }];
  });
  return problems.length ? problems : null;
}

/**
 * The step problems that block enrolling (D-5). `onPick` (editor) selects the step in place;
 * without it, each step problem links to the step in the editor of `sequenceId`.
 */
export function SequenceProblemsList({
  problems,
  sequenceId,
  steps,
  onPick,
}: {
  problems: SequenceProblem[];
  sequenceId: string;
  /** The steps the problems were found in (the saved ones), for the step numbers. */
  steps?: SequenceStep[];
  onPick?: (stepIndex: number) => void;
}) {
  return (
    <ul className="crm-mb-0 crm-ps-3">
      {problems.map((problem, i) => {
        const index = problemStepIndex(problem.field);
        const label = problemLabel(problem.field, steps);
        return (
          <li key={`${problem.field}-${i}`}>
            {index === null ? (
              <strong>{label}</strong>
            ) : onPick ? (
              <button type="button" className="link crm-fw-semibold" onClick={() => onPick(index)}>
                {label}
              </button>
            ) : (
              <Link className="crm-fw-semibold" href={`/sequences/${sequenceId}?tab=steps`}>
                {label}
              </Link>
            )}
            : {problem.message}
          </li>
        );
      })}
    </ul>
  );
}

/**
 * A new dynamic sequence: the default signal (2 opens or 1 click), and the automated outreach's
 * closing wait (1 business day for the contact to engage). Its first email is added in the builder.
 */
/** Sequences QA steps BUG-05: the design's send window error (inline, on Save and the API's). */
export const SEND_WINDOW_ERROR = 'The send window must end after it starts';

/** Sequences QA steps BUG-07: the Reminder time a sequence starts with (design, API default). */
export const DEFAULT_REMINDER_TIME = '08:00';

/**
 * The API's default settings (sequenceSettingsSchema), for a sequence not saved yet. Sequences QA
 * steps BUG-07: HubSpot's default send window for a new sequence, 8:00 AM to 6:00 PM.
 */
export const DEFAULT_SEQUENCE_SETTINGS: SequenceSettings = {
  sendWindow: {
    days: ['mon', 'tue', 'wed', 'thu', 'fri'],
    startTime: '08:00',
    endTime: '18:00',
    timezone: 'owner',
    skipHolidays: true,
  },
  unsubscribeLink: true,
  taskAssignment: 'sender',
  taskReminders: false,
  reminderTime: DEFAULT_REMINDER_TIME,
  unenrollOnReply: true,
  unenrollOnMeeting: true,
  unenrollCompanyOnReply: false,
  unenrollCompanyOnMeeting: false,
  dynamic: null,
};

/**
 * A sequence that exists only in the editor until its first Save (QA 16 Oct #106: nothing is
 * saved when the user leaves without saving, as in HubSpot). It has no id.
 */
export function draftSequence(
  kind: 'dynamic' | 'scratch',
  folder: string | null,
  owner: { id: string; name: string },
  /** A pre-made sequence's name and steps (IDX-07): opened in the editor, saved by its Save. */
  preset?: { name: string; steps: SequenceStep[] },
): Sequence {
  const body = kind === 'dynamic' ? dynamicBody('New Dynamic Sequence', folder) : null;
  return {
    id: '',
    name: preset?.name ?? body?.name ?? 'New Sequence',
    status: 'active',
    visibility: 'personal',
    ownerId: owner.id,
    ownerName: owner.name,
    folder,
    version: 1,
    versionId: '',
    steps: preset?.steps ?? body?.steps ?? [],
    settings: { ...DEFAULT_SEQUENCE_SETTINGS, ...(body?.settings ?? {}) },
    activeEnrollments: 0,
    totalEnrollments: 0,
    replyRate: null,
    meetingRate: null,
    canEdit: true,
    archivedAt: null,
    createdAt: '',
    updatedAt: '',
  };
}

/**
 * Message templates › Build a sequence (HUB-721): an automated email per template, a business day
 * apart. In a dynamic sequence they are the automated lane's, ahead of its first wait.
 */
export function stepsFromTemplates(
  kind: 'dynamic' | 'scratch',
  templateIds: string[],
): SequenceStep[] {
  const lane = kind === 'dynamic' ? ({ lane: 'auto' } as const) : {};
  const wait: SequenceStep = {
    type: 'wait',
    amount: DEFAULT_STEP_DELAY,
    unit: 'business_days',
    ...lane,
  };
  const steps = templateIds.slice(0, 13).flatMap((templateId, i): SequenceStep[] => [
    ...(i > 0 ? [wait] : []),
    {
      type: 'automated_email',
      templateId,
      subject: null,
      bodyHtml: null,
      threadAsReply: false,
      ...lane,
    },
  ]);
  return kind === 'dynamic' && steps.length < 25 ? [...steps, wait] : steps;
}

export function dynamicBody(name: string, folder: string | null) {
  return {
    name,
    visibility: 'personal' as const,
    folder,
    settings: { dynamic: { signalOpens: 2, signalClicks: 1 } },
    steps: [
      { type: 'wait' as const, amount: 1, unit: 'business_days' as const, lane: 'auto' as const },
    ],
  };
}

/** ⇅ when unsorted, ↑ / ↓ when sorted (design: column headers). */
export function SortGlyph({ dir }: { dir: 'asc' | 'desc' | null }) {
  return (
    <svg className="seqm-sort__icon" viewBox="0 0 24 24" width="13" height="13" aria-hidden>
      {dir === 'asc' ? (
        <path d="M12 19V5m-6 6 6-6 6 6" fill="none" stroke="currentColor" strokeWidth="2" />
      ) : dir === 'desc' ? (
        <path d="M12 5v14m-6-6 6 6 6-6" fill="none" stroke="currentColor" strokeWidth="2" />
      ) : (
        <path
          d="M8 18V6M4 10l4-4 4 4M16 6v12m-4-4 4 4 4-4"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.8"
        />
      )}
    </svg>
  );
}

/** The delay a step added after the first starts with: HubSpot's "Delay: 1 business day". */
export const DEFAULT_STEP_DELAY = 1;

/** HubSpot's longest delay between two steps. */
const MAX_STEP_DELAY = 90;

/**
 * HubSpot's "Business days ⓘ" popover for a delay chip: a number, Save and Cancel (Esc cancels).
 * The unit is not edited here, it follows the sequence's Settings. The caller positions it inside
 * a `position: relative` wrapper.
 */
export function BusinessDaysPopover({
  value,
  unit,
  max = MAX_STEP_DELAY,
  label,
  tooltip,
  onSave,
  onCancel,
}: {
  value: number;
  unit: 'business_days' | 'days';
  max?: number;
  label?: string;
  tooltip?: string;
  onSave: (n: number) => void;
  onCancel: () => void;
}) {
  const [text, setText] = useState(String(value));
  const input = useRef<HTMLInputElement>(null);
  useEffect(() => input.current?.select(), []);
  const n = Number(text);
  const valid = text.trim() !== '' && Number.isInteger(n) && n >= 1 && n <= max;
  const save = () => {
    if (valid && n !== value) onSave(n);
  };
  return (
    <div
      className="seq-bdp"
      role="dialog"
      aria-label={label ?? (unit === 'days' ? 'Days' : 'Business days')}
      onKeyDown={(e) => {
        if (e.key === 'Escape') {
          e.stopPropagation();
          onCancel();
        }
      }}
    >
      <label className="field__label" htmlFor="seqBdpInput">
        {label ?? (unit === 'days' ? 'Days' : 'Business days')}{' '}
        <span
          className="seqa-info"
          role="img"
          aria-label="About the unit"
          title={tooltip ?? 'To change to "days" update your follow-up options in settings.'}
        >
          ⓘ
        </span>
      </label>
      <input
        id="seqBdpInput"
        ref={input}
        type="number"
        className="input"
        min={1}
        max={max}
        value={text}
        aria-invalid={!valid || undefined}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            e.preventDefault();
            save();
          }
        }}
      />
      <div className="seq-bdp__actions">
        <button
          type="button"
          className="btn-crm btn-crm--primary btn-crm--sm"
          disabled={!valid || n === value}
          onClick={save}
        >
          Save
        </button>
        <button type="button" className="btn-crm btn-crm--outline btn-crm--sm" onClick={onCancel}>
          Cancel
        </button>
      </div>
    </div>
  );
}
