'use client';

import Link from 'next/link';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { htmlToPlain, safeRichHtml } from '@/lib/utils/safe-html';
import { cn } from '@/lib/utils/cn';
import { AddToPlaylistDialog } from './AddToPlaylistDialog';
import { callDateNumeric, callTitle, directionLabel, durationLong } from '../format';
import type { CallCompanyBrief, CallContactBrief, CallDealBrief, CallRow } from '../types';

/* activity-preview.js icons (16px grid) */
const PATHS = {
  x: <path d="M4 4l8 8M12 4l-8 8" />,
  caret: <path d="M4 6l4 4 4-4" />,
  tri: <path d="M4.5 6.5h7L8 10z" fill="currentColor" stroke="none" />,
  plus: <path d="M8 3v10M3 8h10" />,
  gear: (
    <>
      <path d="M6.9 1.8h2.2l.35 1.6 1.1.55 1.45-.8 1.55 1.55-.8 1.45.55 1.1 1.6.35v2.2l-1.6.35-.55 1.1.8 1.45-1.55 1.55-1.45-.8-1.1.55-.35 1.6H6.9l-.35-1.6-1.1-.55-1.45.8L2.45 12.6l.8-1.45-.55-1.1-1.6-.35V7.5l1.6-.35.55-1.1-.8-1.45L4 3.05l1.45.8 1.1-.55z" />
      <circle cx="8" cy="8.6" r="2" />
    </>
  ),
  copy: (
    <>
      <rect x="5.5" y="5.5" width="7.5" height="7.5" rx="1.5" />
      <path d="M3 10.5V4a1 1 0 0 1 1-1h6.5" />
    </>
  ),
  share: <path d="M8 10V2.5M5 5l3-3 3 3M3 9v4h10V9" />,
  building: <path d="M3 14V3h6v11M9 6h4v8M5 5.5h2M5 8h2M5 10.5h2M11 8.5h0M11 11h0" />,
} as const;

export function Ico({ name, className }: { name: keyof typeof PATHS; className?: string }) {
  return (
    <svg
      className={cn('apv-i', className)}
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      {PATHS[name]}
    </svg>
  );
}

/** The empty association card's drawing (activity-preview.js EMPTY_ART). */
export function EmptyArt() {
  return (
    <svg
      className="apv-empty__art"
      viewBox="0 0 96 96"
      aria-hidden
      fill="none"
      strokeLinejoin="round"
    >
      <path d="M37 21h29v29H40v28H11V49h26z" stroke="#ff5c35" strokeWidth="2" />
      <rect
        x="56"
        y="5"
        width="22"
        height="22"
        rx="3"
        stroke="var(--apv-art, #2456e6)"
        strokeWidth="2"
        fill="var(--surface, #fff)"
      />
      <rect
        x="42"
        y="27"
        width="18"
        height="18"
        rx="2.5"
        fill="#ff5c35"
        stroke="var(--apv-art-ink, #213343)"
        strokeWidth="1.6"
      />
      <rect x="17" y="55" width="18" height="18" rx="2.5" stroke="#7e2a70" strokeWidth="1.8" />
    </svg>
  );
}

export const EMPTY_TEXT: Record<string, string> = {
  Deals: 'Track the revenue opportunities associated with this record.',
  Tickets: 'Track the customer requests associated with this record.',
};

/** The design's sections below Deals, each empty (activity-preview.js callBody `collapsed`). */
export const OTHER_SECTIONS = [
  'Tickets',
  'Meetings',
  'Contracts',
  'Projects',
  'Events',
  'CTA Submissions',
];

const SOURCE_LABEL: Record<string, string> = {
  manual: 'CRM UI',
  import: 'Import',
  api: 'API',
  workflow: 'Workflow',
  integration: 'Integration',
  migration: 'Migration',
};

export function Section({
  title,
  children,
  extra,
  tools,
  onSoon,
}: {
  title: string;
  children: ReactNode;
  extra?: ReactNode;
  /** The association cards' "+ Add" and settings gear. */
  tools?: boolean;
  onSoon: (what: string) => void;
}) {
  const [open, setOpen] = useState(true);
  return (
    <section className={cn('apv-sec', open && 'is-open')}>
      <div className="apv-sec__head">
        <button
          type="button"
          className="apv-sec__toggle"
          aria-expanded={open}
          onClick={() => setOpen((o) => !o)}
        >
          <Ico name="caret" className="apv-sec__caret" />
          <span>{title}</span>
        </button>
        {extra}
        {tools ? (
          <>
            <button
              type="button"
              className="apv-add"
              aria-disabled
              title="Adding associations here is coming soon"
              onClick={() => onSoon('Adding associations from the preview')}
            >
              <Ico name="plus" />
              Add
            </button>
            <button
              type="button"
              className="apv-gear"
              aria-label="Manage card settings"
              title="Card settings are coming soon"
              aria-disabled
              onClick={() => onSoon('Card settings')}
            >
              <Ico name="gear" />
            </button>
          </>
        ) : null}
      </div>
      <div className="apv-sec__body">{children}</div>
    </section>
  );
}

