'use client';

import { useEffect, useId, useMemo, useRef, useState } from 'react';
import { cn } from '@/lib/utils/cn';
import type { CustomSelectOption } from './CustomSelect';

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

type MultiCustomSelectProps = {
  id?: string;
  name?: string;
  placeholder: string;
  value: string[];
  options: CustomSelectOption[];
  onChange: (value: string[]) => void;
  searchable?: boolean;
  disabled?: boolean;
  required?: boolean;
  className?: string;
  menuMinWidth?: number;
  /** Shown when 2+ items selected, e.g. "selected". */
  selectedText?: string;
  /** The closed trigger's text when something is selected (overrides `selectedText`). */
  formatSelected?: (labels: string[]) => string;
  /**
   * Allow typing an email in search and adding it (Enter / “Add …” row).
   * Values are stored lowercased.
   */
  allowCustomEmail?: boolean;
};

function ChevronIcon() {
  return (
    <svg
      className="custom-select__icon"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" aria-hidden>
      <path d="M5 12l5 5L20 7" />
    </svg>
  );
}

/** Design-system multi-select dropdown with search + checkboxes (custom-select.css). */
export function MultiCustomSelect({
  id,
  name,
  placeholder,
  value,
  options,
  onChange,
  searchable = true,
  disabled = false,
  required = false,
  className = '',
  menuMinWidth = 280,
  selectedText = 'selected',
  formatSelected,
  allowCustomEmail = false,
}: MultiCustomSelectProps) {
  const autoId = useId();
  const selectId = id ?? autoId;
  const rootRef = useRef<HTMLDivElement>(null);
  const searchRef = useRef<HTMLInputElement>(null);
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState('');

  const selectedSet = useMemo(() => new Set(value), [value]);

  /** Options with unique values (callers may pass duplicate emails). */
  const uniqueOptions = useMemo(() => {
    const seen = new Set<string>();
    return options.filter((o) => {
      if (seen.has(o.value)) return false;
      seen.add(o.value);
      return true;
    });
  }, [options]);

  const selectedItems = useMemo(
    () =>
      [...new Set(value)].map((v) => {
        const opt = uniqueOptions.find((o) => o.value === v);
        return { value: v, label: opt?.label ?? v };
      }),
    [value, uniqueOptions],
  );

  const display = useMemo(() => {
    if (selectedItems.length === 0) return placeholder;
    if (formatSelected) return formatSelected(selectedItems.map((item) => item.label));
    return `${selectedItems.length} ${selectedText}`;
  }, [selectedItems, placeholder, selectedText, formatSelected]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return uniqueOptions;
    return uniqueOptions.filter(
      (o) => o.label.toLowerCase().includes(q) || o.value.toLowerCase().includes(q),
    );
  }, [uniqueOptions, search]);

  const customEmail = useMemo(() => {
    if (!allowCustomEmail) return null;
    const raw = search.trim().toLowerCase();
    if (!EMAIL_RE.test(raw) || selectedSet.has(raw)) return null;
    const alreadyListed = uniqueOptions.some((o) => o.value.toLowerCase() === raw);
    if (alreadyListed) return null;
    return raw;
  }, [allowCustomEmail, search, selectedSet, uniqueOptions]);

  useEffect(() => {
    if (!open) {
      setSearch('');
      return;
    }
    const onDoc = (e: MouseEvent) => {
      if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    queueMicrotask(() => searchRef.current?.focus());
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const toggle = (optValue: string) => {
    if (selectedSet.has(optValue)) {
      onChange(value.filter((v) => v !== optValue));
    } else {
      onChange([...value, optValue]);
    }
  };

  const addCustom = (email: string) => {
    if (!EMAIL_RE.test(email) || selectedSet.has(email)) return;
    onChange([...value, email]);
    setSearch('');
  };

  const remove = (optValue: string) => {
    onChange(value.filter((v) => v !== optValue));
  };

  return (
    <div
      ref={rootRef}
      id={selectId}
      className={cn(
        'custom-select-wrapper custom-select-wrapper--multi crm-w-100',
        open && 'is-open',
        value.length > 0 && 'is-set',
        className,
      )}
      data-custom-select
      data-type="multi"
      data-placeholder={placeholder}
      data-search={searchable ? 'true' : undefined}
      data-show-checkbox="true"
    >
      {name ? (
        <input
          type="hidden"
          name={name}
          value={value.join(',')}
          required={required && value.length === 0}
        />
      ) : null}

      <button
        type="button"
        className="custom-select__trigger"
        disabled={disabled}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={placeholder}
        onClick={() => {
          if (!disabled) setOpen((v) => !v);
        }}
      >
        <span className="custom-select__value">{display}</span>
        <ChevronIcon />
      </button>

      {selectedItems.length > 0 ? (
        <ul className="custom-select__chips" aria-label="Selected">
          {selectedItems.map((item) => (
            <li key={item.value} className="custom-select__chip">
              <span className="custom-select__chip-label" title={item.label}>
                {item.label}
              </span>
              <button
                type="button"
                className="custom-select__chip-remove"
                aria-label={`Remove ${item.label}`}
                disabled={disabled}
                onClick={(e) => {
                  e.stopPropagation();
                  remove(item.value);
                }}
              >
                ×
              </button>
            </li>
          ))}
        </ul>
      ) : null}

      {open ? (
        <div
          className="custom-select__dropdown"
          style={{ minWidth: menuMinWidth }}
          role="listbox"
          aria-multiselectable
          aria-label={placeholder}
        >
          {searchable ? (
            <div className="custom-select__search">
              <input
                ref={searchRef}
                type="search"
                placeholder={allowCustomEmail ? 'Search or type an email' : 'Search'}
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                onClick={(e) => e.stopPropagation()}
                onKeyDown={(e) => {
                  if (e.key !== 'Enter') return;
                  e.preventDefault();
                  e.stopPropagation();
                  if (customEmail) addCustom(customEmail);
                }}
              />
            </div>
          ) : null}
          <ul className="custom-select__options">
            {customEmail ? (
              <li
                className="custom-select__option custom-select__option--create"
                role="option"
                aria-selected={false}
                onClick={(e) => {
                  e.stopPropagation();
                  addCustom(customEmail);
                }}
              >
                <span className="custom-select__option-text">Add {customEmail}</span>
              </li>
            ) : null}
            {filtered.map((opt) => {
              const selected = selectedSet.has(opt.value);
              return (
                <li
                  key={opt.value}
                  className={cn('custom-select__option', selected && 'is-selected')}
                  role="option"
                  aria-selected={selected}
                  data-value={opt.value}
                  onClick={(e) => {
                    e.stopPropagation();
                    toggle(opt.value);
                  }}
                >
                  <span className="custom-select__checkbox" aria-hidden>
                    <CheckIcon />
                  </span>
                  <span className="custom-select__option-text">{opt.label}</span>
                </li>
              );
            })}
            {filtered.length === 0 && !customEmail ? (
              <li className="custom-select__option" style={{ cursor: 'default', opacity: 0.65 }}>
                <span className="custom-select__option-text">
                  {allowCustomEmail ? 'No matches — type a full email to add' : 'No matches'}
                </span>
              </li>
            ) : null}
          </ul>
          <div className="custom-select__actions">
            <button
              type="button"
              className="custom-select__btn custom-select__btn--clear"
              onClick={(e) => {
                e.stopPropagation();
                onChange([]);
                setSearch('');
              }}
            >
              Clear
            </button>
            <button
              type="button"
              className="custom-select__btn custom-select__btn--done"
              onClick={(e) => {
                e.stopPropagation();
                setOpen(false);
              }}
            >
              Done
            </button>
          </div>
        </div>
      ) : null}
    </div>
  );
}
