'use client';

import Link from 'next/link';
import { useEffect, useMemo, useRef, useState } from 'react';
import type { Owner } from '@/features/owners/api.client';
import { cn } from '@/lib/utils/cn';
import { MAX_MEMBERS, redirectUrlOf } from '../../scheduler';
import type { BookingPageType } from '../../types';
import { GmInfo, GmSvg } from './gmParts';

/**
 * Group and round robin pages, redirect after booking and contact property questions, drawn with
 * the 13 Nov design's markup (create-meeting.html / create-meeting.js): the "Team members" step,
 * the "Edit round robin members" drawer, the Confirmation tab's location picker with "Redirect to
 * an external link", and the Form tab's "Add contact property" editor.
 */

/**
 * QA #650: a Settings › Meetings › Meeting Rotation, as a round robin page's "Use a rotation"
 * offers it. Members are user ids (weights keyed by id); `users` has their names from the API.
 */
export interface RotationOption {
  id: string;
  name: string;
  logic: 'even' | 'weighted';
  weights: Record<string, number>;
  /** In order. `active: false`: deactivated, never booked. */
  users: { id: string; name: string; active: boolean }[];
}

/** How a rotation shares the meetings, for the team step and the drawer. */
export function rotationSummary(r: RotationOption): string {
  return r.logic === 'weighted'
    ? `Meetings go to a free member of ${r.name} by their weight (${r.users
        .filter((u) => u.active)
        .map((u) => `${u.name} ${r.weights[u.id] ?? 0}%`)
        .join(', ')}).`
    : `Meetings go to a free member of ${r.name}, the one with the fewest meetings booked through this page first.`;
}

const initialOf = (name: string) => name.trim().charAt(0).toUpperCase() || '?';

/* ------------------------------------------------------------ team step */

export function TeamStep({
  pageType,
  me,
  memberIds,
  owners,
  calendarConnected,
  rotation,
  rotationMissing = false,
  onEdit,
}: {
  pageType: BookingPageType;
  me: { id: string; name: string };
  memberIds: readonly string[];
  owners: readonly Owner[];
  /** The organizer's calendar can take bookings (null: not known yet). */
  calendarConnected: boolean | null;
  /** QA #650: round robin "Use a rotation": its members are the hosts instead. */
  rotation?: RotationOption | null;
  /**
   * QA round 1 (BUG-04): the page names a rotation that no longer exists (deleted before that
   * was refused), so it books the organizer and members, as "Select users".
   */
  rotationMissing?: boolean;
  onEdit: () => void;
}) {
  const nameOf = (id: string) => owners.find((o) => o.userId === id)?.name ?? 'Unknown user';
  if (pageType === 'round_robin' && rotation) {
    return (
      <section className="gm-step-view gm-team-view" id="gm-team-step">
        <div className="gm-step-content">
          <h1>Team members</h1>
          <div className="gm-team-intro">
            <p>
              This round robin uses the rotation <strong>{rotation.name}</strong>, from Settings ›
              Meetings › Meeting Rotations.
            </p>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              id="gm-edit-members"
              onClick={onEdit}
            >
              Edit members
            </button>
          </div>
          <div className="gm-team-table">
            <div className="gm-team-table-head">Name</div>
            <div id="gm-team-list">
              {rotation.users.map((user) => (
                <div className="gm-team-row" key={user.id}>
                  <span className="gm-team-avatar">{initialOf(user.name)}</span>
                  <span>
                    <strong>{user.name}</strong>
                    <small>
                      {!user.active
                        ? 'Deactivated, never booked'
                        : rotation.logic === 'weighted'
                          ? `Weight ${rotation.weights[user.id] ?? 0}%`
                          : 'Books with their connected Google Calendar'}
                    </small>
                  </span>
                </div>
              ))}
            </div>
          </div>
          <p className="gm-help">{rotationSummary(rotation)}</p>
        </div>
      </section>
    );
  }
  return (
    <section className="gm-step-view gm-team-view" id="gm-team-step">
      <div className="gm-step-content">
        <h1>Team members</h1>
        {rotationMissing ? (
          <p className="gm-help" role="status">
            The rotation this page used was deleted, so it books the organizer and the members
            below. Choose its hosts with Edit members and save.
          </p>
        ) : null}
        <div className="gm-team-intro">
          <p>
            {pageType === 'round_robin'
              ? 'Choose the team members you want to participate in this round robin.'
              : 'Choose the team members you want to participate in this group meeting. Invitees can book times when all of them are free.'}
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            id="gm-edit-members"
            onClick={onEdit}
          >
            Edit members
          </button>
        </div>
        <div className="gm-team-table">
          <div className="gm-team-table-head">Name</div>
          <div id="gm-team-list">
            <div className="gm-team-row">
              <span className="gm-team-avatar">{initialOf(me.name)}</span>
              <span>
                <strong>{me.name} (organizer)</strong>
                {calendarConnected === null ? null : (
                  <small>
                    {calendarConnected ? <i className="gm-connected-dot" /> : null}{' '}
                    {calendarConnected ? 'Calendar connected' : 'Calendar not connected'}
                  </small>
                )}
              </span>
            </div>
            {memberIds.map((id) => (
              <div className="gm-team-row" key={id}>
                <span className="gm-team-avatar">{initialOf(nameOf(id))}</span>
                <span>
                  <strong>{nameOf(id)}</strong>
                  <small>Books with their connected Google Calendar</small>
                </span>
              </div>
            ))}
          </div>
        </div>
        {memberIds.length ? null : (
          <p className="gm-help">Add at least one other team member with Edit members.</p>
        )}
        {pageType === 'round_robin' ? (
          <p className="gm-help">
            Meetings go to a free team member, the one with the fewest meetings booked through this
            page first.
          </p>
        ) : null}
      </div>
    </section>
  );
}

