'use client';

import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { connectGoogleCalendar } from '../../api.client';
import type { ChooserType } from '../../scheduler';

/**
 * Pieces the Meeting Scheduler and Calendar pages share, drawn with the design's markup
 * (sales-schedule.css / meeting-popup.css): the `.ss-dd` dropdown, the `[data-tooltip]` popover,
 * and the meeting type chooser.
 */

export const COMING_SOON = 'Coming soon';

/* ------------------------------------------------------------- dropdown */

/**
 * The design's `.ss-dd`: a toggle and a `.ss-menu` placed `fixed` under it (sales-schedule.js
 * openMenu). The menu goes to <body>, as scheduling-pages.js moves it, so a scrolling table or a
 * filtered event block never clips it.
 */
export function SsDropdown({
  className,
  toggleClassName,
  toggle,
  menuClassName,
  alignRight,
  disabled,
  toggleProps,
  onOpenChange,
  children,
}: {
  className?: string;
  toggleClassName: string;
  toggle: React.ReactNode;
  menuClassName?: string;
  /** Right-align the menu to the toggle (row and bulk actions). */
  alignRight?: boolean;
  disabled?: boolean;
  toggleProps?: React.ButtonHTMLAttributes<HTMLButtonElement> & Record<`data-${string}`, string>;
  onOpenChange?: (open: boolean) => void;
  children: (close: () => void) => React.ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef<HTMLSpanElement>(null);
  const btnRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);

  const set = useCallback(
    (next: boolean) => {
      setOpen(next);
      onOpenChange?.(next);
    },
    [onOpenChange],
  );
  const close = useCallback(() => set(false), [set]);

  const place = useCallback(() => {
    const btn = btnRef.current;
    const menu = menuRef.current;
    if (!btn || !menu) return;
    const r = btn.getBoundingClientRect();
    if (menu.classList.contains('ss-menu--block')) menu.style.minWidth = `${r.width}px`;
    const w = menu.offsetWidth;
    const h = menu.offsetHeight;
    let left = alignRight ? r.right - w : r.left;
    left = Math.max(8, Math.min(left, window.innerWidth - w - 8));
    let top = r.bottom + 4;
    if (top + h > window.innerHeight - 8 && r.top - h - 4 > 8) top = r.top - h - 4;
    menu.style.left = `${left}px`;
    menu.style.top = `${top}px`;
  }, [alignRight]);

  useLayoutEffect(() => {
    if (open) place();
  }, [open, place]);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (menuRef.current?.contains(t) || wrapRef.current?.contains(t)) return;
      close();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        close();
        btnRef.current?.focus();
      }
    };
    const onScroll = (e: Event) => {
      if (menuRef.current?.contains(e.target as Node)) return;
      close();
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    window.addEventListener('scroll', onScroll, true);
    window.addEventListener('resize', close);
    // focus the menu's search, as the design does
    menuRef.current?.querySelector<HTMLInputElement>('input[type="search"]')?.focus();
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
      window.removeEventListener('scroll', onScroll, true);
      window.removeEventListener('resize', close);
    };
  }, [open, close]);

  return (
    <span className={cn('ss-dd', className)} ref={wrapRef}>
      <button
        type="button"
        ref={btnRef}
        className={toggleClassName}
        aria-haspopup="true"
        aria-expanded={open}
        disabled={disabled}
        onClick={() => set(!open)}
        {...toggleProps}
      >
        {toggle}
      </button>
      {open
        ? createPortal(
            <div
              className={cn('ss-menu', menuClassName)}
              ref={menuRef}
              style={{ position: 'fixed', zIndex: 10050 }}
            >
              {children(close)}
            </div>,
            document.body,
          )
        : null}
    </span>
  );
}

/** A filter dropdown with search (`data-ss-select`): the selected option is marked. */
export function SsSelectMenu({
  options,
  value,
  onPick,
  close,
  searchLabel,
  emptyText,
}: {
  options: readonly { value: string; label: string; disabled?: boolean; title?: string }[];
  value: string;
  onPick: (value: string) => void;
  close: () => void;
  searchLabel: string;
  emptyText: string;
}) {
  const [q, setQ] = useState('');
  const shown = options.filter(
    (o) => !q.trim() || o.label.toLowerCase().includes(q.trim().toLowerCase()),
  );
  return (
    <>
      <label className="ss-menu__search">
        <input
          type="search"
          placeholder="Search"
          aria-label={searchLabel}
          autoComplete="off"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <span className="ss-menu__search-icon">
          <CrmIcon name="search" className="iconSize-14" />
        </span>
      </label>
      <div data-ss-menu-list="">
        {shown.map((o) => (
          <button
            type="button"
            key={o.value}
            data-ss-opt={o.value}
            className={o.value === value ? 'is-selected' : undefined}
            disabled={o.disabled}
            aria-disabled={o.disabled || undefined}
            data-tooltip={o.title}
            onClick={() => {
              if (o.disabled) return;
              onPick(o.value);
              close();
            }}
          >
            {o.label}
          </button>
        ))}
      </div>
      {shown.length ? null : <p className="ss-menu__empty">{emptyText}</p>}
    </>
  );
}

