'use client';

/**
 * Quick import's side drawers (`data-integration-import-quick.php:732-1083`): Edit column values,
 * Fix import errors and Create new property. Replacements are the import's real value map
 * (`options.valueMap`), from the preview rows; Create property posts the property.
 */
import { useState, type ReactNode } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import {
  createCustomProperty,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import type { ImportPreview } from '@/features/imports/types';
import { distinctValues } from '@/features/imports/values';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  canBeUnique,
  createPropertyBody,
  createPropertyProblem,
  editRows,
  editsFromRows,
  columnErrorCount,
  editsWithFixes,
  fixChoices,
  fixErrorsText,
  guessedChoices,
  guessPropertyType,
  IGNORE_CHOICE,
  MAX_UNIQUE,
  NEW_PROPERTY_TYPES,
  NUMBER_DISPLAYS,
  replacementOptions,
  type EditRow,
  type MappingRow,
  type QuickEdits,
} from '../quickImport';
import { iqOption, IqSelect, PlusIcon, RemoveIcon } from './quickImportParts';

type Rows = ImportPreview['previewRows'];

const rowsText = (n: number) => `${n} ${n === 1 ? 'row' : 'rows'} with this value`;

/** The drawer frame (`.php:736-788`): backdrop click and the close buttons close it. */
export function Drawer({
  id,
  open,
  onClose,
  children,
}: {
  id: string;
  open: boolean;
  onClose: () => void;
  children: ReactNode;
}) {
  return (
    <div
      className={cn('modal-backdrop modal-backdrop--drawer sidedrawer', open && 'is-open')}
      id={id}
      aria-modal="true"
      role="dialog"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="modal modal--lg sidedrawer__panel">{children}</div>
    </div>
  );
}

function DrawerClose({ onClose }: { onClose: () => void }) {
  return (
    <button
      type="button"
      className="drawer-close modal__close"
      data-close-drawer
      aria-label="Close drawer"
      onClick={onClose}
    >
      <CrmIcon name="x" className="iconSize-18" />
    </button>
  );
}

function DrawerFoot({
  onClose,
  doneId,
  doneLabel,
  onDone,
  busy,
}: {
  onClose: () => void;
  doneId: string;
  doneLabel: string;
  onDone: () => void;
  busy?: boolean;
}) {
  return (
    <div className="modal__footer sidedrawer__footer">
      <button
        type="button"
        className="btn-crm btn-crm--outline"
        data-close-drawer
        onClick={onClose}
      >
        Cancel
      </button>
      <button
        type="button"
        className="btn-crm btn-crm--primary"
        id={doneId}
        disabled={busy}
        onClick={onDone}
      >
        {doneLabel}
      </button>
    </div>
  );
}

/** "Auto fix errors" (checked in the design) and "Reset all changes" (`.php:771-781`). */
function DrawerTools({
  checkId,
  resetId,
  onSoon,
  onReset,
}: {
  checkId: string;
  resetId: string;
  onSoon: (label: string) => void;
  onReset: () => void;
}) {
  return (
    <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-mt-5 crm-pt-4 iq-border-top">
      <label className="check">
        <input type="checkbox" id={checkId} checked onChange={() => onSoon('Auto fix errors')} />
        <span className="check__box"></span>
        <span className="crm-fs-7 crm-text">Auto fix errors</span>
      </label>
      <button
        type="button"
        className="btn-crm btn-crm--ghost btn-crm--sm"
        id={resetId}
        onClick={onReset}
      >
        Reset all changes
      </button>
    </div>
  );
}

export interface DrawerMenus {
  openMenu: string | null;
  setOpenMenu: (key: string | null) => void;
}