/* ------------------------------------------------------- members drawer */

export function MembersDrawer({
  open,
  pageType,
  me,
  self = true,
  value,
  owners,
  rotations,
  rotationId,
  onClose,
  onConfirm,
}: {
  open: boolean;
  pageType: BookingPageType;
  /** The organizer. */
  me: { id: string; name: string };
  /** The organizer is the signed-in user ("(me)"). */
  self?: boolean;
  value: readonly string[];
  owners: readonly Owner[];
  /** QA #650: Settings › Meetings rotations "Use a rotation" offers (null: still loading). */
  rotations: readonly RotationOption[] | null;
  rotationId: string | null;
  onClose: () => void;
  /** `rotationId`: the rotation chosen with "Use a rotation"; null for "Select users". */
  onConfirm: (memberIds: string[], rotationId: string | null) => void;
}) {
  const [picked, setPicked] = useState<string[]>([...value]);
  const [query, setQuery] = useState('');
  const [listOpen, setListOpen] = useState(false);
  const [mode, setMode] = useState<'users' | 'rotation'>(rotationId ? 'rotation' : 'users');
  const [rotation, setRotation] = useState(rotationId ?? '');
  const selectRef = useRef<HTMLDivElement>(null);
  const listRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    setPicked([...value]);
    setQuery('');
    setListOpen(false);
    setMode(rotationId ? 'rotation' : 'users');
    setRotation(rotationId ?? '');
    // Filled each time it opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  useEffect(() => {
    if (!listOpen) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (selectRef.current?.contains(t) || listRef.current?.contains(t)) return;
      setListOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [listOpen]);

  const options = useMemo(() => {
    const q = query.trim().toLowerCase();
    return owners.filter(
      (o) =>
        o.active &&
        o.userId !== me.id &&
        !picked.includes(o.userId) &&
        (!q || `${o.name} ${o.email}`.toLowerCase().includes(q)),
    );
  }, [owners, me.id, picked, query]);

  if (!open) return null;
  const nameOf = (id: string) => owners.find((o) => o.userId === id)?.name ?? 'Unknown user';
  const roundRobin = pageType === 'round_robin';
  const full = picked.length >= MAX_MEMBERS;
  const byRotation = roundRobin && mode === 'rotation';
  const chosen = rotations?.find((r) => r.id === rotation) ?? null;

  return (
    <>
      <div className="gm-drawer-backdrop" id="gm-members-backdrop" onClick={onClose} />
      <aside
        className="gm-members-drawer"
        id="gm-members-drawer"
        aria-label={roundRobin ? 'Edit round robin members' : 'Edit group members'}
        role="dialog"
        aria-modal="true"
      >
        <header>
          <h2>{roundRobin ? 'Edit round robin members' : 'Edit group members'}</h2>
          <button
            type="button"
            className="modal__close"
            id="gm-members-close"
            aria-label="Close"
            onClick={onClose}
          >
            {GmSvg.close}
          </button>
        </header>
        <div className="gm-drawer-body">
          {roundRobin ? (
            <>
              <label className="gm-drawer-label">Round robin member setup</label>
              <div className="gm-member-modes">
                <button
                  type="button"
                  className={cn(!byRotation && 'is-active')}
                  data-member-mode="users"
                  aria-pressed={!byRotation}
                  onClick={() => setMode('users')}
                >
                  <span>{byRotation ? '○' : '●'}</span> Select users
                </button>
                {/* QA #650: the hosts come from a Settings › Meetings rotation. */}
                <button
                  type="button"
                  className={cn(byRotation && 'is-active')}
                  data-member-mode="rotation"
                  aria-pressed={byRotation}
                  onClick={() => setMode('rotation')}
                >
                  <span>{byRotation ? '●' : '○'}</span> Use a rotation
                </button>
              </div>
            </>
          ) : null}
          {byRotation ? (
            <div id="gm-rotation-settings">
              <label className="gm-drawer-label" htmlFor="gm-rotation-select">
                Rotation{' '}
                <GmInfo title="Its members take the meetings, evenly or by weight, as set in Settings › Meetings › Meeting Rotations." />
              </label>
              {rotations === null ? (
                <p className="gm-help">Loading rotations…</p>
              ) : rotations.length ? (
                <>
                  <select
                    id="gm-rotation-select"
                    className="gm-schedule-input"
                    value={rotation}
                    onChange={(e) => setRotation(e.target.value)}
                  >
                    <option value="">Select a rotation</option>
                    {rotations.map((r) => (
                      <option key={r.id} value={r.id}>
                        {r.name} ({r.users.length} member{r.users.length === 1 ? '' : 's'})
                      </option>
                    ))}
                  </select>
                  {chosen ? <p className="gm-help">{rotationSummary(chosen)}</p> : null}
                </>
              ) : (
                <p className="gm-help">
                  No meeting rotations yet. An admin can add one in{' '}
                  <Link href="/settings/meetings#rotations">
                    Settings › Meetings › Meeting Rotations
                  </Link>
                  .
                </p>
              )}
            </div>
          ) : (
            <>
              <label className="gm-drawer-label" htmlFor="gm-member-search">
                Users{' '}
                <GmInfo
                  title={
                    roundRobin
                      ? 'Select the users included in this round robin.'
                      : 'Select the users who join every meeting booked on this page.'
                  }
                />
              </label>
              <div className="gm-member-select" ref={selectRef}>
                <div id="gm-member-chips">
                  <span className="gm-member-chip" data-user={me.name}>
                    <span>{initialOf(me.name)}</span> {me.name} {self ? '(me)' : '(organizer)'}
                  </span>
                  {picked.map((id) => (
                    <span className="gm-member-chip" data-user={nameOf(id)} key={id}>
                      <span>{initialOf(nameOf(id))}</span> {nameOf(id)}{' '}
                      <button
                        type="button"
                        aria-label={`Remove ${nameOf(id)}`}
                        onClick={() => setPicked((p) => p.filter((x) => x !== id))}
                      >
                        {GmSvg.close}
                      </button>
                    </span>
                  ))}
                </div>
                <input
                  id="gm-member-search"
                  autoComplete="off"
                  value={query}
                  disabled={full}
                  placeholder={full ? `At most ${MAX_MEMBERS} team members` : ''}
                  onFocus={() => setListOpen(true)}
                  onChange={(e) => {
                    setQuery(e.target.value);
                    setListOpen(true);
                  }}
                />
                <button
                  type="button"
                  id="gm-member-dropdown"
                  aria-label="Show users"
                  disabled={full}
                  onClick={() => setListOpen((o) => !o)}
                >
                  {GmSvg.chevronDown}
                </button>
              </div>
              <div
                className="gm-member-options"
                id="gm-member-options"
                ref={listRef}
                hidden={!listOpen || !options.length}
              >
                {options.map((o) => (
                  <button
                    type="button"
                    key={o.userId}
                    onClick={() => {
                      setPicked((p) => [...p, o.userId]);
                      setQuery('');
                    }}
                  >
                    {o.name}
                  </button>
                ))}
              </div>
            </>
          )}
        </div>
        <footer>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            id="gm-members-confirm"
            disabled={byRotation && !chosen}
            onClick={() => onConfirm(picked, byRotation && chosen ? chosen.id : null)}
          >
            Confirm
          </button>
        </footer>
      </aside>
    </>
  );
}

