/**
 * Import-Modal (Paste/File, Live-Preview, Spaltenreferenz) — 1:1 aus ChartDataPanel.
 */

import {
  IMPORT_STANDARD_HEADER,
  IMPORT_ALL_COLUMNS_HEADER,
  IMPORT_EXAMPLE_HEADER,
  IMPORT_EXAMPLE_ROW,
  IMPORT_COLUMN_REFERENCE,
  IMPORT_CATEGORY_ORDER,
  IMPORT_PREVIEW_MAX_ROWS,
  IMPORT_PREVIEW_FIELD_ORDER,
} from './importConstants.js';
import { parseImportedBars, MAX_IMPORT_ROWS } from '../dataIO.js';

const { createElement: el } = wp.element;
const { __, sprintf } = wp.i18n;
const { Modal, Notice, TabPanel, Button } = wp.components;

function importColumnDesc(key) {
  const map = {
    value: __('Numeric value, required', 'pop3d-charts'),
    unit: __('Unit (tooltip)', 'pop3d-charts'),
    headline: __('Title / label', 'pop3d-charts'),
    paragraph: __('Body text in tooltip', 'pop3d-charts'),
    smallPrint: __('Source / footnote', 'pop3d-charts'),
    link: __('URL on click', 'pop3d-charts'),
    linkNewTab: __('Open in new tab (1/yes)', 'pop3d-charts'),
    color: __('Hex color', 'pop3d-charts'),
    groupKey: __('Grouping / series', 'pop3d-charts'),
    scatterX: __('X coordinate (bubble/scatter)', 'pop3d-charts'),
    scatterY: __('Y coordinate (bubble/scatter)', 'pop3d-charts'),
    annotation: __('Point label', 'pop3d-charts'),
    annotationDesc: __('Description for label', 'pop3d-charts'),
  };
  return map[key] || key;
}

function importCategoryLabel(category) {
  if (category === 'required') return __('Required', 'pop3d-charts');
  if (category === 'usual') return __('Common', 'pop3d-charts');
  return __('Optional', 'pop3d-charts');
}

function buildImportPreviewTable(rows) {
  const sample = (rows || []).slice(0, IMPORT_PREVIEW_MAX_ROWS);
  if (!sample.length) return null;
  const cols = IMPORT_PREVIEW_FIELD_ORDER.filter((field) =>
    sample.some((row) => {
      const v = row[field];
      return v != null && String(v).trim() !== '';
    })
  );
  if (!cols.length) return null;
  const cellStyle = { padding: '4px 8px', borderBottom: '1px solid #e0e0e0', verticalAlign: 'top' };
  const thStyle = { ...cellStyle, fontWeight: 600, textAlign: 'left', borderBottom: '1px solid #ccc' };
  return el('table', { style: { width: '100%', borderCollapse: 'collapse', fontSize: '11px', marginTop: '6px' } },
    el('thead', null,
      el('tr', null, cols.map((c) => el('th', { key: c, style: thStyle }, c)))
    ),
    el('tbody', null,
      sample.map((row, i) => el('tr', { key: i },
        cols.map((c) => el('td', { key: c, style: cellStyle }, row[c] != null ? String(row[c]) : ''))
      ))
    )
  );
}

