/**
 * State und Handler für den Import-Dialog; Modal-Rendering via ImportDataModal.
 */

import { IMPORT_DEBOUNCE_MS, IMPORT_EXAMPLE_CSV, estimateImportDataLineCount } from './importConstants.js';
import { ImportDataModal } from './ImportDataModal.js';
import { parseImportedBars, loadXlsx, MAX_XLSX_BYTES, MAX_IMPORT_ROWS } from '../dataIO.js';

const { createElement: el, useRef, useState, useEffect } = wp.element;
const { __ } = wp.i18n;

const MAX_BARS_FOR_LAYOUT = 1000;

async function copyToClipboard(text) {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    await navigator.clipboard.writeText(text);
    return true;
  }
  return false;
}

export function useImportDataModal({ setAttributes }) {
  const [importOpen, setImportOpen] = useState(false);
  const [importText, setImportText] = useState('');
  const [importError, setImportError] = useState('');
  const [importPreview, setImportPreview] = useState({ status: 'empty' });
  const [importTabInitial, setImportTabInitial] = useState('paste');
  const [importTabMountKey, setImportTabMountKey] = useState(0);
  const [fileUploadError, setFileUploadError] = useState('');
  const [copyFeedback, setCopyFeedback] = useState('');
  const fileInputRef = useRef(null);
  const importDebounceRef = useRef(null);

  useEffect(() => {
    if (!importOpen) return undefined;
    if (importDebounceRef.current) clearTimeout(importDebounceRef.current);
    importDebounceRef.current = setTimeout(() => {
      importDebounceRef.current = null;
      const trimmed = String(importText || '').trim();
      if (!trimmed) {
        setImportPreview({ status: 'empty' });
        return;
      }
      const parsed = parseImportedBars(importText);
      const rawCount = estimateImportDataLineCount(importText);
      const truncated = rawCount > MAX_IMPORT_ROWS;
      if (!parsed || parsed.length === 0) {
        setImportPreview({ status: 'fail', truncated });
        return;
      }
      setImportPreview({
        status: truncated ? 'limit' : 'ok',
        rows: parsed,
        count: parsed.length,
        truncated,
      });
    }, IMPORT_DEBOUNCE_MS);
    return () => {
      if (importDebounceRef.current) {
        clearTimeout(importDebounceRef.current);
        importDebounceRef.current = null;
      }
    };
  }, [importText, importOpen]);

  function resetImportState() {
    setImportText('');
    setImportError('');
    setFileUploadError('');
    setCopyFeedback('');
    setImportPreview({ status: 'empty' });
    setImportTabInitial('paste');
    setImportTabMountKey((k) => k + 1);
  }

  function openImportModal() {
    resetImportState();
    setImportOpen(true);
  }

  function closeImportModal() {
    setImportError('');
    setImportOpen(false);
  }

  function switchImportTab(name) {
    setImportTabInitial(name);
    setImportTabMountKey((k) => k + 1);
  }

  function insertImportExample() {
    setImportText(IMPORT_EXAMPLE_CSV);
    setImportError('');
    switchImportTab('paste');
  }

  async function handleCopyHeader(text) {
    const ok = await copyToClipboard(text);
    setCopyFeedback(ok ? __('Copied!', 'pop3d-charts') : __('Copy failed', 'pop3d-charts'));
    if (ok) setTimeout(() => setCopyFeedback(''), 2000);
  }

  function handleFileImport(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setFileUploadError('');
    if (file.size > MAX_XLSX_BYTES) {
      setFileUploadError(__('File is too large (max. 5 MB).', 'pop3d-charts'));
      if (fileInputRef.current) fileInputRef.current.value = '';
      return;
    }
    const ext = file.name.split('.').pop().toLowerCase();
    if (ext === 'xlsx' || ext === 'xls') {
      loadXlsx().then((XLSX) => {
        const reader = new FileReader();
        reader.onload = (ev) => {
          const wb = XLSX.read(new Uint8Array(ev.target.result), { type: 'array' });
          const ws = wb.Sheets[wb.SheetNames[0]];
          const csv = XLSX.utils.sheet_to_csv(ws, { FS: ';' });
          setImportText(csv);
          setImportError('');
        };
        reader.readAsArrayBuffer(file);
      });
    } else {
      const reader = new FileReader();
      reader.onload = (ev) => {
        setImportText(ev.target.result);
        setImportError('');
      };
      reader.readAsText(file);
    }
    if (fileInputRef.current) fileInputRef.current.value = '';
  }

  const importModalElement = importOpen
    ? el(ImportDataModal, {
      onRequestClose: closeImportModal,
      importText,
      setImportText,
      importError,
      setImportError,
      importPreview,
      importTabInitial,
      importTabMountKey,
      switchImportTab,
      fileUploadError,
      setFileUploadError,
      copyFeedback,
      handleCopyHeader,
      fileInputRef,
      handleFileImport,
      onInsertExample: insertImportExample,
      setAttributes,
      maxBars: MAX_BARS_FOR_LAYOUT,
    })
    : null;

  return {
    importModalElement,
    openImportModal,
  };
}
