'use client';

import { useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { useOwners } from '@/features/owners/useOwners';
import { getMeetingSettings } from '@/features/settings/workspace-settings.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { createBookingPage } from '../../api.client';
import {
  bookingUrl,
  cloneBody,
  embedCode,
  isSlugTaken,
  organizerChoices,
  SLUG_RE,
  slugify,
} from '../../scheduler';
import type { BookingPage } from '../../types';
import { usePageOptions } from '../../usePageOptions';
import { copyText, SsDropdown, SsSelectMenu } from './parts';

/**
 * The Embed Widget and Clone scheduling page popups, as the list page draws them
 * (create-scheduling-page.html, `.ss-modal`) and as the edit page does
 * (meeting-details-page.html, `.mdp-modal`).
 */

type Variant = 'ss' | 'mdp';

const TAKEN =
  'A meetings link with this name already exists. Please choose a unique meetings link.';

function useEscape(open: boolean, onClose: () => void) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    document.body.classList.add('ss-lock');
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.classList.remove('ss-lock');
    };
  }, [open, onClose]);
}

/* ------------------------------------------------------------- published */

/**
 * MT-12 (M-30, MTG-HS-08): HubSpot's "Schedule page published!" after a new page is created:
 * Get embed code (the Embed Widget), Copy share link, or Return to home. `open` is false while
 * the Embed Widget is open over it, so Escape closes only that.
 */
export function PublishedDialog({
  page,
  open,
  onEmbed,
  onCopyLink,
  onHome,
}: {
  page: BookingPage | null;
  open: boolean;
  onEmbed: () => void;
  onCopyLink: () => void;
  onHome: () => void;
}) {
  useEscape(Boolean(page) && open, onHome);
  if (!page) return null;
  const choices = [
    {
      key: 'embed',
      icon: 'file' as const,
      title: 'Get embed code',
      text: 'Grab the embed code to use anywhere.',
      onClick: onEmbed,
    },
    {
      key: 'link',
      icon: 'copy' as const,
      title: 'Copy share link',
      text: 'Copy a share link to send to your audience.',
      onClick: onCopyLink,
    },
  ];
  return (
    <div className="mdp-modal-backdrop" hidden={!open}>
      <section
        className="mdp-modal mdp-published-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="mdp-published-title"
      >
        <header>
          <h2 id="mdp-published-title">Schedule page published!</h2>
          <button type="button" className="mdp-modal-close" aria-label="Close" onClick={onHome}>
            <CrmIcon name="x" className="iconSize-16" />
          </button>
        </header>
        <div className="mdp-modal-body">
          <p className="mdp-modal-help">Choose how you want to share your meeting:</p>
          <div className="mdp-published-choices">
            {choices.map((c) => (
              <button
                key={c.key}
                type="button"
                className="mdp-published-choice"
                onClick={c.onClick}
              >
                <CrmIcon name={c.icon} className="iconSize-20" />
                <strong>{c.title}</strong>
                <span>{c.text}</span>
              </button>
            ))}
          </div>
        </div>
        <footer className="mdp-modal-footer">
          <button type="button" className="mdp-secondary-button" onClick={onHome}>
            Return to home
          </button>
        </footer>
      </section>
    </div>
  );
}

/* ----------------------------------------------------------------- embed */

