'use client';

/**
 * Quick import's pieces drawn with the design's markup (`data-integration-import-quick.php`):
 * its custom select (the kit's CustomSelect adds Clear / Done, which the design's selects don't
 * have), and the inline icons its JS writes.
 */
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { cn } from '@/lib/utils/cn';
import { matchesSearch } from '../quickImport';

export interface IqOption {
  value: string;
  /** The text matched by the search and shown on the trigger. */
  text: string;
  /** The option's inside; default: `<span class="custom-select__option-text">text</span>`. */
  content?: ReactNode;
}

/**
 * The design's `.custom-select-wrapper` (`.php:133-163`; opened by `.js:1667-1731`): one open at
 * a time (`open` / `onOpen` from the page), search hiding options with `is-hidden`.
 */
export function IqSelect({
  id,
  wrapperClass,
  triggerClass,
  open,
  onOpen,
  value,
  display,
  options,
  onSelect,
  search,
  listClass,
  ids,
}: {
  id?: string;
  wrapperClass?: string;
  triggerClass?: string;
  open: boolean;
  onOpen: (open: boolean) => void;
  value: string;
  display?: ReactNode;
  options: IqOption[];
  onSelect: (value: string) => void;
  /** The search box; `pill` is Number Format's (`.php:450-454`). */
  search?: { placeholder: string; aria: string; id?: string; pill?: boolean };
  listClass?: string;
  /** The design's ids on the trigger, value, dropdown and list. */
  ids?: { trigger?: string; value?: string; dropdown?: string; list?: string };
}) {
  const [query, setQuery] = useState('');
  const searchRef = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (!open) return;
    setQuery('');
    searchRef.current?.focus();
  }, [open]);
  const selected = options.find((o) => o.value === value);
  return (
    <div className={cn('custom-select-wrapper', wrapperClass, open && 'is-open')} id={id}>
      <button
        type="button"
        className={cn('custom-select__trigger', triggerClass)}
        id={ids?.trigger}
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={() => onOpen(!open)}
      >
        <span className="custom-select__value" id={ids?.value}>
          {display ?? selected?.text ?? ''}
        </span>
        <CrmIcon name="chevron-down" className="iconSize-14 custom-select__icon" />
      </button>
      <div className="custom-select__dropdown" id={ids?.dropdown}>
        {search ? (
          <div className={cn('custom-select__search', search.pill && 'iq-select-search-pill')}>
            {search.pill ? (
              <span className="iq-select-search-icon" aria-hidden="true">
                <CrmIcon name="search" className="iconSize-14" />
              </span>
            ) : null}
            <input
              ref={searchRef}
              type="search"
              placeholder={search.placeholder}
              id={search.id}
              aria-label={search.aria}
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
          </div>
        ) : null}
        <ul className={cn('custom-select__options', listClass)} role="listbox" id={ids?.list}>
          {options.map((o) => (
            <li
              key={o.value}
              className={cn(
                'custom-select__option',
                o.value === value && 'is-selected',
                query && !matchesSearch(o.text, query) && 'is-hidden',
              )}
              data-val={o.value}
              role="option"
              aria-selected={o.value === value}
              onClick={() => {
                onSelect(o.value);
                onOpen(false);
              }}
            >
              {o.content ?? <span className="custom-select__option-text">{o.text}</span>}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

/** A plain option for IqSelect. */
export const iqOption = (value: string, text = value): IqOption => ({ value, text });

/** The upload cloud (`.php:81-86`); Download template's has the arrow down (`.php:202-207`). */
export function CloudIcon({ size, down }: { size: 14 | 24; down?: boolean }) {
  return (
    <svg
      className={`icon iconSize-${size}`}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242" />
      <path d="M12 12v9" />
      <path d={down ? 'm8 17 4 4 4-4' : 'm8 16 4-4 4 4'} />
    </svg>
  );
}

const lucide = {
  xmlns: 'http://www.w3.org/2000/svg',
  width: 24,
  height: 24,
  viewBox: '0 0 24 24',
  fill: 'none',
  stroke: 'currentColor',
  strokeWidth: 1.5,
  strokeLinecap: 'round' as const,
  strokeLinejoin: 'round' as const,
};

const small = {
  viewBox: '0 0 24 24',
  fill: 'none',
  stroke: 'currentColor',
  strokeLinecap: 'round' as const,
  strokeLinejoin: 'round' as const,
};

/** The Mapped cell (`.js:160-176`). */
export function StatusCell({
  ignored,
  errors,
  mapped,
  onFix,
}: {
  ignored: boolean;
  errors: number;
  mapped: boolean;
  onFix: () => void;
}) {
  if (ignored) {
    return (
      <span className="iq-status-dot iq-status-dot--muted" title="Don't import">
        <svg {...lucide} className="lucide lucide-minus preview-icon">
          <path d="M5 12h14" />
        </svg>
      </span>
    );
  }
  if (errors > 0) {
    return (
      <>
        <span className="iq-status-dot iq-status-dot--warning" title={`${errors} errors detected`}>
          !
        </span>{' '}
        {/* A plain clickable span, as the design's (`.js:166`); the row's Fix errors stays the
            keyboard way in. */}
        <span className="iq-error-badge" data-action="fix-errors" onClick={onFix}>
          {errors} errors
        </span>
      </>
    );
  }
  if (mapped) {
    return (
      <span className="iq-status-dot iq-status-dot--success" title="Mapped">
        <svg className="icon iconSize-12" {...small} strokeWidth={2}>
          <path d="M20 6L9 17L4 12" />
        </svg>
      </span>
    );
  }
  return (
    <span className="iq-status-dot iq-status-dot--muted" title="Unmapped">
      <svg {...lucide} className="lucide lucide-circle-x preview-icon">
        <circle cx="12" cy="12" r="10" />
        <path d="m15 9-6 6" />
        <path d="m9 9 6 6" />
      </svg>
    </span>
  );
}

/** Import as: Contact properties / Don't import column (`.js:183-185`). */
export function ImportAsIcon({ ignored }: { ignored: boolean }) {
  return ignored ? (
    <svg className="icon iconSize-14" {...small} strokeWidth={1.8}>
      <circle cx="12" cy="12" r="9" />
      <line x1="8" y1="12" x2="16" y2="12" />
    </svg>
  ) : (
    <svg className="icon iconSize-14" {...small} strokeWidth={1.8}>
      <rect x="4" y="3" width="16" height="18" rx="2.5" />
      <circle cx="12" cy="10" r="2.5" />
      <path d="M8.5 16a3.5 3.5 0 0 1 7 0" />
    </svg>
  );
}

/** The row's chevron (`.js:207`, `:227`). */
export function RowChevron() {
  return (
    <svg className="icon iconSize-14 custom-select__icon" {...small} strokeWidth={1.8}>
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

/** Edit column values' pencil (`.js:196`). */
export function EditIcon() {
  return (
    <svg className="icon iconSize-14" {...small} strokeWidth={1.8}>
      <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" />
    </svg>
  );
}

/** Create new property's plus (`.js:266`). */
export function PlusIcon() {
  return (
    <svg className="icon iconSize-14" {...small} strokeWidth={1.8}>
      <path d="M12 5v14M5 12h14" />
    </svg>
  );
}

/** A bulk row's remove cross (`.js:1418`). */
export function RemoveIcon() {
  return (
    <svg className="icon iconSize-14" {...small} strokeWidth={1.8}>
      <path d="M18 6 6 18M6 6l12 12" />
    </svg>
  );
}