/* --------------------------------------------- confirmation: redirect */

export function RedirectPicker({
  value,
  onChange,
}: {
  /** The address chosen; empty: none yet. */
  value: string;
  onChange: (url: string) => void;
}) {
  const [menu, setMenu] = useState(false);
  const [q, setQ] = useState('');
  const [adding, setAdding] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!menu) return;
    const onDown = (e: MouseEvent) => {
      if (!wrapRef.current?.contains(e.target as Node)) setMenu(false);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [menu]);

  const shown = value && (!q.trim() || value.toLowerCase().includes(q.trim().toLowerCase()));
  return (
    <div className="gm-confirmation-redirect" id="gm-confirmation-redirect">
      <div className="gm-confirmation-location-wrap" ref={wrapRef}>
        <button
          type="button"
          className="gm-confirmation-location-trigger"
          id="gm-confirmation-location-trigger"
          aria-expanded={menu}
          onClick={() => {
            setQ('');
            setMenu((m) => !m);
          }}
        >
          <span>{value || 'Please select or add a location'}</span>
          {GmSvg.chevronDown}
        </button>
        {menu ? (
          <div className="gm-confirmation-location-menu" id="gm-confirmation-location-menu">
            <div className="gm-dropdown-search">
              <input
                type="search"
                id="gm-confirmation-location-search"
                placeholder="Search"
                aria-label="Search locations"
                value={q}
                autoFocus
                onChange={(e) => setQ(e.target.value)}
              />
            </div>
            {shown ? (
              <button
                type="button"
                className="gm-confirmation-location-option"
                data-location={value}
                onClick={() => setMenu(false)}
              >
                {value}
              </button>
            ) : null}
            <button
              type="button"
              className="gm-confirmation-add-external"
              id="gm-confirmation-add-external"
              onClick={() => {
                setMenu(false);
                setAdding(true);
              }}
            >
              ＋ Add external link
            </button>
          </div>
        ) : null}
      </div>
      {adding ? (
        <ExternalLinkModal
          initial={value}
          onClose={() => setAdding(false)}
          onAdd={(url) => {
            onChange(url);
            setAdding(false);
          }}
        />
      ) : null}
    </div>
  );
}

