import React, { useState } from 'react';
import { DialogComponent } from '@syncfusion/ej2-react-popups';
import {
  FileManagerComponent,
  Inject,
  NavigationPane,
  DetailsView,
  Toolbar,
} from '@syncfusion/ej2-react-filemanager';

const hostUrl = '/api/eventmedia/filemanager/';

type CustomSelectUploadEventModalProps = {
  open: boolean;
  onClose: () => void;
  onSelect: (file: { id: string; path: string; name: string }) => void; // name ergänzt
  selectedFileId?: string | null;
};

const CustomSelectUploadEventModal: React.FC<CustomSelectUploadEventModalProps> = props => {
  const { open, onClose, onSelect } = props;

  const [selectedFile, setSelectedFile] = useState<{
    id: string;
    path: string;
    name: string;
  } | null>(null);

  // Callback für Dateiauswahl
  interface FileSelectEventArgs {
    fileDetails: {
      name: string;
      isFile: boolean;
      size: number;
      // weitere Felder falls benötigt
    };
  }

  const handleFileSelect = async (args: FileSelectEventArgs) => {
    if (args.fileDetails.isFile && args.fileDetails.size > 0) {
      const filename = args.fileDetails.name;

      try {
        const response = await fetch(
          `/api/eventmedia/find_by_filename?filename=${encodeURIComponent(filename)}`
        );
        if (response.ok) {
          const data = await response.json();
          setSelectedFile({ id: data.id, path: data.file_path, name: filename });
        } else {
          setSelectedFile({ id: filename, path: filename, name: filename });
        }
      } catch (e) {
        console.error('Error fetching file details:', e);
      }
    }
  };

  // Button-Handler
  const handleSelectClick = () => {
    if (selectedFile) {
      onSelect(selectedFile);
    }
  };

  return (
    <DialogComponent
      target="#root"
      visible={open}
      width="700px"
      header="Medium auswählen/hochladen"
      showCloseIcon={true}
      close={onClose}
      isModal={true}
      footerTemplate={() => (
        <div className="flex gap-2 justify-end">
          <button className="e-btn" onClick={onClose}>
            Abbrechen
          </button>
          <button className="e-btn e-primary" disabled={!selectedFile} onClick={handleSelectClick}>
            Auswählen
          </button>
        </div>
      )}
    >
      <FileManagerComponent
        ajaxSettings={{
          url: hostUrl + 'operations',
          getImageUrl: hostUrl + 'get-image',
          uploadUrl: hostUrl + 'upload',
          downloadUrl: hostUrl + 'download',
        }}
        toolbarSettings={{
          items: [
            'NewFolder',
            'Upload',
            'Download',
            'Rename',
            'Delete',
            'SortBy',
            'Refresh',
            'Details',
          ],
        }}
        contextMenuSettings={{
          file: ['Open', '|', 'Download', '|', 'Rename', 'Delete', '|', 'Details'],
          folder: ['Open', '|', 'Rename', 'Delete', '|', 'Details'],
          layout: ['SortBy', 'Refresh', '|', 'View', 'Details'],
        }}
        allowMultiSelection={false}
        fileSelect={handleFileSelect}
      >
        <Inject services={[NavigationPane, DetailsView, Toolbar]} />
      </FileManagerComponent>
    </DialogComponent>
  );
};

export default CustomSelectUploadEventModal;
