'use client';

/**
 * The reply's recipients as the design draws them (inbox-hs.js renderComposer): To chips with
 * the reply icon, "Cc" / "Bcc" buttons that open their own rows (`showCc` / `showBcc`), each a
 * box of address chips. Typing an address and pressing Enter, comma or Tab (or leaving the box)
 * adds it; Backspace in an empty box removes the last one. A box can offer addresses: ones found
 * while typing (`suggest`) and ones to choose from its triangle (`choices`).
 */
import { useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils/cn';
import { cleanAddress } from '../conversation';
import { IxIcon, Tri } from './ix';

/** An address a recipient box offers. */
export interface RecipientChoice {
  email: string;
  label: string;
}

export interface Recipients {
  to: string[];
  cc: string[];
  bcc: string[];
  showCc: boolean;
  showBcc: boolean;
}

type Field = 'to' | 'cc' | 'bcc';
const LABEL: Record<Field, string> = { to: 'recipient', cc: 'Cc recipient', bcc: 'Bcc recipient' };

export function ChipBox({
  field,
  values,
  disabled,
  onChange,
  onInvalid,
  suggest,
  choices,
}: {
  field: Field;
  values: string[];
  disabled: boolean;
  onChange: (next: string[]) => void;
  onInvalid: (value: string) => void;
  suggest?: (query: string) => Promise<RecipientChoice[]>;
  choices?: RecipientChoice[];
}) {
  const [text, setText] = useState('');
  const [found, setFound] = useState<RecipientChoice[]>([]);
  const [choosing, setChoosing] = useState(false);
  const suggestRef = useRef(suggest);
  suggestRef.current = suggest;

  const query = text.trim();
  useEffect(() => {
    setFound([]);
    if (query.length < 2) return;
    let alive = true;
    const timer = window.setTimeout(() => {
      suggestRef.current?.(query).then(
        (list) => alive && setFound(list),
        () => {}, // suggestions are optional
      );
    }, 250);
    return () => {
      alive = false;
      window.clearTimeout(timer);
    };
  }, [query]);

  const offered = (choosing ? (choices ?? []) : found).filter((c) => !values.includes(c.email));
  const pick = (email: string) => {
    onChange([...new Set([...values, email.toLowerCase()])]);
    setText('');
    setChoosing(false);
  };
  const commit = () => {
    const raw = text.trim();
    if (!raw) return true;
    const added: string[] = [];
    for (const part of raw.split(/[,;\s]+/).filter(Boolean)) {
      const email = cleanAddress(part);
      if (!email) {
        onInvalid(part);
        return false;
      }
      added.push(email);
    }
    onChange([...new Set([...values, ...added])]);
    setText('');
    return true;
  };
  return (
    <div className={cn('ix-chips ix-chips--box')} data-box={field} style={{ position: 'relative' }}>
      {values.map((email, i) => (
        <span key={email} className="ix-chip">
          <span className="ix-chip__t" title={email}>
            {email}
          </span>
          <button
            type="button"
            aria-label={`Remove ${email}`}
            disabled={disabled}
            onClick={() => onChange(values.filter((_, j) => j !== i))}
          >
            <IxIcon name="x" className="ix-i--xs" />
          </button>
        </span>
      ))}
      <input
        type="text"
        // typing gets room of its own; the size never depends on focus, so a click elsewhere
        // can't move the button being clicked
        className={cn('ix-chips__in', text && 'is-typing')}
        placeholder={values.length ? '' : 'Enter a recipient'}
        aria-label={`Add ${LABEL[field]}`}
        autoComplete="off"
        disabled={disabled}
        value={text}
        onChange={(e) => {
          setChoosing(false);
          setText(e.target.value);
        }}
        onBlur={() => {
          setChoosing(false);
          void commit();
        }}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ',' || e.key === ';' || (e.key === 'Tab' && text)) {
            if (e.key !== 'Tab' || text.trim()) e.preventDefault();
            commit();
          } else if (e.key === 'Backspace' && !text && values.length) {
            onChange(values.slice(0, -1));
          } else if (e.key === 'Escape' && (choosing || found.length)) {
            e.stopPropagation();
            setChoosing(false);
            setFound([]);
          }
        }}
      />
      {choices?.length ? (
        <button
          type="button"
          className="ix-chips__chv"
          aria-label={`Choose ${LABEL[field]}`}
          aria-expanded={choosing}
          tabIndex={-1}
          disabled={disabled}
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => setChoosing((v) => !v)}
        >
          <Tri />
        </button>
      ) : null}
      {offered.length ? (
        <div
          className="dropdown__menu ix-suggest"
          role="listbox"
          aria-label={`Suggested ${LABEL[field]}s`}
        >
          {offered.map((c) => (
            <button
              key={c.email}
              type="button"
              className="dropdown__item"
              role="option"
              aria-selected={false}
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => pick(c.email)}
            >
              {c.label}
            </button>
          ))}
        </div>
      ) : null}
    </div>
  );
}

export function RecipientRows({
  value,
  disabled,
  onChange,
  onInvalid,
  suggest,
  choices,
  trailing,
}: {
  value: Recipients;
  disabled: boolean;
  onChange: (next: Recipients) => void;
  onInvalid: (text: string) => void;
  suggest?: (query: string) => Promise<RecipientChoice[]>;
  choices?: RecipientChoice[];
  /** After Cc / Bcc on the first row (the design's "Show From and Subject"). */
  trailing?: React.ReactNode;
}) {
  const set = (field: Field) => (list: string[]) => onChange({ ...value, [field]: list });
  const hasSub = value.showCc || value.showBcc;
  return (
    <>
      <div className={cn('ix-comp__to', hasSub && 'ix-comp__to--has-sub')}>
        <span className="ix-comp__rt" title="Reply">
          <IxIcon name="reply" className="ix-i--sm" />
        </span>
        <ChipBox
          field="to"
          values={value.to}
          disabled={disabled}
          onChange={set('to')}
          onInvalid={onInvalid}
          suggest={suggest}
          choices={choices}
        />
        {/* together, so they never end up on lines of their own */}
        <div className="ix-comp__after">
          {!value.showCc || !value.showBcc ? (
            <div className="ix-comp__cc-actions">
              {!value.showCc ? (
                <button
                  type="button"
                  className="ix-comp__cc-btn"
                  aria-label="Add Cc"
                  disabled={disabled}
                  onClick={() => onChange({ ...value, showCc: true })}
                >
                  Cc
                </button>
              ) : null}
              {!value.showBcc ? (
                <button
                  type="button"
                  className="ix-comp__cc-btn"
                  aria-label="Add Bcc"
                  disabled={disabled}
                  onClick={() => onChange({ ...value, showBcc: true })}
                >
                  Bcc
                </button>
              ) : null}
            </div>
          ) : null}
          {trailing}
        </div>
      </div>
      {value.showCc ? (
        <div className="ix-comp__to ix-comp__to--sub">
          <span className="ix-comp__lbl">Cc</span>
          <ChipBox
            field="cc"
            values={value.cc}
            disabled={disabled}
            onChange={set('cc')}
            onInvalid={onInvalid}
            suggest={suggest}
          />
        </div>
      ) : null}
      {value.showBcc ? (
        <div className="ix-comp__to ix-comp__to--sub">
          <span className="ix-comp__lbl">Bcc</span>
          <ChipBox
            field="bcc"
            values={value.bcc}
            disabled={disabled}
            onChange={set('bcc')}
            onInvalid={onInvalid}
            suggest={suggest}
          />
        </div>
      ) : null}
    </>
  );
}
