'use client';

import type { KeyboardEvent, ReactNode } from 'react';
import { cn } from '@/lib/utils/cn';

/** One timeline filter tab. */
export interface TimelineTab<K extends string = string> {
  key: K;
  label: string;
}

/** Compose drawer opened from a Notes / Emails / Calls / Tasks / Meetings / … tab. */
export type ActivityComposeKind =
  | 'note'
  | 'email'
  | 'call'
  | 'task'
  | 'meeting'
  // HUB-327
  | 'communication'
  | 'postal-mail';

const TAB_ADD_ACTIONS: Record<string, { kind: ActivityComposeKind; label: string }> = {
  notes: { kind: 'note', label: 'Create a note' },
  emails: { kind: 'email', label: 'Create an email' },
  calls: { kind: 'call', label: 'Log a call' },
  tasks: { kind: 'task', label: 'Create a task' },
  meetings: { kind: 'meeting', label: 'Schedule a meeting' },
  communications: { kind: 'communication', label: 'Log a communication' },
  'postal-mail': { kind: 'postal-mail', label: 'Log postal mail' },
};

/** Secondary "Log …" CTA before Create on Emails / Meetings tabs (HubSpot parity). */
const TAB_LOG_ACTIONS: Record<string, { kind: 'log-email' | 'log-meeting'; label: string }> = {
  emails: { kind: 'log-email', label: 'Log an email' },
  meetings: { kind: 'log-meeting', label: 'Log a meeting' },
};

/** Add CTA for a specific activity tab (`all` / stage-history → null). */
export function activityTabAddAction(tabKey: string) {
  return TAB_ADD_ACTIONS[tabKey] ?? null;
}

/** Log CTA for emails / meetings tabs (null on other tabs). */
export function activityTabLogAction(tabKey: string) {
  return TAB_LOG_ACTIONS[tabKey] ?? null;
}

/** Search placeholder for the active activity tab. */
export function activityTabSearchPlaceholder(tabKey: string): string {
  switch (tabKey) {
    case 'notes':
      return 'Search notes';
    case 'emails':
      return 'Search emails';
    case 'calls':
      return 'Search calls';
    case 'tasks':
      return 'Search tasks';
    case 'meetings':
      return 'Search meetings';
    case 'communications':
      return 'Search communications';
    case 'postal-mail':
      return 'Search postal mail';
    default:
      return 'Search activities';
  }
}

const TYPE_META: Record<
  string,
  {
    label: string;
    tone: 'note' | 'email' | 'call' | 'task' | 'meeting' | 'communication' | 'postal' | 'default';
  }
> = {
  note: { label: 'Note', tone: 'note' },
  email: { label: 'Email', tone: 'email' },
  call: { label: 'Call', tone: 'call' },
  task: { label: 'Task', tone: 'task' },
  meeting: { label: 'Meeting', tone: 'meeting' },
  communication: { label: 'Communication', tone: 'communication' },
  postal_mail: { label: 'Postal mail', tone: 'postal' },
};

export function activityTypeMeta(type: string) {
  return TYPE_META[type] ?? { label: type, tone: 'default' as const };
}

function NoteGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <path d="M14 2v6h6" />
      <path d="M8 13h8M8 17h5" />
    </svg>
  );
}

function EmailGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="m3 7 9 6 9-6" />
    </svg>
  );
}

function CallGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.35 1.9.67 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.32 1.85.54 2.81.67A2 2 0 0 1 22 16.92z" />
    </svg>
  );
}

function TaskGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M9 11l3 3L22 4" />
      <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
    </svg>
  );
}

function MeetingGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <rect x="3" y="4" width="18" height="18" rx="2" />
      <path d="M16 2v4M8 2v4M3 10h18" />
    </svg>
  );
}

/** A speech bubble: SMS, WhatsApp and LinkedIn messages. */
function CommunicationGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
      <path d="M8 9h8M8 13h5" />
    </svg>
  );
}

/** A letter with a stamp: postal mail. */
function PostalMailGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <rect x="2" y="5" width="20" height="14" rx="2" />
      <rect x="15" y="8" width="4" height="4" />
      <path d="M5 9h6M5 13h6M5 16h9" />
    </svg>
  );
}

function DefaultGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <circle cx="12" cy="12" r="9" />
      <path d="M12 8v4l2.5 2.5" />
    </svg>
  );
}

const TYPE_GLYPH: Record<string, () => ReactNode> = {
  note: NoteGlyph,
  email: EmailGlyph,
  call: CallGlyph,
  task: TaskGlyph,
  meeting: MeetingGlyph,
  communication: CommunicationGlyph,
  postal_mail: PostalMailGlyph,
  'postal-mail': PostalMailGlyph,
};