/** "Redirect to an external link" (`#gm-external-link-backdrop`). */
function ExternalLinkModal({
  initial,
  onClose,
  onAdd,
}: {
  initial: string;
  onClose: () => void;
  onAdd: (url: string) => void;
}) {
  const [text, setText] = useState(initial);
  const [touched, setTouched] = useState(false);
  const url = redirectUrlOf(text);
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div
      className="gm-external-link-backdrop"
      id="gm-external-link-backdrop"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <section
        className="gm-external-link-modal"
        role="dialog"
        aria-modal="true"
        aria-label="Redirect to an external link"
      >
        <header>
          <h2>Redirect to an external link</h2>
          <button
            type="button"
            className="modal__close"
            id="gm-external-link-close"
            aria-label="Close"
            onClick={onClose}
          >
            {GmSvg.close}
          </button>
        </header>
        <div className="gm-external-link-body">
          <p>
            Please enter a valid URL, like:
            <br />
            http://www.crm.com.
          </p>
          <input
            type="url"
            id="gm-external-link-input"
            placeholder="e.g. http://www.example.com"
            autoComplete="url"
            autoFocus
            maxLength={2048}
            value={text}
            onChange={(e) => setText(e.target.value)}
            onBlur={() => setTouched(true)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && url) onAdd(url);
            }}
          />
          <p
            className="gm-url-error"
            id="gm-external-link-error"
            hidden={!touched || !text.trim() || Boolean(url)}
          >
            Please enter a valid URL.
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            id="gm-external-link-add"
            disabled={!url}
            onClick={() => url && onAdd(url)}
          >
            Add
          </button>
        </div>
      </section>
    </div>
  );
}

