'use client';

import { useId, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import type { CustomSelectOption } from '@/components/crm/CustomSelect';

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

/** To, Cc, Bcc and Other guests: emails as chips with an "Add email" box. */
export function RecipientChips({
  value,
  onChange,
  options = [],
  label = 'Add recipient',
  autoFocus = false,
  onInvalidChange,
}: {
  value: string[];
  onChange: (next: string[]) => void;
  /** Known recipients, offered as the user types. */
  options?: readonly CustomSelectOption[];
  label?: string;
  autoFocus?: boolean;
  /** True while a bad address sits in the box, so the form can hold back sending. */
  onInvalidChange?: (invalid: boolean) => void;
}) {
  const listId = useId();
  const inputRef = useRef<HTMLInputElement>(null);
  const [draft, setDraft] = useState('');
  const [invalid, setInvalid] = useState(false);
  const chipText = (email: string) => options.find((o) => o.value === email)?.label ?? email;

  /** Adds what was typed. A bad address stays in the box to be fixed. */
  const commit = () => {
    // Handles pasted "Jane Doe <jane@x.co>, joe@x.co": with an address there, names are ignored.
    const words = draft.split(/[\s,;<>"]+/).filter(Boolean);
    const addresses = words.filter((w) => w.includes('@'));
    const parts = (addresses.length ? addresses : words).map((p) => p.toLowerCase());
    if (!parts.length) return;
    const bad = parts.filter((p) => !EMAIL_RE.test(p));
    const good = parts.filter((p) => EMAIL_RE.test(p) && !value.includes(p));
    if (good.length) onChange([...value, ...new Set(good)]);
    setDraft(bad.join(', '));
    setInvalid(bad.length > 0);
    onInvalidChange?.(bad.length > 0);
  };

  return (
    <div
      className="acx-chips"
      onClick={(e) => {
        if (e.target === e.currentTarget) inputRef.current?.focus();
      }}
    >
      {value.map((email) => (
        <span className="acx-chip" key={email}>
          {chipText(email)}
          <button
            type="button"
            aria-label={`Remove ${email}`}
            onClick={() => onChange(value.filter((v) => v !== email))}
          >
            <CrmIcon name="x" className="iconSize-14" />
          </button>
        </span>
      ))}
      <input
        ref={inputRef}
        className="acx-chips__input"
        autoComplete="off"
        placeholder="Add email"
        aria-label={label}
        aria-invalid={invalid}
        autoFocus={autoFocus}
        list={options.length ? listId : undefined}
        value={draft}
        onChange={(e) => {
          setDraft(e.target.value);
          setInvalid(false);
          onInvalidChange?.(false);
        }}
        onBlur={commit}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ',' || e.key === ';') {
            if (draft.trim()) {
              e.preventDefault();
              commit();
            }
          }
          if (e.key === 'Backspace' && !draft && value.length) {
            onChange(value.slice(0, -1));
          }
        }}
      />
      {options.length ? (
        <datalist id={listId}>
          {options
            .filter((o) => !value.includes(o.value))
            .map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
        </datalist>
      ) : null}
    </div>
  );
}
