/**
 * Panel "Chart Data" — Zeilenliste bearbeiten (ohne Import/Export; siehe ImportExportPanel).
 */

import { BarItemEditor } from '../BarItemEditor.js';
import { getChartDataIntro } from '../attributeHelpers.js';
import { isPieLayout } from '../constants.js';

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

const MAX_BARS_FOR_LAYOUT = 1000;

export function ChartDataPanel({
  attributes,
  setAttributes,
  bars,
  barsOrdered,
  layout,
  defaultBar,
  emptyDatasetBar,
  openState,
}) {
  const updateBar = (index, newBar) => {
    const next = [...bars];
    next[index] = newBar;
    setAttributes({ bars: next });
  };
  const addBar = () => {
    if (bars.length >= MAX_BARS_FOR_LAYOUT) return;
    setAttributes({ bars: [...bars, defaultBar()] });
  };
  const removeBar = (index) => {
    if (bars.length <= 1) return;
    setAttributes({ bars: bars.filter((_, i) => i !== index) });
  };
  const moveBarByDisplayIndex = (dispIdx, delta) => {
    const targetIdx = dispIdx + delta;
    if (dispIdx < 0 || targetIdx < 0 || targetIdx >= barsOrdered.length) return;
    const ordered = barsOrdered.map((x) => x.bar);
    [ordered[targetIdx], ordered[dispIdx]] = [ordered[dispIdx], ordered[targetIdx]];
    const patch = { bars: ordered };
    if ((attributes.sortOrder || 'custom') !== 'custom') patch.sortOrder = 'custom';
    setAttributes(patch);
  };
  const duplicateBar = (index) => {
    if (bars.length >= MAX_BARS_FOR_LAYOUT) return;
    const next = [...bars];
    next.splice(index + 1, 0, { ...bars[index], headline: (bars[index].headline || '') + ' (Copy)' });
    setAttributes({ bars: next });
  };

  const clearAllChartData = () => {
    if (!window.confirm(__('Replace all rows with a single empty row?', 'pop3d-charts'))) return;
    setAttributes({ bars: [emptyDatasetBar()] });
  };

  const pieSumWarning = (() => {
    if (!isPieLayout(layout)) return null;
    const axisUnit = String((attributes.axisY?.unit) ?? '%').trim();
    if (axisUnit !== '%' || bars.length === 0) return null;
    const sum = bars.reduce((s, b) => s + (Number(b.value) || 0), 0);
    if (sum <= 100.5) return null;
    return el(Notice, { status: 'warning', isDismissible: false },
      __('Pie chart: sum exceeds 100%.', 'pop3d-charts') + ' ' + Math.round(sum * 10) / 10 + '%');
  })();

  return el(PanelBody, { title: __('Chart Data', 'pop3d-charts'), ...(openState || {}) },
    el('p', { style: { marginBottom: '0.75rem', color: '#666', fontSize: '12px', fontStyle: 'italic' } }, getChartDataIntro(layout)),
    el('p', { style: { marginBottom: '0.5rem', marginTop: '0.75rem', color: '#666', fontSize: '12px' } },
      __('Number of bars:', 'pop3d-charts') + ' ' + bars.length),
    pieSumWarning,
    (bars.length >= 100) ? el('p', {
      style: { marginBottom: '1rem', padding: '8px 10px', fontSize: '12px', color: '#856404', background: '#fff3cd', border: '1px solid #ffc107', borderRadius: '4px' },
    }, __('Performance warning: 100+ data points may slow down rendering.', 'pop3d-charts')) : null,
    el('div', { style: { display: 'flex', gap: '8px', marginBottom: '0.75rem', flexWrap: 'wrap', alignItems: 'center' } },
      bars.length < MAX_BARS_FOR_LAYOUT ? el(Button, { variant: 'secondary', isSmall: true, onClick: addBar },
        __('Add Bar', 'pop3d-charts')) : null,
      el(Button, { variant: 'secondary', isSmall: true, isDestructive: true, onClick: clearAllChartData }, __('Clear all data', 'pop3d-charts'))
    ),
    barsOrdered.map(({ bar, originalIndex }, displayIndex) => el(BarItemEditor, {
      key: originalIndex,
      bar,
      displayIndex,
      originalIndex,
      total: bars.length,
      layout,
      onChange: (b) => updateBar(originalIndex, b),
      onRemove: () => removeBar(originalIndex),
      onMoveUp: () => moveBarByDisplayIndex(displayIndex, -1),
      onMoveDown: () => moveBarByDisplayIndex(displayIndex, +1),
      onDuplicate: () => duplicateBar(originalIndex),
    }))
  );
}
