'use client';

import { useRef, useState, type ReactNode } from 'react';
import { AnchoredPopover } from '@/components/crm/AnchoredPopover';
import { DmIcon } from '@/features/data-model/ui/icons';
import { cn } from '@/lib/utils/cn';

/** `.os-dd`: a toggle button and its menu (the design's data-os-dd). */
export function OsDropdown({
  label,
  className,
  menuClassName = 'os-pop os-pop--menu',
  width,
  align = 'start',
  disabled,
  ariaLabel,
  children,
}: {
  label: ReactNode;
  className: string;
  menuClassName?: string;
  width?: number;
  align?: 'start' | 'end';
  disabled?: boolean;
  ariaLabel?: string;
  children: (close: () => void) => ReactNode;
}) {
  const ref = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);
  const close = () => setOpen(false);
  return (
    <div className="os-dd">
      <button
        ref={ref}
        type="button"
        className={className}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={ariaLabel}
        disabled={disabled}
        onClick={() => setOpen((v) => !v)}
      >
        {label}
      </button>
      <AnchoredPopover
        open={open}
        anchorRef={ref}
        onClose={close}
        className={menuClassName}
        width={width}
        align={align}
        fitContent={!width}
      >
        {children(close)}
      </AnchoredPopover>
    </div>
  );
}

/** `os_select()`: a dropdown field. */
export function OsSelect({
  label,
  value,
  options,
  onChange,
  width,
  disabled,
}: {
  label: string;
  value: string;
  options: readonly string[];
  onChange?: (value: string) => void;
  width?: 'wide' | 'mid' | 'narrow';
  disabled?: boolean;
}) {
  return (
    <OsDropdown
      className={cn('os-select os-select--field', width && `os-select--${width}`)}
      ariaLabel={label}
      disabled={disabled}
      label={
        <>
          <span className="os-select__value">{value}</span>
          <DmIcon name="caret" size={18} />
        </>
      }
    >
      {(close) =>
        options.map((option) => (
          <button
            key={option}
            type="button"
            role="option"
            aria-selected={option === value}
            className={cn('os-menu__item', option === value && 'is-selected')}
            onClick={() => {
              onChange?.(option);
              close();
            }}
          >
            {option}
          </button>
        ))
      }
    </OsDropdown>
  );
}

/** `.os-tip`: the info icon; the text shows as the browser tooltip. */
export function Tip({ text }: { text: string }) {
  return (
    <span className="os-tip" tabIndex={0} title={text} aria-label={text}>
      <DmIcon name="info" size={14} />
    </span>
  );
}

/** Marks a setting the API can't save yet. */
export function Soon({ children = 'Coming soon' }: { children?: ReactNode }) {
  return <span className="os-soon">{children}</span>;
}

/** `os_check_row()`: checkbox + bold label + help, with optional content below. */
export function CheckRow({
  label,
  help,
  checked,
  onChange,
  disabled,
  indent,
  children,
}: {
  label: ReactNode;
  help?: ReactNode;
  checked: boolean;
  onChange?: (checked: boolean) => void;
  disabled?: boolean;
  indent?: boolean;
  children?: ReactNode;
}) {
  return (
    <label className={cn('os-opt-row', indent && 'os-opt-row--indent', disabled && 'is-off')}>
      <span className="check">
        <input
          type="checkbox"
          checked={checked}
          disabled={disabled}
          onChange={(e) => onChange?.(e.target.checked)}
        />
        <span className="check__box" aria-hidden />
      </span>
      <span>
        <b>{label}</b>
        {help ? <small>{help}</small> : null}
        {children}
      </span>
    </label>
  );
}

/** `os_switch_row()`. */
export function SwitchRow({
  label,
  help,
  checked,
  onChange,
  disabled,
}: {
  label: ReactNode;
  help?: ReactNode;
  checked: boolean;
  onChange?: (checked: boolean) => void;
  disabled?: boolean;
}) {
  return (
    <div className="os-switch-row">
      <label className="os-switch">
        <input
          type="checkbox"
          checked={checked}
          disabled={disabled}
          aria-label={typeof label === 'string' ? label : undefined}
          onChange={(e) => onChange?.(e.target.checked)}
        />
        <span className="os-switch__ui" aria-hidden />
      </label>
      <span>
        <b>{label}</b>
        {help ? <small>{help}</small> : null}
      </span>
    </div>
  );
}

export function RadioRow({
  name,
  checked,
  disabled,
  small,
  children,
}: {
  name: string;
  checked: boolean;
  disabled?: boolean;
  small?: boolean;
  children: ReactNode;
}) {
  return (
    <label className={cn('os-radio-row', small && 'os-radio-row--sm')}>
      <input type="radio" name={name} checked={checked} disabled={disabled} readOnly />
      {children}
    </label>
  );
}

type DisplayStyle = 'none' | 'dot' | 'badge';

/**
 * `os_style_cards()`: pipeline / lifecycle stage display colors. LP5: pipelines pick one (`value`,
 * `onChange`); without `onChange` the cards only show the current one (Lifecycle: Coming soon).
 */
export function StyleCards({
  disabled,
  value = 'none',
  onChange,
}: {
  disabled?: boolean;
  value?: DisplayStyle;
  onChange?: (value: DisplayStyle) => void;
}) {
  const card = (style: DisplayStyle, content: ReactNode) => (
    <button
      type="button"
      className={cn('os-style', value === style && 'is-active')}
      role="radio"
      aria-checked={value === style}
      disabled={disabled}
      onClick={onChange && value !== style ? () => onChange(style) : undefined}
    >
      {content}
    </button>
  );
  return (
    <div className="os-styles" role="radiogroup" aria-label="Display colors">
      {card('none', 'Text (no color)')}
      {card(
        'dot',
        <>
          <i className="os-style__dot" />
          Text with colored dot
        </>,
      )}
      {card('badge', <span className="os-style__badge">Text in colored badge</span>)}
    </div>
  );
}

/** The design's grey form thumbnail beside "Customize the 'Create X' form". */
export function FormThumb() {
  return (
    <span className="os-thumb" aria-hidden>
      <span className="os-thumb__grid">
        <i />
        <i />
        <i />
      </span>
      <span className="os-thumb__side">
        <i />
        <i />
        <i />
        <i />
      </span>
    </span>
  );
}