function CopyButton({ value, what }: { value: string; what: string }) {
  const toast = useToast();
  return (
    <button
      type="button"
      className="apv-copy"
      aria-label={`Copy ${what}`}
      title="Copy"
      onClick={() => {
        void navigator.clipboard?.writeText(value).then(
          () => toast(`Copied ${what}`),
          () => toast('Copy failed', 'danger'),
        );
      }}
    >
      <Ico name="copy" />
    </button>
  );
}

export function ContactCard({
  x,
  onSoon,
}: {
  x: CallContactBrief;
  onSoon: (what: string) => void;
}) {
  return (
    <div className="apv-card">
      <div className="apv-card__head">
        <span className="apv-card__logo" aria-hidden>
          {(x.name || '?').charAt(0)}
        </span>
        <Link className="apv-card__name" href={`/contacts/${x.id}`}>
          {x.name}
        </Link>
      </div>
      {x.jobTitle ? <p className="apv-card__line apv-card__line--muted">{x.jobTitle}</p> : null}
      <p className="apv-card__line">
        <span>Email:</span>{' '}
        {x.email ? (
          <>
            <a href={`mailto:${x.email}`}>{x.email}</a>
            <CopyButton value={x.email} what="email" />
          </>
        ) : (
          '--'
        )}
      </p>
      <p className="apv-card__line">
        <span>Phone number:</span>{' '}
        {x.phone ? (
          <>
            <a href={`tel:${x.phone}`}>{x.phone}</a>
            <CopyButton value={x.phone} what="phone number" />
          </>
        ) : (
          '--'
        )}
      </p>
      <button
        type="button"
        className="apv-link apv-card__label"
        aria-disabled
        title="Association labels are coming soon"
        onClick={() => onSoon('Association labels')}
      >
        Add association label
      </button>
    </div>
  );
}

export function CompanyCard({ x }: { x: CallCompanyBrief }) {
  return (
    <div className="apv-card">
      <div className="apv-card__head">
        <span className="apv-card__logo" aria-hidden>
          <Ico name="building" />
        </span>
        <Link className="apv-card__name" href={`/companies/${x.id}`}>
          {x.name}
        </Link>
      </div>
      <p className="apv-card__line">
        <span>Company Domain…:</span>{' '}
        {x.domain ? (
          <>
            <a href={`https://${x.domain}`} target="_blank" rel="noopener noreferrer">
              {x.domain}
            </a>
            <CopyButton value={x.domain} what="domain" />
          </>
        ) : (
          '--'
        )}
      </p>
      <p className="apv-card__line">
        <span>Phone Number:</span>{' '}
        {x.phone ? (
          <>
            <a href={`tel:${x.phone}`}>{x.phone}</a>
            <CopyButton value={x.phone} what="phone number" />
          </>
        ) : (
          '--'
        )}
      </p>
    </div>
  );
}

export function DealCard({ x }: { x: CallDealBrief }) {
  return (
    <div className="apv-card">
      <div className="apv-card__head">
        <span className="apv-card__logo" aria-hidden>
          {(x.name || '?').charAt(0)}
        </span>
        <Link className="apv-card__name" href={`/deals/${x.id}`}>
          {x.name}
        </Link>
      </div>
    </div>
  );
}

export function Cards<T extends { id: string }>({
  title,
  linked,
  render,
  onSoon,
}: {
  title: string;
  linked: { total: number; items: T[] };
  render: (x: T) => ReactNode;
  onSoon: (what: string) => void;
}) {
  return (
    <Section title={`${title} (${linked.total})`} tools onSoon={onSoon}>
      {linked.items.length ? (
        <div>
          {linked.items.map((x) => (
            <div key={x.id} className="apv-cardwrap">
              {render(x)}
            </div>
          ))}
          {linked.total > linked.items.length ? (
            <p className="apv-muted">
              And {linked.total - linked.items.length} more {title.toLowerCase()}.
            </p>
          ) : null}
        </div>
      ) : (
        <div className="apv-empty">
          <EmptyArt />
          <p>{EMPTY_TEXT[title] ?? `No ${title.toLowerCase()} associated with this record.`}</p>
        </div>
      )}
    </Section>
  );
}