export function EmbedDialog({
  page,
  variant,
  onClose,
  toast,
}: {
  page: BookingPage | null;
  variant: Variant;
  onClose: () => void;
  toast: (message: string) => void;
}) {
  const [copied, setCopied] = useState(false);
  const [emailOpen, setEmailOpen] = useState(false);
  const [email, setEmail] = useState('');
  useEscape(page !== null, onClose);
  useEffect(() => {
    setCopied(false);
    setEmailOpen(false);
    setEmail('');
  }, [page]);
  if (!page) return null;

  const url = bookingUrl(window.location.origin, page.slug);
  const code = embedCode(url);
  const copy = async () => {
    if (await copyText(code)) {
      setCopied(true);
      toast('Embed code copied');
      window.setTimeout(() => setCopied(false), 2000);
    } else {
      toast('Select the code and copy it');
    }
  };
  // There is no mail endpoint for this: the developer's email opens in the user's mail app.
  const mailto = `mailto:${encodeURIComponent(email.trim())}?subject=${encodeURIComponent(
    `Meetings embed code: ${page.title}`,
  )}&body=${encodeURIComponent(`Please add this booking widget to our website:\n\n${code}\n`)}`;
  const send = () => {
    window.location.href = mailto;
    toast(`Embed code ready to send to ${email.trim()}`);
    onClose();
  };

  if (variant === 'mdp') {
    return (
      <div
        className="mdp-modal-backdrop mdp-embed-backdrop"
        onMouseDown={(e) => {
          if (e.target === e.currentTarget) onClose();
        }}
      >
        <section
          className="mdp-modal mdp-embed-modal"
          role="dialog"
          aria-modal="true"
          aria-labelledby="mdp-embed-title"
        >
          <header>
            <h2 id="mdp-embed-title">Embed Widget</h2>
            <button type="button" className="mdp-modal-close" aria-label="Close" onClick={onClose}>
              <CrmIcon name="x" className="iconSize-16" />
            </button>
          </header>
          <div className="mdp-modal-body">
            <strong className="mdp-embed-meeting-title">{page.title}</strong>
            <p className="mdp-embed-url">{url}</p>
            <label className="mdp-embed-code-label" htmlFor="mdp-embed-code">
              Embed code
            </label>
            <p className="mdp-modal-help mdp-embed-help">
              Embed the Meetings booking widget on your website{' '}
              <span
                className="mdp-embed-info"
                title="Embed the Meetings booking widget on your website"
                aria-label="More information"
              >
                ⓘ
              </span>
            </p>
            <textarea id="mdp-embed-code" readOnly rows={7} aria-label="Embed code" value={code} />
            <div className="mdp-modal-inline-actions mdp-embed-actions">
              <button type="button" onClick={() => void copy()}>
                {copied ? 'Copied!' : 'Copy code'}
              </button>
              <button
                type="button"
                aria-expanded={emailOpen}
                className={emailOpen ? 'is-active' : undefined}
                onClick={() => setEmailOpen((o) => !o)}
              >
                Email web developer
              </button>
            </div>
            {emailOpen ? (
              <div className="mdp-embed-email-section">
                <input
                  type="email"
                  placeholder="Enter your web developer's email address"
                  autoComplete="email"
                  aria-label="Web developer email address"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  autoFocus
                />
                <button
                  type="button"
                  className="mdp-send-message"
                  disabled={!email.trim()}
                  onClick={send}
                >
                  Send message
                </button>
              </div>
            ) : null}
          </div>
          <footer>
            <button type="button" className="mdp-primary-button" onClick={onClose}>
              Close
            </button>
          </footer>
        </section>
      </div>
    );
  }

  return (
    <div className="ss-modal" data-ss-modal="embed">
      <div className="ss-modal__bd" onClick={onClose} />
      <div
        className="ss-dialog ss-dialog--md"
        role="dialog"
        aria-modal="true"
        aria-labelledby="ss-embed-title"
        style={{ maxWidth: 540, borderRadius: 12, background: 'var(--surface)' }}
      >
        <header
          className="ss-dialog__head"
          style={{ padding: '16px 20px', borderBottom: '1px solid var(--border)' }}
        >
          <h2 id="ss-embed-title" style={{ fontSize: 17, fontWeight: 600 }}>
            Embed Widget
          </h2>
          <button type="button" className="ss-iconbtn" aria-label="Close" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-16" />
          </button>
        </header>
        <div className="ss-dialog__body" style={{ padding: 20 }}>
          <h3 style={{ fontSize: 15, fontWeight: 700, margin: '0 0 4px', color: 'var(--text)' }}>
            {page.title}
          </h3>
          <p
            style={{
              color: 'var(--text-muted)',
              fontSize: 13,
              margin: '0 0 16px',
              wordBreak: 'break-all',
            }}
          >
            {url}
          </p>
          <h4 style={{ fontSize: 13.5, fontWeight: 600, margin: '0 0 4px', color: 'var(--text)' }}>
            Embed code
          </h4>
          <p
            style={{
              fontSize: 13,
              color: 'var(--text)',
              margin: '0 0 8px',
              display: 'flex',
              alignItems: 'center',
              gap: 4,
            }}
          >
            Embed the Meetings booking widget on your website
            <button
              type="button"
              className="ss-info"
              data-tooltip="Embed the Meetings booking widget on your website"
              aria-label="More info"
            >
              <CrmIcon name="info" className="iconSize-14" />
            </button>
          </p>
          <div className="ss-code-box" style={{ marginBottom: 14 }}>
            <textarea
              readOnly
              className="ss-embed-textarea"
              rows={7}
              value={code}
              aria-label="Embed code"
              style={{
                width: '100%',
                boxSizing: 'border-box',
                padding: 12,
                resize: 'none',
              }}
            />
          </div>
          <div className="ss-btn-pill-group">
            <button type="button" className="ss-btn-seg" onClick={() => void copy()}>
              {copied ? 'Copied!' : 'Copy code'}
            </button>
            <button
              type="button"
              className={cn('ss-btn-seg', emailOpen && 'is-active')}
              onClick={() => setEmailOpen((o) => !o)}
            >
              Email web developer
            </button>
          </div>
          {emailOpen ? (
            <div style={{ marginBottom: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <input
                type="email"
                className="ss-input"
                placeholder="Enter your web developer's email address"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                autoFocus
                style={{
                  height: 40,
                  borderRadius: 8,
                  border: '1.5px solid var(--text, #33475b)',
                  padding: '0 14px',
                  fontSize: 13.5,
                }}
              />
              <div>
                <button
                  type="button"
                  className="ss-btn-pill-disabled"
                  disabled={!email.trim()}
                  onClick={send}
                >
                  Send message
                </button>
              </div>
            </div>
          ) : null}
        </div>
        <footer
          className="ss-dialog__foot crm-justify-content-end"
          style={{ padding: '0 20px 22px', borderTop: 'none', justifyContent: 'flex-start' }}
        >
          <button type="button" className="ss-btn-close-dark" onClick={onClose}>
            Close
          </button>
        </footer>
      </div>
    </div>
  );
}

/* ----------------------------------------------------------------- clone */

export function CloneDialog({
  page,
  variant,
  onClose,
  onCloned,
}: {
  page: BookingPage | null;
  variant: Variant;
  onClose: () => void;
  onCloned: (page: BookingPage) => void;
}) {
  const me = useCurrentUser();
  // HUB-662: admins clone for another organizer, as they create pages for others.
  const canPickOrganizer = me.role === 'admin';
  const { owners } = useOwners(canPickOrganizer && page !== null, false);
  // QA round 1 (BUG-03): only users who may manage their pages (not read-only) organize one.
  const pageOptions = usePageOptions(canPickOrganizer && page !== null);
  const [organizerId, setOrganizerId] = useState(me.user.id);
  const organizerOptions = [
    { value: me.user.id, label: 'Current user (me)' },
    ...organizerChoices(owners, pageOptions?.organizerIds)
      .filter((o) => o.userId !== me.user.id)
      .map((o) => ({ value: o.userId, label: o.name })),
  ];
  const organizerLabel =
    organizerOptions.find((o) => o.value === organizerId)?.label ?? me.user.name;
  const [name, setName] = useState('');
  const [slug, setSlug] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const nameRef = useRef<HTMLInputElement>(null);
  useEscape(page !== null, onClose);
  // QA round 1 (BUG-04): a page whose rotation was deleted (before that was refused) is cloned
  // without it, booking its organizer and members, instead of being refused.
  const [rotationGone, setRotationGone] = useState(false);
  useEffect(() => {
    setRotationGone(false);
    const rotationId = page?.pageType === 'round_robin' ? page.rotationId : null;
    if (!rotationId) return;
    let alive = true;
    getMeetingSettings().then(
      (m) => alive && setRotationGone(!m.rotations.some((r) => r.id === rotationId)),
      () => {},
    );
    return () => {
      alive = false;
    };
  }, [page]);
  const rotationNote = rotationGone
    ? 'The rotation this page used was deleted, so the clone books its organizer and members.'
    : null;

  useEffect(() => {
    if (!page) return;
    setName(`${page.title} (clone)`);
    setSlug(slugify(`${page.slug}-clone`));
    setOrganizerId(me.user.id);
    setError(null);
    setBusy(false);
    window.setTimeout(() => nameRef.current?.select(), 50);
  }, [page, me.user.id]);
  if (!page) return null;

  const cleanSlug = slugify(slug);
  const preview = bookingUrl(window.location.origin, cleanSlug || 'clone');

  const save = async (e?: React.FormEvent) => {
    e?.preventDefault();
    if (busy) return;
    if (!name.trim() || !cleanSlug) {
      setError('Enter an internal name and a scheduling page link.');
      return;
    }
    if (!SLUG_RE.test(cleanSlug)) {
      setError('Use 3-64 lowercase letters, digits and -.');
      return;
    }
    setBusy(true);
    setError(null);
    try {
      const body = cloneBody(
        page,
        name.trim(),
        cleanSlug,
        organizerId !== me.user.id ? organizerId : undefined,
      );
      const created = await createBookingPage(rotationGone ? { ...body, rotationId: null } : body);
      onCloned(created);
    } catch (err) {
      // QA #652: a clone is active, so without a calendar the 409 is the API's "Connect…" one.
      setError(isSlugTaken(err) ? TAKEN : errorText(err));
      setBusy(false);
    }
  };

  if (variant === 'mdp') {
    return (
      <div
        className="mdp-modal-backdrop"
        onMouseDown={(e) => {
          if (e.target === e.currentTarget) onClose();
        }}
      >
        <section
          className="mdp-modal mdp-clone-modal"
          role="dialog"
          aria-modal="true"
          aria-labelledby="mdp-clone-title"
        >
          <header>
            <h2 id="mdp-clone-title">Clone scheduling page</h2>
            <button type="button" className="mdp-modal-close" aria-label="Close" onClick={onClose}>
              ×
            </button>
          </header>
          <form className="mdp-modal-body" id="mdp-clone-form" onSubmit={(e) => void save(e)}>
            <label htmlFor="mdp-clone-name">
              Internal name <span>*</span> <small>ⓘ</small>
            </label>
            <input
              id="mdp-clone-name"
              ref={nameRef}
              value={name}
              onChange={(e) => {
                setName(e.target.value);
                setError(null);
              }}
            />
            <label>
              Organizer <small>ⓘ</small>
            </label>
            {canPickOrganizer ? (
              <select
                aria-label="Organizer"
                value={organizerId}
                onChange={(e) => setOrganizerId(e.target.value)}
              >
                {organizerOptions.map((o) => (
                  <option key={o.value} value={o.value}>
                    {o.label}
                  </option>
                ))}
              </select>
            ) : (
              <>
                <p className="mdp-clone-help">
                  You don&apos;t have permission to clone scheduling pages for other users, but you
                  can still clone pages for yourself.
                </p>
                <select disabled aria-label="Organizer">
                  <option>Current user (me)</option>
                </select>
              </>
            )}
            <label htmlFor="mdp-clone-slug">
              Scheduling page link <span>*</span> <small>ⓘ</small>
            </label>
            <input
              id="mdp-clone-slug"
              value={slug}
              onChange={(e) => {
                setSlug(e.target.value);
                setError(null);
              }}
            />
            {rotationNote ? <p className="mdp-clone-help">{rotationNote}</p> : null}
            {error ? <p className="mdp-clone-error">{error}</p> : null}
            <p className="mdp-clone-url">
              <span>{preview.slice(0, preview.length - (cleanSlug || 'clone').length)}</span>
              <strong>{cleanSlug || 'clone'}</strong>
            </p>
          </form>
          <footer>
            <button
              type="submit"
              form="mdp-clone-form"
              className="mdp-primary-button"
              disabled={busy}
            >
              {busy ? 'Saving…' : 'Save'}
            </button>
            <button type="button" className="mdp-secondary-button" onClick={onClose}>
              Cancel
            </button>
          </footer>
        </section>
      </div>
    );
  }

  const label: React.CSSProperties = {
    display: 'flex',
    justifyContent: 'flex-start',
    alignItems: 'center',
    gap: 4,
    marginBottom: 6,
    fontSize: 13.5,
    fontWeight: 600,
  };
  return (
    <div className="ss-modal" data-ss-modal="clone">
      <div className="ss-modal__bd" onClick={onClose} />
      <form
        className="ss-dialog ss-dialog--md"
        role="dialog"
        aria-modal="true"
        aria-labelledby="ss-clone-title"
        onSubmit={(e) => void save(e)}
        style={{ maxWidth: 520, borderRadius: 12, background: 'var(--surface)' }}
      >
        <header
          className="ss-dialog__head"
          style={{ padding: '16px 20px', borderBottom: '1px solid var(--border)' }}
        >
          <h2 id="ss-clone-title" style={{ fontSize: 17, fontWeight: 600 }}>
            Clone scheduling page
          </h2>
          <button type="button" className="ss-iconbtn" aria-label="Close" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-16" />
          </button>
        </header>
        <div className="ss-dialog__body" style={{ padding: 20 }}>
          <label className="ss-field" style={{ marginBottom: 16 }}>
            <span className="ss-lbl" style={label}>
              Internal name *
              <button
                type="button"
                className="ss-info"
                data-tooltip="This is used for internal management purposes and will be the name of your link when inserting it in an email."
                aria-label="More info"
              >
                <CrmIcon name="info" className="iconSize-14" />
              </button>
            </span>
            <input
              className="ss-input"
              name="cloneName"
              required
              ref={nameRef}
              style={{ height: 38, borderRadius: 6 }}
              value={name}
              onChange={(e) => {
                setName(e.target.value);
                setError(null);
              }}
            />
          </label>
          <div className="ss-field" style={{ marginBottom: 16 }}>
            <span className="ss-lbl" style={label}>
              Organizer
              <button
                type="button"
                className="ss-info"
                data-tooltip="The team member that will be the owner of the scheduled events."
                aria-label="More info"
              >
                <CrmIcon name="info" className="iconSize-14" />
              </button>
            </span>
            {canPickOrganizer ? (
              <SsDropdown
                className="ss-dd--block"
                toggleClassName="ss-select"
                menuClassName="ss-menu--block ss-organizer-menu"
                toggleProps={{
                  style: {
                    width: '100%',
                    height: 38,
                    borderRadius: 6,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                  },
                }}
                toggle={
                  <>
                    <span>{organizerLabel}</span>
                    <CrmIcon name="chevron-down" className="iconSize-14" />
                  </>
                }
              >
                {(close) => (
                  <SsSelectMenu
                    options={organizerOptions}
                    value={organizerId}
                    onPick={setOrganizerId}
                    close={close}
                    searchLabel="Search organizers"
                    emptyText="No organizers found"
                  />
                )}
              </SsDropdown>
            ) : (
              <div className="ss-dd ss-dd--block" style={{ position: 'relative', width: '100%' }}>
                <button
                  type="button"
                  className="ss-select"
                  disabled
                  data-tooltip="You don't have permission to clone scheduling pages for other users."
                  style={{
                    width: '100%',
                    height: 38,
                    borderRadius: 6,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    cursor: 'not-allowed',
                  }}
                >
                  <span>{me.user.name}</span>
                  <CrmIcon name="chevron-down" className="iconSize-14" />
                </button>
              </div>
            )}
          </div>
          <label className="ss-field" style={{ marginBottom: 8 }}>
            <span className="ss-lbl" style={label}>
              Scheduling page link *
              <button
                type="button"
                className="ss-info"
                data-tooltip="This is the link that prospects and customers use to book meetings on your calendar."
                aria-label="More info"
              >
                <CrmIcon name="info" className="iconSize-14" />
              </button>
            </span>
            <input
              className="ss-input"
              name="cloneSlug"
              required
              style={{ height: 38, borderRadius: 6 }}
              value={slug}
              onChange={(e) => {
                setSlug(e.target.value);
                setError(null);
              }}
            />
            <div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 6 }}>
              {preview}
            </div>
            {rotationNote ? (
              <div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 6 }}>
                {rotationNote}
              </div>
            ) : null}
            {error ? (
              <div
                role="alert"
                style={{ fontSize: 12.5, color: 'var(--danger)', marginTop: 6, fontWeight: 600 }}
              >
                {error}
              </div>
            ) : null}
          </label>
        </div>
        <footer
          className="ss-dialog__foot crm-justify-content-end"
          style={{
            padding: '14px 20px',
            borderTop: '1px solid var(--border)',
            display: 'flex',
            gap: 8,
          }}
        >
          <button
            type="submit"
            className="btn-crm btn-crm--primary btn-crm--sm lp-btn--pill"
            style={{ minWidth: 70 }}
            disabled={busy}
          >
            {busy ? 'Saving…' : 'Save'}
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm lp-btn--pill"
            onClick={onClose}
          >
            Cancel
          </button>
        </footer>
      </form>
    </div>
  );
}
