'use client';

/**
 * Quick import's Step 2 (`data-integration-import-quick.php:260-364`): the toolbar (status filter
 * with counts, Clear filters, search), the mapping table the design's `createMappingTable` draws
 * (`.js:126-309`) and its empty state.
 */
import { Fragment, useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { cn } from '@/lib/utils/cn';
import {
  columnErrorCount,
  duplicateMappingProblem,
  duplicateRowError,
  propertyGroups,
  STATUS_FILTERS,
  SUGGESTED_GROUP,
  type ImportAs,
  type MappingRow,
  type QuickProperty,
  type StatusFilter,
} from '../quickImport';
import {
  EditIcon,
  ImportAsIcon,
  IqSelect,
  PlusIcon,
  RowChevron,
  StatusCell,
} from './quickImportParts';

export interface MappingProps {
  rows: MappingRow[];
  visible: MappingRow[];
  counts: Record<StatusFilter, number>;
  properties: QuickProperty[];
  filter: StatusFilter;
  onFilter: (f: StatusFilter) => void;
  search: string;
  onSearch: (q: string) => void;
  onReset: () => void;
  openMenu: string | null;
  setOpenMenu: (key: string | null) => void;
  onImportAs: (column: string, value: ImportAs) => void;
  onProperty: (column: string, field: string) => void;
  onEditValues: (column: string) => void;
  onFixErrors: (column: string) => void;
  /** Admins only (master's wizard gates "Create a property" on manage_settings). */
  onCreateProperty: ((column: string) => void) | null;
  /** The object imported; Contact unless Advanced imports says ("Company properties"). */
  objectName?: { singular: string; lower: string };
  /** Advanced imports' Mapping Guide chip: the row it points to, highlighted. */
  highlight?: string | null;
  /**
   * B5/B6: "Import as" options, Advanced imports with Companies or Deals ticked ("Company
   * properties", "Deal properties"). Left out: the object's properties and "Don't import column",
   * as before.
   */
  importAsOptions?: Array<{ value: ImportAs; label: string }>;
  /** B5: the properties a company column chooses from. */
  companyProperties?: QuickProperty[];
  /** B6: the properties a deal column chooses from. */
  dealProperties?: QuickProperty[];
  /** B7: the properties each extra object's column chooses from, by object (custom keys). */
  extraProperties?: Record<string, QuickProperty[]>;
}

const CONTACT_NAME = { singular: 'Contact', lower: 'contact' };

function Star() {
  return <span className="crm-text-brand crm-fw-bold crm-me-1">*</span>;
}

/** One table row (`.js:155-272`) with its hover popover (`.js:274-292`). */
function MappingTableRow({
  row,
  properties,
  openMenu,
  setOpenMenu,
  hovered,
  onHover,
  onImportAs,
  onProperty,
  onEditValues,
  onFixErrors,
  onCreateProperty,
  objectName = CONTACT_NAME,
  highlight,
  importAsOptions,
  companyProperties,
  dealProperties,
  extraProperties,
}: Omit<
  MappingProps,
  'rows' | 'visible' | 'counts' | 'filter' | 'onFilter' | 'search' | 'onSearch' | 'onReset'
> & {
  row: MappingRow;
  hovered: boolean;
  onHover: (on: boolean) => void;
}) {
  const [propQuery, setPropQuery] = useState('');
  const searchRef = useRef<HTMLInputElement>(null);
  const importKey = `import-as:${row.column}`;
  const propKey = `property:${row.column}`;
  const propOpen = openMenu === propKey;
  // Opening the menu clears and focuses its search (`.js:386-391`).
  useEffect(() => {
    if (!propOpen) return;
    setPropQuery('');
    searchRef.current?.focus();
  }, [propOpen]);
  const ignored = row.importAs === 'ignore';
  const hasProperty = !!row.property && !ignored;
  const active = openMenu === importKey || openMenu === propKey;
  const p = row.property;
  const duplicate = duplicateRowError(row);
  const asOptions = importAsOptions ?? [
    { value: 'contact' as const, label: `${objectName.singular} properties` },
    { value: 'ignore' as const, label: "Don't import column" },
  ];
  const asLabel = asOptions.find((o) => o.value === row.importAs)?.label ?? asOptions[0]!.label;
  const choices =
    row.importAs === 'contact' || row.importAs === 'ignore'
      ? properties
      : row.importAs === 'company' && companyProperties
        ? companyProperties
        : row.importAs === 'deal' && dealProperties
          ? dealProperties
          : (extraProperties?.[row.importAs] ?? []);

  return (
    <tr
      className={cn(
        'iq-map-row',
        active && 'is-active-row',
        highlight === row.column && 'iq-guide-highlight-row',
      )}
      data-status={row.status}
      data-column={row.column}
    >
      <td>
        <strong>{row.column}</strong>
      </td>
      <td className="iq-preview-cell">
        <div className="iq-preview-list">
          {row.preview.map((v, i) => (
            <div className="iq-preview-item" key={i}>
              {v}
            </div>
          ))}
        </div>
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm iq-edit-col-btn"
          data-action="edit-values"
          onClick={() => onEditValues(row.column)}
        >
          <EditIcon /> Edit column values
        </button>
      </td>
      <td className="iq-status-cell">
        <StatusCell
          ignored={ignored}
          errors={columnErrorCount(row.errors)}
          mapped={!!row.field && row.status !== 'unmapped'}
          onFix={() => onFixErrors(row.column)}
        />
      </td>
      <td>
        <div className={cn('custom-select-wrapper', openMenu === importKey && 'is-open')}>
          <button
            type="button"
            className="custom-select__trigger iq-table-select-trigger"
            title={asLabel}
            data-trigger="import-as"
            aria-expanded={openMenu === importKey}
            onClick={() => setOpenMenu(openMenu === importKey ? null : importKey)}
          >
            <span className="crm-d-flex crm-align-items-center crm-gap-2 custom-select__value">
              <ImportAsIcon ignored={ignored} />
              <span>{asLabel}</span>
            </span>
            <RowChevron />
          </button>
          <div className="custom-select__dropdown">
            <ul className="custom-select__options">
              {asOptions.map(({ value, label }) => (
                <li
                  key={value}
                  className={cn('custom-select__option', row.importAs === value && 'is-selected')}
                  data-opt-val={value}
                  onClick={() => {
                    onImportAs(row.column, value);
                    setOpenMenu(null);
                  }}
                >
                  <span className="custom-select__option-text">{label}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </td>
      <td>
        <div
          className={cn(
            'custom-select-wrapper iq-prop-wrapper',
            ignored && 'crm-opacity-50',
            openMenu === propKey && 'is-open',
          )}
        >
          <button
            type="button"
            className="custom-select__trigger iq-table-select-trigger iq-property-trigger"
            title={hasProperty ? p!.label : undefined}
            data-trigger="property"
            aria-expanded={openMenu === propKey}
            disabled={ignored}
            onClick={() => {
              onHover(false);
              setOpenMenu(openMenu === propKey ? null : propKey);
            }}
            onMouseEnter={() => {
              if (openMenu !== propKey) onHover(true);
            }}
            onMouseLeave={() => onHover(false)}
          >
            <span className={cn('custom-select__value', !hasProperty && 'crm-text-muted')}>
              {hasProperty ? <Star /> : null}
              {hasProperty ? p!.label : 'Choose or create a property'}
            </span>
            <RowChevron />
          </button>

          {hasProperty ? (
            <div
              className={cn('iq-property-popover', hovered && 'is-hovered')}
              onMouseEnter={() => onHover(true)}
              onMouseLeave={() => onHover(false)}
            >
              <h4 className="iq-popover-title">{p!.label}</h4>
              <p className="iq-popover-sub">* This property can be used to create new records.</p>
              <div className="iq-popover-meta-row">
                <span className="iq-popover-meta-lbl">Usage</span>
                <span className="iq-popover-meta-val">{p!.usage}</span>
              </div>
              <div className="iq-popover-meta-row">
                <span className="iq-popover-meta-lbl">Type</span>
                <span className="iq-popover-meta-val">{p!.typeLabel}</span>
              </div>
              <div className="iq-popover-meta-row">
                <span className="iq-popover-meta-lbl">Description</span>
                <span className="iq-popover-meta-val">{p!.description}</span>
              </div>
              <a href={p!.detailsHref} className="iq-popover-link">
                View property details
              </a>
            </div>
          ) : null}

          <div className="custom-select__dropdown iq-property-menu">
            <div className="custom-select__search">
              <input
                type="search"
                placeholder="Search property..."
                className="iq-prop-search-input"
                aria-label="Search properties"
                value={propQuery}
                onChange={(e) => setPropQuery(e.target.value)}
                ref={searchRef}
              />
            </div>
            <div className="iq-property-list">
              {propertyGroups(choices, propQuery).map((g) => (
                <Fragment key={g.title}>
                  <div className="iq-property-group-title">{g.title}</div>
                  {g.items.map((item) => (
                    <div
                      key={item.field}
                      className={cn(
                        'custom-select__option',
                        row.field === item.field && 'is-selected',
                      )}
                      data-prop-name={item.label}
                      onClick={() => {
                        onProperty(row.column, item.field);
                        setOpenMenu(null);
                      }}
                    >
                      <span className="custom-select__option-text">
                        {g.title === SUGGESTED_GROUP ? <Star /> : null}
                        {item.label}
                      </span>
                    </div>
                  ))}
                </Fragment>
              ))}
            </div>
            {onCreateProperty ? (
              <button
                type="button"
                className="iq-property-create-btn"
                data-action="create-property"
                onClick={() => {
                  setOpenMenu(null);
                  onCreateProperty(row.column);
                }}
              >
                <PlusIcon />
                Create new property · {row.column}
              </button>
            ) : null}
          </div>
        </div>
        {/* QA #414: another column maps to the same property; Next waits until it's fixed. */}
        {duplicate ? (
          <p className="field__error crm-d-block crm-mt-1 crm-mb-0">{duplicate}</p>
        ) : null}
      </td>
    </tr>
  );
}

export function QuickImportMapping(props: MappingProps) {
  const { counts, filter, onFilter, search, onSearch, onReset, visible, openMenu, setOpenMenu } =
    props;
  const lower = (props.objectName ?? CONTACT_NAME).lower;
  // The popover's hover bridge (`.js:94-108`): shown on enter, hidden 320 ms after leaving.
  const [hovered, setHovered] = useState<string | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const hover = (column: string, on: boolean) => {
    if (timer.current) clearTimeout(timer.current);
    if (on) setHovered(column);
    else timer.current = setTimeout(() => setHovered((h) => (h === column ? null : h)), 320);
  };
  const filterKey = 'status-filter';
  const current = STATUS_FILTERS.find((f) => f.value === filter)!;
  const duplicate = duplicateMappingProblem(props.rows);

  return (
    <>
      <div className="iq-mapping-toolbar">
        <div className="crm-d-flex crm-align-items-center crm-gap-3 crm-flex-wrap">
          <IqSelect
            id="iqStatusFilterWrap"
            wrapperClass="iq-status-filter-wrapper"
            open={openMenu === filterKey}
            onOpen={(o) => setOpenMenu(o ? filterKey : null)}
            value={filter}
            display={current.label}
            ids={{
              trigger: 'iqStatusFilterTrigger',
              value: 'iqStatusFilterVal',
              dropdown: 'iqStatusFilterMenu',
            }}
            options={STATUS_FILTERS.map((f) => ({
              value: f.value,
              text: f.label,
              content: (
                <>
                  <span className="custom-select__option-text">{f.label}</span>
                  <span className={`badge ${f.badge} crm-ms-auto`}>{counts[f.value]}</span>
                </>
              ),
            }))}
            onSelect={(v) => onFilter(v as StatusFilter)}
          />
          <button
            type="button"
            className="btn-crm btn-crm--ghost btn-crm--sm iq-clear-filters-btn"
            id="iqClearFiltersBtn"
            hidden={filter === 'all'}
            onClick={() => onFilter('all')}
          >
            Clear filters
          </button>
        </div>
        <div className="search-input iq-search-box">
          <CrmIcon name="search" className="iconSize-16" />
          <input
            className="input"
            type="search"
            id="iqColSearch"
            placeholder="Search columns"
            autoComplete="off"
            aria-label="Search columns"
            value={search}
            onChange={(e) => onSearch(e.target.value)}
          />
        </div>
      </div>

      {duplicate ? (
        <p className="field__error crm-d-block crm-mt-4 crm-mb-0" role="alert">
          {duplicate}
        </p>
      ) : null}

      <div className="card crm-p-0 crm-mt-4 iq-table-card">
        <div className="iq-table-responsive">
          <table className="crm-table iq-table" id="iqMappingTable">
            <thead>
              <tr>
                <th>Column header from file</th>
                <th>
                  Preview Information{' '}
                  <span title="Sample values extracted from the first rows of your file">
                    <CrmIcon name="info" className="iconSize-14" />
                  </span>
                </th>
                <th className="crm-text-center">Mapped</th>
                <th>
                  Import as{' '}
                  <span title={`Choose whether to import as a ${lower} property or ignore`}>
                    <CrmIcon name="info" className="iconSize-14" />
                  </span>
                </th>
                <th>CRM property</th>
              </tr>
            </thead>
            <tbody id="iqMappingTbody">
              {visible.map((row) => (
                <MappingTableRow
                  key={row.column}
                  {...props}
                  row={row}
                  hovered={hovered === row.column}
                  onHover={(on) => hover(row.column, on)}
                />
              ))}
            </tbody>
          </table>
        </div>

        <div className="iq-empty-state" id="iqEmptyState" hidden={visible.length > 0}>
          <div className="iq-empty-state__icon" aria-hidden="true">
            <CrmIcon name="search" className="iconSize-32" />
          </div>
          <p className="iq-empty-state__text">
            No columns match your search. Try a different search or adjust your filters.
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            id="iqResetFiltersEmptyBtn"
            onClick={onReset}
          >
            Reset search &amp; filters
          </button>
        </div>
      </div>
    </>
  );
}