/** An Actions item: a link (`href`), else one that is coming soon. */
export type ActionsItem = { label: string; href?: string };

/**
 * The design's "Actions ▾" (top: preview and history items; About: properties). MT-5: a page's
 * own `groups` (the meeting preview's "View meeting details").
 */
export function ActionsMenu({
  where,
  onSoon,
  groups: custom,
}: {
  where: 'top' | 'about';
  onSoon: (what: string) => void;
  groups?: ActionsItem[][];
}) {
  const btnRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const [pos, setPos] = useState<{ top: number; left: number; arrow: number } | null>(null);
  useEffect(() => {
    if (!pos) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (!menuRef.current?.contains(t) && !btnRef.current?.contains(t)) setPos(null);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setPos(null);
        btnRef.current?.focus();
      }
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [pos]);
  const groups: ActionsItem[][] =
    custom ??
    (where === 'about'
      ? [['View all properties', 'View property history']]
      : [
          ['Customize preview', 'View all properties', 'View property history'],
          ['View association history'],
        ]
    ).map((g) => g.map((label) => ({ label })));
  const width = 260;
  return (
    <>
      <button
        ref={btnRef}
        type="button"
        className="apv-actions"
        aria-haspopup="menu"
        aria-expanded={Boolean(pos)}
        onClick={() => {
          if (pos) {
            setPos(null);
            return;
          }
          const r = btnRef.current!.getBoundingClientRect();
          const left = Math.max(8, Math.min(window.innerWidth - width - 8, r.right - width + 8));
          setPos({ top: r.bottom + 12, left, arrow: r.left + r.width / 2 - left });
        }}
      >
        Actions
        <Ico name="tri" className="apv-i--tri" />
      </button>
      {pos ? (
        <div
          ref={menuRef}
          className="apv-menu"
          role="menu"
          style={
            {
              top: pos.top,
              left: pos.left,
              width,
              '--apv-arrow': `${Math.max(16, Math.min(width - 20, pos.arrow))}px`,
            } as React.CSSProperties
          }
        >
          {groups.map((g) => (
            <div key={g[0]?.label} className="apv-menu__grp">
              {g.map(({ label, href }) =>
                href ? (
                  <Link
                    key={label}
                    href={href}
                    role="menuitem"
                    className="apv-menu__item"
                    onClick={() => setPos(null)}
                  >
                    {label}
                  </Link>
                ) : (
                  <button
                    key={label}
                    type="button"
                    role="menuitem"
                    className="apv-menu__item is-dis"
                    aria-disabled
                    onClick={() => {
                      setPos(null);
                      onSoon(label);
                    }}
                  >
                    {label}
                  </button>
                ),
              )}
            </div>
          ))}
        </div>
      ) : null}
    </>
  );
}

/**
 * The docked call preview (design activity-preview.js callBody): title and direction, the
 * recording card (notes; recordings, transcripts and playlists wait for a calling provider),
 * About this call, and the linked contacts, companies and deals.
 */