export function ImportDataModal({
  onRequestClose,
  importText,
  setImportText,
  importError,
  setImportError,
  importPreview,
  importTabInitial,
  importTabMountKey,
  switchImportTab,
  fileUploadError,
  setFileUploadError,
  copyFeedback,
  handleCopyHeader,
  fileInputRef,
  handleFileImport,
  onInsertExample,
  setAttributes,
  maxBars,
}) {
  const importTabs = [
    { name: 'paste', title: __('Paste', 'pop3d-charts') },
    { name: 'file', title: __('File', 'pop3d-charts') },
  ];

  const pastePlaceholder = sprintf(__('Header: %s', 'pop3d-charts'), IMPORT_EXAMPLE_HEADER) + '\n' + sprintf(__('Example: %s', 'pop3d-charts'), IMPORT_EXAMPLE_ROW);

  function renderImportLiveFeedback() {
    const { status, count, rows, truncated } = importPreview;
    if (status === 'empty' && !importText.trim()) return null;
    const statusStyle = { fontSize: '12px', color: '#50575e', marginTop: '0.5rem' };
    let statusLine = null;
    if (status === 'ok' || status === 'limit') {
      statusLine = el('p', { style: statusStyle },
        sprintf(__('%d rows recognized.', 'pop3d-charts'), count || 0));
    } else if (status === 'fail') {
      statusLine = el('p', { style: { ...statusStyle, color: '#856404' } },
        __('Could not parse the data yet. Check the format or add a header row with a value column.', 'pop3d-charts'));
    }
    const limitNotice = (status === 'limit' || truncated)
      ? el('p', { style: { ...statusStyle, color: '#856404', marginTop: '4px' } },
        sprintf(__('More than %d rows detected — only the first %d will be imported.', 'pop3d-charts'), MAX_IMPORT_ROWS, MAX_IMPORT_ROWS))
      : null;
    const previewTable = (status === 'ok' || status === 'limit') && rows && rows.length > 0
      ? el('div', { className: 'pop3d-import-preview-wrap' },
        el('p', { style: { fontSize: '11px', color: '#666', margin: '0 0 4px' } },
          sprintf(__('Preview (first %d rows)', 'pop3d-charts'), IMPORT_PREVIEW_MAX_ROWS)),
        buildImportPreviewTable(rows)
      )
      : null;
    return el('div', null, statusLine, limitNotice, previewTable);
  }

  function renderColumnReference() {
    const sorted = [...IMPORT_COLUMN_REFERENCE].sort(
      (a, b) => IMPORT_CATEGORY_ORDER.indexOf(a.category) - IMPORT_CATEGORY_ORDER.indexOf(b.category)
    );
    const thStyle = { textAlign: 'left', padding: '6px 8px', borderBottom: '1px solid #ccc', fontSize: '11px' };
    const tdStyle = { padding: '6px 8px', borderBottom: '1px solid #e8e8e8', fontSize: '11px', verticalAlign: 'top' };
    return el('details', { style: { marginTop: '1rem', fontSize: '12px' } },
      el('summary', { style: { cursor: 'pointer', fontWeight: 600 } }, __('Column reference', 'pop3d-charts')),
      el('div', { style: { marginTop: '0.5rem', display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' } },
        el(Button, { variant: 'secondary', isSmall: true, onClick: () => handleCopyHeader(IMPORT_STANDARD_HEADER) },
          __('Copy standard header', 'pop3d-charts')),
        el(Button, { variant: 'secondary', isSmall: true, onClick: () => handleCopyHeader(IMPORT_ALL_COLUMNS_HEADER) },
          __('Copy all columns', 'pop3d-charts')),
        copyFeedback ? el('span', { style: { fontSize: '12px', color: '#2271b1' } }, copyFeedback) : null
      ),
      el('table', { style: { width: '100%', borderCollapse: 'collapse', marginTop: '0.5rem' } },
        el('thead', null,
          el('tr', null,
            el('th', { style: thStyle }, __('Category', 'pop3d-charts')),
            el('th', { style: thStyle }, __('Column', 'pop3d-charts')),
            el('th', { style: thStyle }, __('Description', 'pop3d-charts')),
            el('th', { style: thStyle }, __('Example', 'pop3d-charts'))
          )
        ),
        el('tbody', null,
          sorted.map((col) => el('tr', { key: col.key },
            el('td', { style: tdStyle }, importCategoryLabel(col.category)),
            el('td', { style: { ...tdStyle, fontFamily: 'monospace' } },
              col.key,
              col.aliases ? el('div', { style: { fontSize: '10px', color: '#666', marginTop: '2px', fontFamily: 'inherit' } },
                __('Also accepted:', 'pop3d-charts') + ' ' + col.aliases) : null
            ),
            el('td', { style: tdStyle }, importColumnDesc(col.key)),
            el('td', { style: { ...tdStyle, fontFamily: 'monospace', color: '#666' } }, col.example)
          ))
        )
      )
    );
  }

  return el(Modal, {
    className: 'pop3d-import-modal',
    title: __('Import data', 'pop3d-charts'),
    onRequestClose,
  },
    el('div', { className: 'pop3d-import-modal__body' },
      el('p', { style: { marginBottom: '0.5rem', color: '#1e1e1e', fontSize: '13px' } },
        __('Paste data or upload a file — a header row is detected automatically.', 'pop3d-charts')),
      el('ol', { style: { margin: '0 0 0.75rem 1.25rem', padding: 0, color: '#666', fontSize: '12px' } },
        el('li', null, __('Paste from Excel or Google Sheets (tab-separated).', 'pop3d-charts')),
        el('li', null, __('CSV with semicolon (;) separator.', 'pop3d-charts')),
        el('li', null, __('JSON array of bar objects.', 'pop3d-charts')),
        el('li', null, __('Or use the File tab to upload .json, .xlsx, or .csv.', 'pop3d-charts'))
      ),
      importError ? el(Notice, { status: 'error', isDismissible: true, onRemove: () => setImportError('') }, importError) : null,
      el(TabPanel, {
        key: 'import-tabs-' + importTabMountKey,
        className: 'pop3d-import-tab-panel',
        activeClass: 'is-active',
        initialTabName: importTabInitial,
        tabs: importTabs,
      }, (tab) => {
        if (tab.name === 'paste') {
          return el('div', { style: { marginTop: '0.5rem' } },
            el('div', { style: { display: 'flex', justifyContent: 'flex-end', marginBottom: '6px' } },
              el(Button, { variant: 'secondary', isSmall: true, onClick: onInsertExample },
                __('Insert example', 'pop3d-charts'))
            ),
            el('textarea', {
              value: importText,
              onChange: (e) => { setImportText(e.target.value); if (importError) setImportError(''); },
              style: { width: '100%', minHeight: '200px', fontFamily: 'monospace', fontSize: '12px' },
              placeholder: pastePlaceholder,
            })
          );
        }
        return el('div', { style: { marginTop: '0.5rem' } },
          fileUploadError ? el(Notice, { status: 'error', isDismissible: true, onRemove: () => setFileUploadError('') }, fileUploadError) : null,
          el(Button, { variant: 'secondary', isSmall: true, onClick: () => { if (fileInputRef.current) fileInputRef.current.click(); } },
            __('Upload .json / .xlsx / .csv file', 'pop3d-charts')),
          el('input', { type: 'file', accept: '.json,.xlsx,.xls,.csv', ref: fileInputRef, onChange: handleFileImport, style: { display: 'none' } }),
          importText.trim() ? el('p', { style: { marginTop: '0.75rem', fontSize: '12px' } },
            el(Button, { variant: 'link', isSmall: true, onClick: () => switchImportTab('paste') },
              __('View raw data', 'pop3d-charts'))
          ) : null
        );
      }),
      renderImportLiveFeedback(),
      renderColumnReference(),
      el('div', { style: { marginTop: '1rem', display: 'flex', gap: '8px' } },
        el(Button, {
          variant: 'primary',
          onClick: () => {
            const parsed = parseImportedBars(importText);
            if (parsed && parsed.length > 0) {
              setAttributes({ bars: parsed.slice(0, maxBars) });
              setImportError('');
              onRequestClose();
            } else {
              setImportError(__('Could not read the data. Make sure there is a value column and the format is correct.', 'pop3d-charts'));
            }
          },
        }, __('Import', 'pop3d-charts')),
        el(Button, { variant: 'secondary', onClick: () => { setImportError(''); onRequestClose(); } }, __('Cancel', 'pop3d-charts'))
      )
    )
  );
}
