'use client';

import { useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils/cn';
import { durationLabel, DURATION_OPTIONS, MAX_DURATION, MIN_DURATION } from '../../scheduler';

/**
 * The create / edit scheduling page form's controls, drawn with create-meeting.css markup
 * (create-meeting.html and the selects create-meeting.js builds: gmEnhanceSearchSelect,
 * the duration multi-select, the custom duration dialog).
 */

/** The design's 16px line icons (create-meeting.html). */
export const GmSvg = {
  chevronDown: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="m4 6 4 4 4-4" />
    </svg>
  ),
  prev: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="m10 3-5 5 5 5" />
    </svg>
  ),
  next: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="m6 3 5 5-5 5" />
    </svg>
  ),
  info: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <circle cx="8" cy="8" r="6.1" />
      <path d="M8 7v4M8 4.7h.01" />
    </svg>
  ),
  search: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <circle cx="6.8" cy="6.8" r="4.6" />
      <path d="m10.2 10.2 3.2 3.2" />
    </svg>
  ),
  trash: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="M3 4h10M6 4V2.5h4V4m-5 0 .6 9h4.8L11 4M6.5 6.5v4M9.5 6.5v4" />
    </svg>
  ),
  check: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="m3 8 3 3 7-7" />
    </svg>
  ),
  pin: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="M13 6.7c0 3.2-5 7-5 7s-5-3.8-5-7a5 5 0 1 1 10 0Z" />
      <circle cx="8" cy="6.5" r="1.6" />
    </svg>
  ),
  lines: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="M3 3h10M3 6h10M3 9h6M3 12h8" />
    </svg>
  ),
  person: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <circle cx="8" cy="5" r="2.5" />
      <path d="M3 14c.2-2.7 2.1-4.2 5-4.2s4.8 1.5 5 4.2" />
    </svg>
  ),
  close: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="m4 4 8 8M12 4l-8 8" />
    </svg>
  ),
  /** `.gm-date-input-wrap` (Custom date range). */
  calendar: (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <rect x="2" y="3.5" width="12" height="11" rx="1" />
      <path d="M5 2v3M11 2v3M2 6.5h12" />
    </svg>
  ),
};

/**
 * The round robin welcome screen's "Default Image" (create-meeting.html `#gm-welcome-illustration`;
 * the design's own artwork, so its colours are the picture's, not theme tokens).
 */
export function GmWelcomeArt({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 120 100" aria-hidden="true">
      <rect
        x="24"
        y="28"
        width="54"
        height="48"
        rx="4"
        fill="#fff"
        stroke="#405a72"
        strokeWidth="2"
        transform="rotate(-12 51 52)"
      />
      <path d="M28 38 77 28M30 47 79 37M32 56 81 46M34 65 83 55" stroke="#e8a23a" strokeWidth="3" />
      <path d="M45 73 88 62 102 73 58 86Z" fill="#f5dca5" stroke="#405a72" strokeWidth="2" />
      <path d="m67 65 20-7 5 4-20 7Z" fill="#405a72" />
      <path d="m75 70 20-7 4 4-20 7Z" fill="#e8a23a" />
    </svg>
  );
}

export function GmInfo({ title }: { title: string }) {
  return (
    <span className="gm-info" title={title}>
      {GmSvg.info}
    </span>
  );
}

/** `.gm-switch`. */
export function GmSwitch({
  id,
  checked,
  onChange,
  disabled,
  title,
}: {
  id?: string;
  checked: boolean;
  onChange?: (on: boolean) => void;
  disabled?: boolean;
  title?: string;
}) {
  return (
    <label className={cn('gm-switch', disabled && 'is-disabled')} title={title}>
      <input
        id={id}
        type="checkbox"
        checked={checked}
        disabled={disabled}
        onChange={(e) => onChange?.(e.target.checked)}
      />
      <span />
    </label>
  );
}

/** Closes a menu on a click outside `ref`. */
function useOutside(open: boolean, ref: React.RefObject<HTMLElement | null>, close: () => void) {
  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (!ref.current?.contains(e.target as Node)) close();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') close();
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [open, ref, close]);
}

export interface GmOption {
  value: string;
  label: string;
  disabled?: boolean;
}

/** The design's searchable select (`.gm-search-select-wrap`, create-meeting.js gmEnhanceSearchSelect). */
export function GmSearchSelect({
  value,
  options,
  onChange,
  label,
  disabled,
  title,
  className,
}: {
  value: string;
  options: readonly GmOption[];
  onChange: (value: string) => void;
  label: string;
  disabled?: boolean;
  title?: string;
  className?: string;
}) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState('');
  const ref = useRef<HTMLDivElement>(null);
  useOutside(open, ref, () => setOpen(false));
  const current = options.find((o) => o.value === value);
  const term = q.trim().toLowerCase();
  return (
    <div className={cn('gm-search-select-wrap', className)} ref={ref}>
      <button
        type="button"
        className="gm-search-select-trigger"
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={label}
        disabled={disabled}
        title={title}
        onClick={() => {
          setQ('');
          setOpen((o) => !o);
        }}
      >
        <span>{current?.label ?? value}</span>
        {GmSvg.chevronDown}
      </button>
      {open ? (
        <div className="gm-search-select-menu">
          <div className="gm-dropdown-search">
            <input
              type="search"
              placeholder="Search"
              aria-label="Search options"
              value={q}
              onChange={(e) => setQ(e.target.value)}
              autoFocus
            />
            {GmSvg.search}
          </div>
          <div className="gm-search-select-options" role="listbox" aria-label={label}>
            {options
              .filter((o) => !term || o.label.toLowerCase().includes(term))
              .map((o) => (
                <button
                  type="button"
                  key={o.value}
                  role="option"
                  aria-selected={o.value === value}
                  className="gm-search-select-option"
                  disabled={o.disabled}
                  title={o.disabled ? 'Coming soon' : undefined}
                  onClick={() => {
                    onChange(o.value);
                    setOpen(false);
                  }}
                >
                  {o.label}
                </button>
              ))}
          </div>
        </div>
      ) : null}
    </div>
  );
}