/** Edit column values (`.php:736-788`, `.js:1373-1491`). */
export function EditValuesBody({
  row,
  rows,
  edits,
  onDone,
  onClose,
  onSoon,
  openMenu,
  setOpenMenu,
}: DrawerMenus & {
  row: MappingRow;
  rows: Rows;
  edits: QuickEdits;
  onDone: (next: Record<string, string>) => void;
  onClose: () => void;
  onSoon: (label: string) => void;
}) {
  const initial = () => editRows(rows, row.column, edits, row.property);
  const [draft, setDraft] = useState<EditRow[]>(initial);
  const choices = replacementOptions(rows, row.column, row.property);
  const set = (i: number, patch: Partial<EditRow>) =>
    setDraft((d) => d.map((r, j) => (j === i ? { ...r, ...patch } : r)));

  return (
    <>
      <div className="modal__header sidedrawer__header">
        <div>
          <h3 className="modal__title sidedrawer__title">Edit column values</h3>
          <p className="crm-fs-8 crm-text-muted crm-m-0" id="iqEditDrawerSubhead">
            Column header from file: <strong id="iqEditColName">{row.column}</strong> · Property:{' '}
            <strong id="iqEditPropName">{row.property?.label ?? row.column}</strong> (
            {row.property?.typeLabel ?? '--'})
          </p>
        </div>
        <DrawerClose onClose={onClose} />
      </div>
      <div className="modal__body sidedrawer__body">
        <div className="iq-drawer-section sidedrawer__section">
          <h4 className="iq-drawer-section__title sidedrawer__section-title">
            Replace column values in bulk
          </h4>
          <div className="iq-bulk-table-wrap">
            <div className="iq-bulk-head">
              <span className="iq-bulk-col">Column value</span>
              <span className="iq-bulk-col">Replacement value</span>
            </div>
            <div className="iq-bulk-rows" id="iqBulkRowsList">
              {draft.map((r, i) => {
                const key = `edit:${i}`;
                const added = r.count === null;
                const same = (o: { value: string; label: string }) =>
                  [o.value, o.label].some((x) => x.toLowerCase() === r.source.toLowerCase());
                // The value unchanged first (`.js:1407`), then the other choices.
                const options = [
                  ...(added || !r.source ? [] : [iqOption(r.source)]),
                  ...choices
                    .filter((o) => added || !same(o))
                    .map((o) => iqOption(o.value, o.label)),
                  iqOption(IGNORE_CHOICE, "Don't import this value"),
                ];
                return (
                  <div className="iq-bulk-row" key={i}>
                    <div className="iq-bulk-col">
                      {added ? (
                        <input
                          type="text"
                          className="input crm-fs-7 crm-w-100"
                          placeholder="Error or select value"
                          value={r.source}
                          onChange={(e) => set(i, { source: e.target.value })}
                        />
                      ) : (
                        <>
                          <input
                            type="text"
                            className="input crm-fs-7 crm-w-100"
                            value={r.source}
                            readOnly
                          />
                          <span className="crm-fs-8 crm-text-muted crm-mt-1 crm-d-block">
                            {rowsText(r.count!)}
                          </span>
                        </>
                      )}
                    </div>
                    <div className="iq-bulk-arrow" aria-hidden="true">
                      →
                    </div>
                    <div className="iq-bulk-col">
                      <IqSelect
                        wrapperClass="crm-w-100 iq-bulk-select"
                        triggerClass="crm-w-100"
                        open={openMenu === key}
                        onOpen={(o) => setOpenMenu(o ? key : null)}
                        value={r.choice}
                        display={
                          options.find((o) => o.value === r.choice)?.text ?? 'Replacement value...'
                        }
                        options={options}
                        onSelect={(v) => set(i, { choice: v })}
                      />
                    </div>
                    <button
                      type="button"
                      className="iq-bulk-row-remove"
                      aria-label="Remove replacement"
                      onClick={() => setDraft((d) => d.filter((_, j) => j !== i))}
                    >
                      <RemoveIcon />
                    </button>
                  </div>
                );
              })}
            </div>
            <div className="crm-mt-3">
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                id="iqAddBulkRowBtn"
                onClick={() => setDraft((d) => [...d, { source: '', choice: '', count: null }])}
              >
                <PlusIcon /> Replace another value
              </button>
            </div>
          </div>
        </div>
        <DrawerTools
          checkId="iqAutoFixCheck"
          resetId="iqResetEditsBtn"
          onSoon={onSoon}
          onReset={() => setDraft(editRows(rows, row.column, {}, row.property))}
        />
      </div>
      <DrawerFoot
        onClose={onClose}
        doneId="iqSaveBulkEditsBtn"
        doneLabel="Done"
        onDone={() => onDone(editsFromRows(draft))}
      />
    </>
  );
}