/* ------------------------------------------------ form: contact property */

export function ContactPropertyEditor({
  properties,
  loading,
  onSave,
  onCancel,
}: {
  /** The properties not asked yet. */
  properties: readonly { name: string; label: string }[];
  loading: boolean;
  onSave: (property: { name: string; label: string }) => void;
  onCancel: () => void;
}) {
  const [menu, setMenu] = useState(false);
  const [q, setQ] = useState('');
  const [chosen, setChosen] = useState<{ name: string; label: string } | null>(null);
  const wrapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!menu) return;
    const onDown = (e: MouseEvent) => {
      if (!wrapRef.current?.contains(e.target as Node)) setMenu(false);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [menu]);

  const shown = properties.filter(
    (p) => !q.trim() || p.label.toLowerCase().includes(q.trim().toLowerCase()),
  );
  return (
    <div className="gm-contact-property-editor" id="gm-contact-property-editor">
      <label htmlFor="gm-contact-property-trigger">Add contact property</label>
      <div className="gm-contact-property-select-wrap" ref={wrapRef}>
        <button
          type="button"
          className="gm-contact-property-trigger"
          id="gm-contact-property-trigger"
          aria-expanded={menu}
          onClick={() => {
            setQ('');
            setMenu((m) => !m);
          }}
        >
          <span>{chosen?.label ?? 'Select a contact property'}</span>
          {GmSvg.chevronDown}
        </button>
        {menu ? (
          <div className="gm-contact-property-menu" id="gm-contact-property-menu">
            <div className="gm-dropdown-search">
              <input
                type="search"
                id="gm-contact-property-search"
                placeholder="Search"
                aria-label="Search contact properties"
                value={q}
                autoFocus
                onChange={(e) => setQ(e.target.value)}
              />
            </div>
            <div className="gm-contact-property-options" id="gm-contact-property-options">
              {loading ? (
                <p className="gm-help">Loading…</p>
              ) : shown.length ? (
                shown.map((p) => (
                  <button
                    type="button"
                    key={p.name}
                    className={cn(chosen?.name === p.name && 'is-selected')}
                    onClick={() => {
                      setChosen(p);
                      setMenu(false);
                    }}
                  >
                    {p.label}
                  </button>
                ))
              ) : (
                <p className="gm-help">No contact properties found</p>
              )}
            </div>
          </div>
        ) : null}
      </div>
      <div className="gm-inline-editor-actions">
        <button
          type="button"
          className="btn-crm btn-crm--outline"
          id="gm-contact-property-save"
          disabled={!chosen}
          onClick={() => chosen && onSave(chosen)}
        >
          Save
        </button>
        <button
          type="button"
          className="btn-crm btn-crm--outline"
          id="gm-contact-property-cancel"
          onClick={onCancel}
        >
          Cancel
        </button>
      </div>
    </div>
  );
}
