import React from 'react';
import PhotoPostWizard from '@/features/photopost/components/PhotoPostWizard';
import { getEventMedia } from '@/features/event/api/getEventMedia';
import { uploadEventFile } from '@/shared/api/fileService';
import { generateSocialMediaPosts, publishSocialMediaPost } from '@/features/photopost/api/socialPostService';
import { speechToText } from '@/shared/api/toolService';
import { toast } from 'sonner';

interface PhotoPostWizardContainerProps {
  eventId: string | number;
  onComplete: () => void;
}

const PhotoPostWizardContainer: React.FC<PhotoPostWizardContainerProps> = ({ eventId, onComplete }) => {
  const onFetchEventImages = async (id: string | number) => {
    try {
      const images = await getEventMedia(id as any);
      return Array.isArray(images) ? images as any : [];
    } catch (e) {
      toast.error('Fehler beim Laden der Event Bilder');
      return [];
    }
  };

  const onUploadEventFile = async (file: File, evId?: string) => {
    try {
      const res = await uploadEventFile(file, evId);
      if (!res.success) toast.error(res.message || 'Upload fehlgeschlagen');
      return res;
    } catch (e: any) {
      toast.error(e?.message || 'Upload fehlgeschlagen');
      return { success: false, message: e?.message || 'Upload fehlgeschlagen' };
    }
  };

  const onGenerateSocialPosts = async (payload: any) => {
    try {
      const res = await generateSocialMediaPosts(payload);
      if (!res) throw new Error('Keine Antwort');
      return res;
    } catch (e) {
      toast.error('Fehler beim Generieren');
      throw e;
    }
  };

  const onPublishSocialPost = async (args: { postId: string; posts: any; images: any; scheduledTime: string }) => {
    try {
      const res = await publishSocialMediaPost(args);
      if (res?.status === 'sucess') {
        toast.success(args.scheduledTime ? 'Erfolgreich geplant!' : 'Erfolgreich veröffentlicht!');
      } else {
        toast.error('Fehler beim Senden!');
      }
      return res;
    } catch (e) {
      toast.error('Fehler beim Senden!');
      throw e;
    }
  };

  const onSpeechToTextWrapper = async (file: File) => {
    try {
      const res = await speechToText(file);
      if (!res.success) toast.error(res.message || 'Transkription fehlgeschlagen');
      return res;
    } catch (e: any) {
      toast.error(e?.message || 'Transkription fehlgeschlagen');
      return { success: false, message: e?.message || 'Transkription fehlgeschlagen' };
    }
  };

  return (
    <PhotoPostWizard
      eventId={eventId}
      onComplete={onComplete}
      onFetchEventImages={onFetchEventImages}
      onUploadEventFile={onUploadEventFile}
      onGenerateSocialPosts={onGenerateSocialPosts}
      onPublishSocialPost={onPublishSocialPost}
      onSpeechToText={onSpeechToTextWrapper}
    />
  );
};

export default PhotoPostWizardContainer;