/* -------------------------------------------------------------- tooltip */

/**
 * The design's tooltip (scheduling-pages.js positionTooltip): one `.ss-tooltip-popover` for the
 * page, shown over any `[data-tooltip]` inside `root` on hover or focus.
 */
export function useDesignTooltip(root: React.RefObject<HTMLElement | null>) {
  useEffect(() => {
    // The page may render its root after loading: fall back to the document.
    const inside = (el: Element) => (root.current ?? document.body).contains(el);
    const tip = document.createElement('div');
    tip.className = 'ss-tooltip-popover md-tooltip-popover';
    tip.setAttribute('role', 'tooltip');
    tip.setAttribute('aria-hidden', 'true');
    document.body.appendChild(tip);
    let active: HTMLElement | null = null;

    const show = (target: HTMLElement) => {
      const text = target.getAttribute('data-tooltip') ?? '';
      if (!text) return hide();
      active = target;
      tip.textContent = text;
      tip.classList.toggle('is-multiline', text.length > 35);
      tip.classList.remove('is-arrow-top');
      tip.classList.add('is-visible');
      tip.setAttribute('aria-hidden', 'false');
      const rect = target.getBoundingClientRect();
      const tr = tip.getBoundingClientRect();
      let top = rect.top - tr.height - 8;
      if (target.getAttribute('data-tooltip-pos') === 'bottom' || top < 10) {
        top = rect.bottom + 8;
        tip.classList.add('is-arrow-top');
      }
      const center = rect.left + rect.width / 2 - tr.width / 2;
      const left = Math.max(10, Math.min(center, window.innerWidth - tr.width - 10));
      tip.style.top = `${top}px`;
      tip.style.left = `${left}px`;
      tip.style.setProperty('--arrow-left', `${rect.left + rect.width / 2 - left}px`);
    };
    const hide = () => {
      active = null;
      tip.classList.remove('is-visible', 'is-arrow-top');
      tip.setAttribute('aria-hidden', 'true');
    };
    const find = (e: Event) =>
      (e.target as Element | null)?.closest?.<HTMLElement>('[data-tooltip]') ?? null;
    const over = (e: Event) => {
      const t = find(e);
      if (t && t !== active && (inside(t) || t.closest('.ss-menu'))) show(t);
    };
    const out = (e: Event) => {
      const t = find(e);
      if (t && t === active) hide();
    };
    document.addEventListener('mouseover', over);
    document.addEventListener('mouseout', out);
    document.addEventListener('focusin', over);
    document.addEventListener('focusout', out);
    window.addEventListener('scroll', hide, true);
    return () => {
      document.removeEventListener('mouseover', over);
      document.removeEventListener('mouseout', out);
      document.removeEventListener('focusin', over);
      document.removeEventListener('focusout', out);
      window.removeEventListener('scroll', hide, true);
      tip.remove();
    };
  }, [root]);
}

/* -------------------------------------------- choose a scheduling page type */

const EXAMPLES: Record<string, { title: string; items: string[] }> = {
  group: {
    title: 'Group examples',
    items: [
      'I want my manager to be invited to all my important meetings.',
      'I want to invite a subject matter expert to help on my consultation calls.',
      'My colleague and I share a project, and I want us both to be on every call.',
    ],
  },
  'round-robin': {
    title: 'Round robin examples',
    items: [
      'I want to send prospects and customers a link to book a time with any of my company’s reps.',
      'I want to add the link on my website to book time with any available team members.',
      'I want to replace my “request a demo” form with a link to book time with any of my company’s reps.',
    ],
  },
};

const CHOICES: readonly {
  type: ChooserType;
  title: string;
  text: string;
  img: string;
  person?: boolean;
}[] = [
  {
    type: 'one-on-one',
    title: 'One-on-One',
    text: 'Prospects schedule time with just you.',
    img: '/crm/assets/img/one-on-one.svg',
    person: true,
  },
  {
    type: 'group',
    title: 'Group',
    text: 'Prospects schedule time with multiple team members at once.',
    img: '/crm/assets/img/group.svg',
  },
  {
    type: 'round-robin',
    title: 'Round Robin',
    text: 'Prospects schedule time with an available team member based on distribution rules.',
    img: '/crm/assets/img/round-robin.svg',
  },
];

/**
 * "Choose a scheduling page type" (create-scheduling-page.html, meeting-popup.js): a card click
 * selects the type (One-on-One by default), Next opens the create page for it.
 */
