import React, { useEffect, useState } from 'react';
import CustomMediaInfoPanel from './components/CustomMediaInfoPanel';
import {
  FileManagerComponent,
  Inject,
  NavigationPane,
  DetailsView,
  Toolbar,
} from '@syncfusion/ej2-react-filemanager';

const hostUrl = '/api/eventmedia/filemanager/'; // Dein Backend-Endpunkt für FileManager

interface MediaItem {
  id: string;
  file_path: string;
  url: string;
  description: string;
  eventId?: string;
}

const Media: React.FC = () => {
  const [mediaList, setMediaList] = useState<MediaItem[]>([]);
  const [selectedMedia, setSelectedMedia] = useState<MediaItem | null>(null);

  // Medien vom Server laden
  useEffect(() => {
    fetch('/api/eventmedia')
      .then(res => res.json())
      .then(setMediaList);
  }, []);


  // Speichern von Metadaten/Event-Zuordnung
  const handleSave = async (data: { title: string; description: string; eventId?: string }) => {
    if (!selectedMedia) return;
    await fetch(`/api/eventmedia/${selectedMedia.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    // Nach dem Speichern neu laden
    const res = await fetch('/api/eventmedia');
    setMediaList(await res.json());
  };

  return (
    <div>
      <h2 className="text-xl font-bold mb-4">Medien</h2>
      <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}
      >
        <Inject services={[NavigationPane, DetailsView, Toolbar]} />
      </FileManagerComponent>
      {selectedMedia && (
        <CustomMediaInfoPanel
          mediaId={selectedMedia.id}
          title={selectedMedia.url}
          description={selectedMedia.description}
          eventId={selectedMedia.eventId}
          onSave={handleSave}
        />
      )}
    </div>
  );
};

export default Media;
