'use client';

import { useEffect, useId, useRef, useState, type ReactNode } from 'react';
import { ownerDisplayName } from '@/features/owners/labels';
import type { Owner } from '@/features/owners/api.client';
import { isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { actionErrorText } from './shared';

const EMPTY_TEXT = new Set(['--', '—', '']);

/**
 * HUB-615: a record field edited in place, as on HubSpot's About card. Click the value to edit
 * it. A dropdown (`saveOn="change"`) saves as soon as a choice is picked; other inputs save on
 * Enter or when focus leaves the field. Esc cancels. `onSave` throws to keep the editor open
 * with the error under the input: an `Error` for a check the page made itself, or the API error
 * (409 shows "Someone else changed this, reload"). The page updates the record itself.
 */
export function InlineEdit<V>({
  label,
  display,
  canEdit,
  lockedTitle,
  initial,
  renderInput,
  onSave,
  saveOn = 'blur',
  dropdown = false,
}: {
  label: string;
  /** What the field shows when not editing. */
  display: ReactNode;
  canEdit: boolean;
  /** Why the field can't be edited, shown on hover. */
  lockedTitle?: string;
  /** The value the input starts with each time editing begins. */
  initial: () => V;
  renderInput: (input: { id: string; value: V; onChange: (value: V) => void }) => ReactNode;
  onSave: (value: V) => Promise<void>;
  saveOn?: 'change' | 'blur';
  /** A field with options: shows a caret instead of the pencil. */
  dropdown?: boolean;
}) {
  const id = useId();
  const editorRef = useRef<HTMLDivElement>(null);
  const busyRef = useRef(false);
  const [editing, setEditing] = useState(false);
  const [value, setValue] = useState<V | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Focus the input when editing starts, so leaving it saves.
  useEffect(() => {
    if (!editing) return;
    const first = editorRef.current?.querySelector<HTMLElement>(
      'input, select, textarea, [data-autofocus]',
    );
    if (first && document.activeElement !== first) first.focus();
  }, [editing]);

  const empty = typeof display === 'string' && EMPTY_TEXT.has(display.trim());

  if (!editing || value === null) {
    if (!canEdit) {
      return (
        <span className={cn('crm-inline__static', empty && 'is-empty')} title={lockedTitle}>
          {display}
        </span>
      );
    }
    return (
      <button
        type="button"
        className={cn('crm-inline__value', empty && 'is-empty')}
        title={`Edit ${label}`}
        onClick={() => {
          setValue(initial());
          setError(null);
          setEditing(true);
        }}
      >
        <span>{display}</span>
        {dropdown ? (
          <svg
            className="crm-inline__pen crm-inline__caret"
            viewBox="0 0 24 24"
            width="14"
            height="14"
            fill="currentColor"
            aria-hidden
          >
            <path d="M7 10l5 5 5-5z" />
          </svg>
        ) : (
          <svg
            className="crm-inline__pen"
            viewBox="0 0 24 24"
            width="12"
            height="12"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.8"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden
          >
            <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" />
          </svg>
        )}
      </button>
    );
  }

  const cancel = () => {
    setEditing(false);
    setError(null);
  };
  const commit = (next: V) => {
    if (busyRef.current) return;
    busyRef.current = true;
    setBusy(true);
    setError(null);
    onSave(next)
      .then(() => setEditing(false))
      .catch((err: unknown) =>
        setError(!isApiError(err) && err instanceof Error ? err.message : actionErrorText(err)),
      )
      .finally(() => {
        busyRef.current = false;
        setBusy(false);
      });
  };

  return (
    <div
      ref={editorRef}
      className={cn('crm-inline__editor', busy && 'is-busy')}
      role="group"
      aria-label={`Edit ${label}`}
      aria-busy={busy || undefined}
      onKeyDown={(e) => {
        if (e.key === 'Escape') {
          e.stopPropagation();
          if (!busyRef.current) cancel();
        } else if (e.key === 'Enter' && !(e.target instanceof HTMLTextAreaElement)) {
          e.preventDefault();
          commit(value);
        }
      }}
      onBlur={(e) => {
        // Moving between this field's own inputs (checkboxes, first/last name) keeps it open.
        if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
        if (busyRef.current) return;
        if (saveOn === 'change') cancel();
        else commit(value);
      }}
    >
      {renderInput({
        id,
        value,
        onChange: (next) => {
          setValue(next);
          if (saveOn === 'change') commit(next);
        },
      })}
      {error ? (
        <p className="crm-inline__error" role="alert">
          {error}
        </p>
      ) : (
        <p className="crm-inline__hint">
          {saveOn === 'change' ? 'Pick a value · Esc to cancel' : 'Enter to save · Esc to cancel'}
        </p>
      )}
    </div>
  );
}

/**
 * Owner choices: active owners, plus the record's current owner when deactivated (so the
 * select can still show it).
 */
export function ownerChoices(
  owners: Owner[],
  current: { id: string; name: string } | null,
): Array<{ value: string; label: string }> {
  const list = owners
    .filter((o) => o.active || o.userId === current?.id)
    .map((o) => ({ value: o.userId, label: ownerDisplayName(o) }));
  if (current && !list.some((o) => o.value === current.id)) {
    list.push({ value: current.id, label: current.name });
  }
  return list;
}

/** Picklist choices: active options, plus the current value when it was archived. */
export function picklistChoices(
  options: Array<{ value: string; label: string; archived?: boolean }>,
  current: string | null,
): Array<{ value: string; label: string }> {
  const list = options.filter((o) => !o.archived).map((o) => ({ value: o.value, label: o.label }));
  if (current && !list.some((o) => o.value === current)) {
    list.push({
      value: current,
      label: options.find((o) => o.value === current)?.label ?? current,
    });
  }
  return list;
}

/** A plain text input for `InlineEdit`, focused when editing begins. */
export function InlineTextInput({
  id,
  value,
  onChange,
  type = 'text',
  maxLength,
}: {
  id: string;
  value: string;
  onChange: (value: string) => void;
  type?: 'text' | 'email' | 'tel' | 'number' | 'date';
  maxLength?: number;
}) {
  return (
    <input
      className="input"
      id={id}
      type={type}
      step={type === 'number' ? 'any' : undefined}
      maxLength={maxLength}
      autoFocus
      value={value}
      onChange={(e) => onChange(e.target.value)}
    />
  );
}

type DropdownOption = { value: string; label: string };

/**
 * HUB-615: the option list of a dropdown field, open as soon as editing starts (HubSpot's
 * "-- ▾"). Single choice: picking an option calls `onChange` (the field saves on change).
 * `multiple`: checkboxes, saved when focus leaves the field. A search box shows for long
 * lists. The list sits in the card's flow, so a card's `overflow: hidden` never clips it.
 */
export function InlineDropdown({
  id,
  value,
  onChange,
  options,
  emptyLabel,
  multiple = false,
}: {
  id: string;
  value: string | string[];
  onChange: (value: string | string[]) => void;
  options: DropdownOption[];
  /** Single choice: adds a first "no value" choice. */
  emptyLabel?: string;
  multiple?: boolean;
}) {
  const [search, setSearch] = useState('');
  const picked = Array.isArray(value) ? value : value ? [value] : [];
  const choices: DropdownOption[] =
    !multiple && emptyLabel !== undefined
      ? [{ value: '', label: emptyLabel }, ...options]
      : options;
  const q = search.trim().toLowerCase();
  const shown = q ? choices.filter((o) => o.label.toLowerCase().includes(q)) : choices;
  const [active, setActive] = useState(() =>
    Math.max(
      0,
      choices.findIndex((o) => (multiple ? false : o.value === (picked[0] ?? ''))),
    ),
  );
  const listRef = useRef<HTMLUListElement>(null);
  const searchable = choices.length > 7;

  useEffect(() => {
    listRef.current
      ?.querySelector<HTMLElement>(`[data-index="${active}"]`)
      ?.scrollIntoView({ block: 'nearest' });
  }, [active]);

  const choose = (option: DropdownOption) => {
    if (!multiple) {
      onChange(option.value);
      return;
    }
    const next = picked.includes(option.value)
      ? picked.filter((v) => v !== option.value)
      : options.map((o) => o.value).filter((v) => v === option.value || picked.includes(v));
    onChange(next);
  };

  const selectedLabel = multiple
    ? picked.map((v) => options.find((o) => o.value === v)?.label ?? v).join(', ')
    : (choices.find((o) => o.value === (picked[0] ?? ''))?.label ?? picked[0] ?? '');

  return (
    <div
      className="crm-inline-dd"
      id={id}
      onKeyDown={(e) => {
        if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
          e.preventDefault();
          e.stopPropagation();
          setActive((i) =>
            Math.min(Math.max(i + (e.key === 'ArrowDown' ? 1 : -1), 0), shown.length - 1),
          );
        } else if (e.key === 'Enter' && shown[active] && (!multiple || !e.ctrlKey)) {
          // Enter picks the highlighted option; in a multi-select, Ctrl+Enter saves.
          e.preventDefault();
          e.stopPropagation();
          choose(shown[active]);
        }
      }}
    >
      <div className="crm-inline-dd__trigger">
        <span className={cn(!selectedLabel && 'is-empty')}>{selectedLabel || '--'}</span>
        <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden>
          <path d="M7 14l5-5 5 5z" />
        </svg>
      </div>
      <div className="crm-inline-dd__panel">
        {searchable ? (
          <input
            className="crm-inline-dd__search"
            type="search"
            placeholder="Search"
            aria-label="Search options"
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setActive(0);
            }}
          />
        ) : null}
        <ul
          ref={listRef}
          className="crm-inline-dd__list"
          role="listbox"
          aria-multiselectable={multiple || undefined}
          tabIndex={-1}
          data-autofocus={searchable ? undefined : ''}
          // Keep focus in the field while clicking options (leaving it saves or cancels).
          onMouseDown={(e) => e.preventDefault()}
        >
          {shown.map((option, index) => {
            const isPicked = multiple
              ? picked.includes(option.value)
              : option.value === (picked[0] ?? '');
            return (
              <li
                key={option.value || '__empty'}
                data-index={index}
                role="option"
                aria-selected={isPicked}
                className={cn(
                  'crm-inline-dd__option',
                  isPicked && 'is-selected',
                  index === active && 'is-active',
                  !option.value && 'is-empty',
                )}
                onMouseEnter={() => setActive(index)}
                onClick={() => choose(option)}
              >
                {multiple ? (
                  <span className={cn('crm-inline-dd__check', isPicked && 'is-on')} aria-hidden />
                ) : null}
                <span>{option.label}</span>
              </li>
            );
          })}
          {shown.length === 0 ? <li className="crm-inline-dd__none">No matches</li> : null}
        </ul>
      </div>
    </div>
  );
}

/** A single-choice dropdown for `InlineEdit` (use `saveOn="change"`); `emptyLabel` adds "no value". */
export function InlineSelectInput({
  id,
  value,
  onChange,
  options,
  emptyLabel,
}: {
  id: string;
  value: string;
  onChange: (value: string) => void;
  options: DropdownOption[];
  emptyLabel?: string;
}) {
  return (
    <InlineDropdown
      id={id}
      value={value}
      onChange={(v) => onChange(Array.isArray(v) ? (v[0] ?? '') : v)}
      options={options}
      emptyLabel={emptyLabel}
    />
  );
}