export function MeetingTypeChooser({
  open,
  onClose,
  onChoose,
}: {
  open: boolean;
  onClose: () => void;
  onChoose: (type: ChooserType) => void;
}) {
  const modalRef = useRef<HTMLElement>(null);
  const [examples, setExamples] = useState<string | null>(null);
  const [left, setLeft] = useState<number | null>(null);
  const [picked, setPicked] = useState<ChooserType>('one-on-one');

  useEffect(() => {
    if (!open) return;
    const previous = document.activeElement as HTMLElement | null;
    setPicked('one-on-one');
    modalRef.current?.focus();
    document.body.classList.add('meeting-choice-open');
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.classList.remove('meeting-choice-open');
      setExamples(null);
      previous?.focus?.();
    };
  }, [open, onClose]);

  if (!open) return null;

  const toggleExamples = (type: string, button: HTMLButtonElement) => {
    if (examples === type) {
      setExamples(null);
      return;
    }
    const item = button.closest('.meeting-choice-item');
    const modal = modalRef.current;
    if (item && modal && !window.matchMedia('(max-width: 700px)').matches) {
      const r = item.getBoundingClientRect();
      setLeft(r.left + r.width / 2 - modal.getBoundingClientRect().left);
    } else {
      setLeft(null);
    }
    setExamples(type);
  };

  const content = examples ? EXAMPLES[examples] : undefined;

  return (
    <div
      className="meeting-choice-backdrop"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <section
        className="meeting-choice-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="meeting-choice-title"
        tabIndex={-1}
        ref={modalRef}
      >
        <header className="meeting-choice-modal__header">
          <h2 id="meeting-choice-title">Choose a scheduling page type</h2>
          <button
            className="meeting-choice-close"
            type="button"
            aria-label="Close dialog"
            onClick={onClose}
          >
            <CrmIcon name="x" className="iconSize-20" />
          </button>
        </header>

        <div className="meeting-choice-grid">
          {CHOICES.map((c) => (
            <article
              key={c.type}
              className={cn('meeting-choice-item', c.type !== 'round-robin' && 'crm-h-100')}
            >
              <button
                className={cn('meeting-choice-card', picked === c.type && 'is-selected')}
                type="button"
                data-meeting-type={c.type}
                aria-pressed={picked === c.type}
                onClick={() => setPicked(c.type)}
                onDoubleClick={() => onChoose(c.type)}
              >
                <span className="meeting-choice-check" aria-hidden="true">
                  <svg viewBox="0 0 16 16">
                    <path
                      d="m3.5 8.5 3 3 6-7"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                </span>
                <span
                  className={cn('meeting-choice-art', c.person && 'meeting-choice-art--person')}
                  aria-hidden="true"
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={c.img} width={100} alt="" />
                </span>
                <strong>{c.title}</strong>
                <span>{c.text}</span>
              </button>
              {c.type === 'one-on-one' ? null : (
                <button
                  className="meeting-choice-examples"
                  type="button"
                  aria-expanded={examples === c.type}
                  onClick={(e) => toggleExamples(c.type, e.currentTarget)}
                >
                  View example use cases
                </button>
              )}
            </article>
          ))}
        </div>

        {content ? (
          <aside
            className="meeting-choice-popover"
            aria-live="polite"
            style={
              {
                ...(left !== null ? { left: `${left}px` } : {}),
                '--caret-left': '50%',
              } as React.CSSProperties
            }
          >
            <span className="meeting-choice-popover__caret" aria-hidden="true" />
            <h3>{content.title}</h3>
            <ul>
              {content.items.map((item) => (
                <li key={item}>{item}</li>
              ))}
            </ul>
          </aside>
        ) : null}

        <footer className="meeting-choice-footer">
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm lp-btn--pill"
            onClick={onClose}
          >
            Cancel
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--primary btn-crm--sm lp-btn--pill"
            onClick={() => onChoose(picked)}
          >
            Next
          </button>
        </footer>
      </section>
    </div>
  );
}

/**
 * "Connect Google Calendar": off to Google's consent screen. The scheduling pages list's banner,
 * and since QA #652 the editor when a save is refused for want of a calendar (there the
 * design's error toast says "Connect Now": calendar-connect.js).
 */
export function ConnectCalendarLink({ label = 'Connect Google Calendar' }: { label?: string }) {
  const toast = useToast();
  const onConnect = async () => {
    try {
      const { authUrl } = await connectGoogleCalendar();
      window.location.assign(authUrl);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };
  return (
    <button type="button" className="ss-link ss-link--brand" onClick={() => void onConnect()}>
      {label}
    </button>
  );
}

/** This app's origin (for public links), once mounted in the browser. */
export function useOrigin(): string {
  const [origin, setOrigin] = useState('');
  useEffect(() => setOrigin(window.location.origin), []);
  return origin;
}

/** Copies `text`; false when the browser refuses. */
export async function copyText(text: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
}