export function CallPreviewPanel({
  call,
  timeZone,
  outcomeLabel,
  onClose,
}: {
  call: CallRow | null;
  timeZone: string;
  outcomeLabel: (value: string | null) => string | null;
  onClose: () => void;
}) {
  const toast = useToast();
  const soon = (what: string) => toast(`${what} is coming soon`, 'info');
  const [tab, setTab] = useState<'summary' | 'notes'>('notes');
  /** CL9: the call "Add to playlist" adds. */
  const [playlistFor, setPlaylistFor] = useState<string | null>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const closeRef = useRef<HTMLButtonElement>(null);

  const callId = call?.id ?? null;
  useEffect(() => {
    if (!callId) return;
    document.body.classList.add('apv-open');
    setTab('notes');
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
    closeRef.current?.focus({ preventScroll: true });
    return () => document.body.classList.remove('apv-open');
  }, [callId]);

  useEffect(() => {
    if (!callId) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !document.querySelector('.apv-menu, .lp-modal-ov, .lp-pop')) {
        onClose();
      }
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [callId, onClose]);

  if (!call) return null;
  const name = callTitle(call);
  const notesPlain = call.notes ? htmlToPlain(call.notes).trim() : '';
  const about: Array<[string, string]> = [
    ['Activity date', callDateNumeric(call.occurredAt, timeZone)],
    ['Activity assigned to', call.owner?.name ?? '--'],
    ['Call outcome', outcomeLabel(call.outcome) ?? '--'],
    ['Call duration', durationLong(call.durationSeconds)],
    ['Record source', SOURCE_LABEL[call.source] ?? call.source],
  ];

  return (
    <aside className="apv" role="complementary" aria-label={`${name} preview`}>
      {/* CL9: a portal, so it opens over the page. */}
      <AddToPlaylistDialog
        callIds={playlistFor ? [playlistFor] : null}
        onClose={() => setPlaylistFor(null)}
      />
      <header className="apv__head">
        <h2 className="apv__h">Preview</h2>
        <button
          ref={closeRef}
          type="button"
          className="apv__close"
          aria-label="Close preview"
          onClick={onClose}
        >
          <Ico name="x" />
        </button>
      </header>
      <div ref={scrollRef} className="apv__scroll">
        <div className="apv-top">
          <div className="apv-top__bar">
            <ActionsMenu where="top" onSoon={soon} />
          </div>
          <h2 className="apv-title">{name}</h2>
          <p className="apv-meta">
            <b>Call Direction</b> {directionLabel(call.direction) ?? '--'}
          </p>
        </div>

        <Section title="Call Recording" onSoon={soon}>
          <div className="apv-rec__tools">
            <button type="button" className="apv-pill" onClick={() => setPlaylistFor(call.id)}>
              <Ico name="plus" />
              Add to playlist
            </button>
            <button
              type="button"
              className="apv-pill apv-pill--primary"
              aria-disabled
              title="Sharing calls is coming soon"
              onClick={() => soon('Sharing calls')}
            >
              <Ico name="share" />
              Share
            </button>
          </div>
          <div className="apv-notes">
            <div className="apv-notes__top">
              <div className="apv-seg" role="tablist">
                {(['summary', 'notes'] as const).map((t) => (
                  <button
                    key={t}
                    type="button"
                    role="tab"
                    className={cn('apv-seg__btn', tab === t && 'is-on')}
                    aria-selected={tab === t}
                    onClick={() => setTab(t)}
                  >
                    {t === 'summary' ? 'Summary' : 'Notes'}
                  </button>
                ))}
              </div>
              <CopyButton value={notesPlain} what="notes" />
            </div>
            {tab === 'notes' ? (
              <div className="apv-notes__pane">
                {call.notes ? (
                  <div dangerouslySetInnerHTML={{ __html: safeRichHtml(call.notes) }} />
                ) : (
                  <span className="apv-muted">No notes for this call.</span>
                )}
              </div>
            ) : (
              <div className="apv-notes__pane">
                <span className="apv-muted">A summary appears once the call has a transcript.</span>
              </div>
            )}
          </div>
        </Section>

        <Section
          title="About this call"
          onSoon={soon}
          extra={
            <>
              <span className="apv-sec__spacer" />
              <ActionsMenu where="about" onSoon={soon} />
              <button
                type="button"
                className="apv-gear"
                aria-label="Card settings"
                title="Card settings are coming soon"
                aria-disabled
                onClick={() => soon('Card settings')}
              >
                <Ico name="gear" />
              </button>
            </>
          }
        >
          {about.map(([label, value]) => (
            <div key={label} className="apv-field">
              <span className="apv-field__l">{label}</span>
              <span className="apv-field__v">{value}</span>
            </div>
          ))}
        </Section>

        <Cards
          title="Contacts"
          linked={call.associations.contacts}
          render={(x) => <ContactCard x={x} onSoon={soon} />}
          onSoon={soon}
        />
        <Cards
          title="Companies"
          linked={call.associations.companies}
          render={(x) => <CompanyCard x={x} />}
          onSoon={soon}
        />
        <Cards
          title="Deals"
          linked={call.associations.deals}
          render={(x) => <DealCard x={x} />}
          onSoon={soon}
        />
        {OTHER_SECTIONS.map((title) => (
          <Section key={title} title={`${title} (0)`} tools onSoon={soon}>
            <div className="apv-empty">
              <EmptyArt />
              <p>{EMPTY_TEXT[title] ?? `See the ${title} associated with this record.`}</p>
            </div>
          </Section>
        ))}
      </div>
    </aside>
  );
}