/** Fix import errors (`.php:794-922`, `.js:1494-1550`). */
export function FixErrorsBody({
  row,
  edits,
  onDone,
  onClose,
  onSoon,
  openMenu,
  setOpenMenu,
}: DrawerMenus & {
  row: MappingRow;
  edits: QuickEdits;
  onDone: (next: Record<string, string>) => void;
  onClose: () => void;
  onSoon: (label: string) => void;
}) {
  const { rows: errored, values } = row.errors;
  const options = row.property?.options ?? [];
  const label = row.property?.label ?? row.column;
  const [choices, setChoices] = useState(() => fixChoices(values, edits[row.column]));
  const [showErrored, setShowErrored] = useState(false);
  const count = `${columnErrorCount(row.errors)} errors`;
  const text = fixErrorsText(row.property, label);

  return (
    <>
      <div className="modal__header sidedrawer__header">
        <div>
          <h3 className="modal__title sidedrawer__title">Fix import errors</h3>
          <p className="crm-fs-8 crm-text-muted crm-m-0">
            Column: <strong id="iqFixColName">{row.column}</strong> ·{' '}
            <span className="badge badge--warning">{count}</span> · Property:{' '}
            <strong id="iqFixPropName">{label}</strong> ({row.property?.typeLabel ?? '--'})
          </p>
        </div>
        <DrawerClose onClose={onClose} />
      </div>
      <div className="modal__body sidedrawer__body">
        <div className="iq-error-box">
          <div className="iq-error-box__head">
            <h4 className="iq-error-box__title">{text.title}</h4>
            <span className="badge badge--warning">{count}</span>
          </div>
          <p className="iq-error-box__desc">{text.description}</p>
          <div className="crm-d-flex crm-gap-2 crm-mt-3">
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              id="iqToggleErroredValuesBtn"
              onClick={() => setShowErrored((s) => !s)}
            >
              <CrmIcon name="eye" className="iconSize-14" /> View errored values
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              id="iqQuickFixErrorsBtn"
              onClick={() => setChoices((c) => guessedChoices(c, options, !!row.property?.owners))}
            >
              Edit errored values
            </button>
          </div>
          <div className="iq-errored-table-wrap" id="iqErroredTableWrap" hidden={!showErrored}>
            <table className="crm-table iq-table iq-table--sm crm-mt-3">
              <thead>
                <tr>
                  <th>Row #</th>
                  <th>{label} (File Value)</th>
                </tr>
              </thead>
              <tbody>
                {errored.map((e) => (
                  <tr key={e.row}>
                    <td>{e.row}</td>
                    <td>
                      <span className="badge badge--warning">{e.value}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div className="iq-drawer-section sidedrawer__section crm-mt-5">
          <h4 className="iq-drawer-section__title sidedrawer__section-title">Fix errors</h4>
          <p className="crm-fs-7 crm-text-muted crm-mb-3">{text.fix}</p>
          <div className="iq-bulk-table-wrap">
            <div className="iq-bulk-head">
              <span className="iq-bulk-col">Column value</span>
              <span className="iq-bulk-col">Replacement value</span>
            </div>
            {values.map((v, i) => {
              const key = `fix:${i}`;
              const opts = [
                iqOption('', 'Choose an existing option...'),
                ...options.map((o) => iqOption(o.value, o.label)),
                iqOption(IGNORE_CHOICE, "Don't import this value"),
              ];
              return (
                <div className="iq-bulk-row" key={v.value}>
                  <div className="iq-bulk-col">
                    <input type="text" className="input crm-fs-7" value={v.value} readOnly />
                    <span className="crm-fs-8 crm-text-muted crm-mt-1 crm-d-block">
                      {rowsText(v.count)}
                    </span>
                  </div>
                  <div className="iq-bulk-arrow" aria-hidden="true">
                    →
                  </div>
                  <div className="iq-bulk-col">
                    <IqSelect
                      wrapperClass="crm-w-100"
                      triggerClass="crm-w-100"
                      open={openMenu === key}
                      onOpen={(o) => setOpenMenu(o ? key : null)}
                      value={choices[v.value] ?? ''}
                      options={opts}
                      onSelect={(next) => setChoices((c) => ({ ...c, [v.value]: next }))}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <DrawerTools
          checkId="iqAutoFixErrorsCheck"
          resetId="iqResetErrorFixesBtn"
          onSoon={onSoon}
          onReset={() => setChoices(fixChoices(values, undefined))}
        />
      </div>
      <DrawerFoot
        onClose={onClose}
        doneId="iqApplyErrorFixesBtn"
        doneLabel="Done"
        onDone={() => onDone(editsWithFixes(edits[row.column], choices))}
      />
    </>
  );
}

/** Create new property (`.php:928-1083`, `.js:1553-1607`), for admins. */
export function CreatePropertyBody({
  column,
  rows,
  uniqueUsed,
  taken,
  onCreated,
  onClose,
  onSoon,
  onError,
  openMenu,
  setOpenMenu,
  objectType,
}: DrawerMenus & {
  column: string;
  rows: Rows;
  /** The object the property is for; contacts unless Advanced imports says. */
  objectType?: string;
  /** Live unique properties of contacts. */
  uniqueUsed: number;
  /** Contacts' existing custom property names, so the new one gets a free name. */
  taken: string[];
  onCreated: (saved: CustomPropertyDefinition) => void;
  onClose: () => void;
  onSoon: (label: string) => void;
  onError: (message: string) => void;
}) {
  const values = distinctValues(rows, column);
  const scannedType = guessPropertyType(values);
  const [stage, setStage] = useState<'scan' | 'form'>('scan');
  const [label, setLabel] = useState(column);
  const [description, setDescription] = useState('');
  const [typeLabel, setTypeLabel] = useState(scannedType);
  const [numberDisplay, setNumberDisplay] = useState('Formatted number');
  const [unique, setUnique] = useState(false);
  const [busy, setBusy] = useState(false);
  const uniqueOk = canBeUnique(typeLabel);
  // Off while the API would refuse it: no label, or a dropdown with no values to offer.
  const problem = createPropertyProblem({ label, typeLabel, values });

  const create = async () => {
    if (busy || problem) return;
    setBusy(true);
    try {
      const saved = await createCustomProperty(
        createPropertyBody({
          label,
          description,
          typeLabel,
          numberDisplay,
          unique,
          values,
          taken,
          objectType,
        }),
      );
      onCreated(saved);
    } catch (err) {
      onError(errorText(err));
      setBusy(false);
    }
  };

  return (
    <>
      <div id="iqScanningStage" hidden={stage !== 'scan'}>
        <div className="modal__header sidedrawer__header">
          <h3 className="modal__title sidedrawer__title">Scanning column data</h3>
          <DrawerClose onClose={onClose} />
        </div>
        <div className="modal__body sidedrawer__body">
          <div className="iq-scanning-box">
            <p className="crm-fs-7 crm-text crm-mb-4">
              Scanning the first {rows.length.toLocaleString()} rows of this column to auto-fill
              property details... <strong>Done</strong>
            </p>
            <div className="card crm-p-4 crm-mb-4 crm-bg-surface-2">
              <h4 className="crm-fs-7 crm-fw-bold crm-mb-3">Auto-fill property details</h4>
              <div className="crm-mb-2">
                <span className="crm-fs-8 crm-text-muted crm-d-block">Property label</span>
                <strong className="crm-fs-7" id="iqScanPropLabel">
                  {column}
                </strong>
              </div>
              <div>
                <span className="crm-fs-8 crm-text-muted crm-d-block">Property type</span>
                <strong className="crm-fs-7" id="iqScanPropType">
                  {scannedType}
                </strong>
              </div>
            </div>
            <p className="crm-fs-8 crm-text-muted">
              You can review and change any of the property details before creating.
            </p>
          </div>
        </div>
        <div className="modal__footer sidedrawer__footer">
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            data-close-drawer
            onClick={onClose}
          >
            Cancel
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            id="iqReviewPropDetailsBtn"
            onClick={() => setStage('form')}
          >
            Review property details
          </button>
        </div>
      </div>

      <div id="iqCreatePropStage" hidden={stage !== 'form'}>
        <div className="modal__header sidedrawer__header">
          <h3 className="modal__title sidedrawer__title">Create new property</h3>
          <DrawerClose onClose={onClose} />
        </div>
        <div className="modal__body sidedrawer__body">
          <div className="iq-tab-bar crm-mb-4">
            <button type="button" className="iq-tab is-active" id="iqTabManual">
              <CrmIcon name="pencil" className="iconSize-14" /> Create manually
            </button>
          </div>

          <div className="crm-mb-4">
            <label htmlFor="newPropLabelInput" className="iq-field__label">
              Property label <span className="crm-text-danger">*</span>
            </label>
            <input
              type="text"
              id="newPropLabelInput"
              className="input crm-w-100"
              value={label}
              required
              onChange={(e) => setLabel(e.target.value)}
            />
          </div>

          <div className="crm-mb-4">
            <label htmlFor="newPropDescInput" className="iq-field__label">
              Property description
            </label>
            <textarea
              id="newPropDescInput"
              className="input crm-w-100 crm-pt-2"
              rows={2}
              placeholder="Describe the purpose of this property..."
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>

          <div className="crm-mb-4">
            <label htmlFor="newPropTypeTrigger" className="iq-field__label">
              Field type <span className="crm-text-danger">*</span>
            </label>
            <IqSelect
              id="newPropTypeWrap"
              wrapperClass="crm-w-100"
              triggerClass="crm-w-100"
              ids={{ trigger: 'newPropTypeTrigger', value: 'newPropTypeVal' }}
              open={openMenu === 'new-prop-type'}
              onOpen={(o) => setOpenMenu(o ? 'new-prop-type' : null)}
              value={typeLabel}
              options={NEW_PROPERTY_TYPES.map((t) => iqOption(t.label))}
              onSelect={(v) => {
                setTypeLabel(v);
                if (!canBeUnique(v)) setUnique(false);
              }}
            />
          </div>

          <div className="crm-mb-4" id="newPropNumberFormatGroup">
            <label htmlFor="newPropNumberFormatTrigger" className="iq-field__label">
              Number format
            </label>
            <IqSelect
              id="newPropNumberFormatWrap"
              wrapperClass="crm-w-100"
              triggerClass="crm-w-100"
              ids={{ trigger: 'newPropNumberFormatTrigger', value: 'newPropNumberFormatVal' }}
              open={openMenu === 'new-prop-number'}
              onOpen={(o) => setOpenMenu(o ? 'new-prop-number' : null)}
              value={numberDisplay}
              options={NUMBER_DISPLAYS.map((d) => iqOption(d.label))}
              onSelect={setNumberDisplay}
            />
          </div>

          <div className="crm-mb-4">
            <label className="check crm-align-items-start">
              <input
                type="checkbox"
                id="newPropAgentPromptCheck"
                className="iq-check-align"
                checked={false}
                onChange={() => onSoon('Smart property')}
              />
              <span className="check__box crm-mt-1"></span>
              <span className="crm-fs-7 crm-text">
                Make this a smart property and let Data Agent research and fill this property
              </span>
            </label>
            <div className="crm-mt-2" id="newPropAgentPromptBox" hidden>
              <textarea
                className="input crm-fs-7 crm-w-100"
                rows={3}
                placeholder="Enter prompt instructions for AI Data Agent..."
              />
            </div>
          </div>

          <div className="crm-mb-4">
            <label className="check crm-align-items-start">
              <input
                type="checkbox"
                id="newPropUniqueCheck"
                className="iq-check-align"
                checked={unique}
                disabled={!uniqueOk || (!unique && uniqueUsed >= MAX_UNIQUE)}
                onChange={(e) => setUnique(e.target.checked)}
              />
              <span className="check__box crm-mt-1"></span>
              <span className="crm-fs-7 crm-text">
                Require unique values for this property ({uniqueUsed + (unique ? 1 : 0)} of{' '}
                {MAX_UNIQUE})
              </span>
            </label>
          </div>
        </div>
        <DrawerFoot
          onClose={onClose}
          doneId="iqSaveNewPropertyBtn"
          doneLabel="Create property"
          onDone={create}
          busy={busy || problem !== null}
        />
      </div>
    </>
  );
}
