import React, { useRef, useState } from 'react';
import { exportUsers, importUsers } from '../../services/users';
import './ExportButton.css';

const ExportButton = ({ onExport, onRefetch }) => {
  const [loading, setLoading] = useState(false);
  const [importing, setImporting] = useState(false);
  const [overwrite, setOverwrite] = useState(false);
  const fileInputRef = useRef(null);

  const handleExport = async (format) => {
    setLoading(true);
    const result = await exportUsers(format);
    setLoading(false);
    if (result.success) {
      onExport && onExport('success', `Export erfolgreich (${format.toUpperCase()})`);
    } else {
      onExport && onExport('error', result.message || 'Export fehlgeschlagen');
    }
  };

  const handleImportClick = () => {
    fileInputRef.current && fileInputRef.current.click();
  };

  const handleFileChange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    setImporting(true);
    try {
      const text = await file.text();
      let parsed;
      try {
        parsed = JSON.parse(text);
      } catch {
        onExport && onExport('error', 'Datei ist kein gültiges JSON');
        return;
      }

      // Akzeptiere { users: [...] } oder direkt ein Array
      const payload = Array.isArray(parsed)
        ? { users: parsed }
        : parsed;

      if (!Array.isArray(payload.users)) {
        onExport && onExport('error', 'Kein gültiges Export-Format. Erwartet: { "users": [...] }');
        return;
      }

      const result = await importUsers(payload, overwrite);
      if (result.success) {
        const { imported, skipped, errors } = result.data.results;
        const errText = errors.length ? `, ${errors.length} Fehler` : '';
        onExport && onExport(
          errors.length ? 'warning' : 'success',
          `Import: ${imported} importiert, ${skipped} übersprungen${errText}`
        );
        if (imported > 0) onRefetch && onRefetch();
      } else {
        onExport && onExport('error', result.message || 'Import fehlgeschlagen');
      }
    } finally {
      setImporting(false);
      // Reset so dieselbe Datei erneut gewählt werden kann
      e.target.value = '';
    }
  };

  return (
    <div className="export-import-section">
      <div className="export-buttons">
        <button
          className="export-button"
          onClick={() => handleExport('csv')}
          disabled={loading || importing}
        >
          {loading ? 'Exportiere...' : 'Als CSV exportieren'}
        </button>
        <button
          className="export-button"
          onClick={() => handleExport('json')}
          disabled={loading || importing}
        >
          {loading ? 'Exportiere...' : 'Als JSON exportieren'}
        </button>
      </div>

      <div className="import-section">
        <label className="import-overwrite">
          <input
            type="checkbox"
            checked={overwrite}
            onChange={e => setOverwrite(e.target.checked)}
            disabled={importing}
          />
          Vorhandene überschreiben
        </label>
        <button
          className="import-button"
          onClick={handleImportClick}
          disabled={loading || importing}
        >
          {importing ? 'Importiere...' : 'JSON importieren'}
        </button>
        <input
          ref={fileInputRef}
          type="file"
          accept=".json,application/json"
          style={{ display: 'none' }}
          onChange={handleFileChange}
        />
      </div>
    </div>
  );
};

export default ExportButton;