/** Coloured type badge used in activity list rows (design: note / email / etc.). */
export function ActivityTypeIcon({ type, className }: { type: string; className?: string }) {
  const meta = activityTypeMeta(type);
  const Glyph = TYPE_GLYPH[type] ?? DefaultGlyph;
  return (
    <span
      className={cn('crm-activity-type-icon', `crm-activity-type-icon--${meta.tone}`, className)}
      aria-hidden
    >
      <Glyph />
    </span>
  );
}

function FilterGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M4 5h16l-6 7v5l-4 2v-7L4 5z" />
    </svg>
  );
}

/** Primary / outline "Add …" control under the activity tabs (design: pill + icon). */
export function ActivityTabAddButton({
  label,
  kind,
  disabled,
  title,
  onClick,
  className,
  variant = 'outline',
}: {
  label: string;
  kind?: ActivityComposeKind;
  disabled?: boolean;
  title?: string;
  onClick: () => void;
  className?: string;
  variant?: 'primary' | 'outline';
}) {
  const Glyph = kind ? (TYPE_GLYPH[kind] ?? DefaultGlyph) : null;
  return (
    <button
      type="button"
      className={cn(
        'btn-crm btn-crm--sm crm-activity-add-btn',
        variant === 'primary' ? 'btn-crm--primary' : 'btn-crm--outline',
        className,
      )}
      disabled={disabled}
      title={title}
      onClick={onClick}
    >
      {Glyph ? (
        <span className="crm-activity-add-btn__icon" aria-hidden>
          <Glyph />
        </span>
      ) : null}
      {label}
    </button>
  );
}

/** Filters toggle matching the design (opens Sort / Date / User panel). */
export function ActivityFiltersButton({
  open,
  active,
  onClick,
}: {
  open: boolean;
  /** True when any filter differs from defaults. */
  active?: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      className={cn(
        'btn-crm btn-crm--outline btn-crm--sm crm-activity-filters-btn',
        (open || active) && 'is-active',
      )}
      aria-expanded={open}
      onClick={onClick}
    >
      <FilterGlyph />
      Filters
    </button>
  );
}

/** The activity-type tabs above a record timeline (contact and deal pages). */
export function TimelineTypeTabs<K extends string>({
  tabs,
  active,
  onChange,
  label = 'Activity types',
  className,
  keys = false,
}: {
  tabs: ReadonlyArray<TimelineTab<K>>;
  active: K;
  onChange: (key: K) => void;
  label?: string;
  className?: string;
  /**
   * R5b: Left / Right move between the tabs and select, with a roving tab index, as the 28 Oct
   * design (activity-tabs.js:358-367, :385). Opt-in: the contact and company record pages.
   */
  keys?: boolean;
}) {
  const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {
    if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
    const buttons = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>('[role=tab]'));
    const i = buttons.indexOf(document.activeElement as HTMLButtonElement);
    if (i < 0) return;
    e.preventDefault();
    const n = e.key === 'ArrowRight' ? (i + 1) % tabs.length : (i - 1 + tabs.length) % tabs.length;
    buttons[n]?.focus();
    onChange(tabs[n]!.key);
  };
  return (
    <nav
      className={cn('set-tabs crm-activity-tabs crm-px-3 crm-gap-0', className)}
      role="tablist"
      aria-label={label}
      onKeyDown={keys ? onKeyDown : undefined}
    >
      {tabs.map(({ key, label: text }) => (
        <button
          key={key}
          type="button"
          className={cn('set-tab crm-activity-tab', active === key && 'active is-active')}
          role="tab"
          aria-selected={active === key}
          tabIndex={keys ? (active === key ? 0 : -1) : undefined}
          onClick={() => onChange(key)}
        >
          {text}
        </button>
      ))}
    </nav>
  );
}

/** "Load more" under a timeline while the API has another page (`nextCursor`). */
export function TimelineLoadMore({
  hasMore,
  loading,
  onLoadMore,
}: {
  hasMore: boolean;
  loading: boolean;
  onLoadMore: () => void;
}) {
  if (!hasMore) return null;
  return (
    <div className="crm-d-flex crm-justify-content-center" style={{ padding: '12px 0' }}>
      <button
        type="button"
        className={cn('btn-crm btn-crm--outline btn-crm--sm', loading && 'is-loading')}
        disabled={loading}
        aria-busy={loading}
        onClick={onLoadMore}
      >
        {loading ? 'Loading…' : 'Load more'}
      </button>
    </div>
  );
}