/** "Duration options": chips, a searchable checkbox menu and "Add custom duration". */
export function DurationSelect({
  value,
  extra,
  onChange,
  onAddCustom,
}: {
  value: readonly number[];
  /** Lengths added with "Add custom duration" or saved on the page. */
  extra: readonly number[];
  onChange: (minutes: number[]) => void;
  onAddCustom: () => void;
}) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState('');
  const ref = useRef<HTMLDivElement>(null);
  useOutside(open, ref, () => setOpen(false));
  const all = [...new Set([...DURATION_OPTIONS, ...extra])].sort((a, b) => a - b);
  const toggle = (m: number, on: boolean) =>
    onChange(on ? [...value, m].sort((a, b) => a - b) : value.filter((v) => v !== m));
  const term = q.trim().toLowerCase();
  return (
    <div className="gm-multi-select gm-duration-select" id="gm-duration-select" ref={ref}>
      <div
        role="button"
        tabIndex={0}
        className="gm-select-trigger"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            setOpen((o) => !o);
          }
        }}
      >
        <span className="gm-duration-chips">
          {value.map((m) => (
            <span className="gm-duration-chip" key={m}>
              {durationLabel(m)}{' '}
              <button
                type="button"
                aria-label={`Remove ${durationLabel(m)}`}
                onClick={(e) => {
                  e.stopPropagation();
                  toggle(m, false);
                }}
              >
                ×
              </button>
            </span>
          ))}
        </span>
        {GmSvg.chevronDown}
      </div>
      {open ? (
        <div className="gm-multi-menu gm-duration-menu">
          <div className="gm-dropdown-search">
            <input
              type="search"
              placeholder="Search"
              aria-label="Search duration options"
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
            {GmSvg.search}
          </div>
          <div className="gm-duration-options">
            {all
              .filter((m) => !term || durationLabel(m).toLowerCase().includes(term))
              .map((m) => (
                <label key={m}>
                  <input
                    type="checkbox"
                    checked={value.includes(m)}
                    onChange={(e) => toggle(m, e.target.checked)}
                  />
                  {durationLabel(m)}
                </label>
              ))}
          </div>
          <button
            type="button"
            className="gm-inline-action gm-add-custom-duration"
            onClick={() => {
              setOpen(false);
              onAddCustom();
            }}
          >
            Add custom duration
          </button>
        </div>
      ) : null}
    </div>
  );
}

/** "Add custom duration" (`#gm-duration-backdrop`); the API takes 5 minutes to 8 hours. */
export function CustomDurationModal({
  open,
  onClose,
  onSave,
}: {
  open: boolean;
  onClose: () => void;
  onSave: (minutes: number) => void;
}) {
  const [hours, setHours] = useState('00');
  const [minutes, setMinutes] = useState('00');
  useEffect(() => {
    if (open) {
      setHours('00');
      setMinutes('00');
    }
  }, [open]);
  if (!open) return null;
  const total = Number(hours || 0) * 60 + Number(minutes || 0);
  const valid =
    Number(minutes || 0) >= 0 &&
    Number(minutes || 0) <= 59 &&
    total >= MIN_DURATION &&
    total <= MAX_DURATION;
  return (
    <div
      className="gm-modal-backdrop"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <section
        className="gm-standard-modal gm-custom-duration-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="gm-custom-duration-title"
      >
        <header>
          <h2 id="gm-custom-duration-title">Add custom duration</h2>
          <button type="button" className="modal__close" aria-label="Close" onClick={onClose}>
            {GmSvg.close}
          </button>
        </header>
        <div className="gm-standard-modal-body">
          <strong>Choose a custom meeting duration up to 8 hours</strong>
          <div className="gm-custom-duration-fields">
            <label>
              <input
                type="number"
                min={0}
                max={8}
                value={hours}
                aria-label="Hours"
                onChange={(e) => setHours(e.target.value)}
              />{' '}
              hours
            </label>
            <label>
              <input
                type="number"
                min={0}
                max={59}
                value={minutes}
                aria-label="Minutes"
                onChange={(e) => setMinutes(e.target.value)}
              />{' '}
              minutes
            </label>
          </div>
        </div>
        <footer>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={!valid}
            onClick={() => {
              onSave(total);
              onClose();
            }}
          >
            Save
          </button>
        </footer>
      </section>
    </div>
  );
}
