import { getWebhookUrl } from '@/lib/config';
import { toast } from 'sonner';

export interface FileUploadResponse {
  success: boolean;
  message: string;
  url?: string;  // The URL from the API response
  fileUrl?: string; // For backward compatibility
  id?: string; // Add other fields as needed based on your API response
}

export const uploadBlogFile = async (file: File, blogId?: string): Promise<FileUploadResponse> => {
  console.log('Uploading file');
  
  const formData = new FormData();
  formData.append('file', file);
  formData.append('blog_id', blogId);
  
  // Debug: Log FormData contents
  for (let [key, value] of formData.entries()) {
    console.log(key, value);
  }

  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/file_upload_blog`, {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'File uploaded successfully',
      url: data.url, // The URL from the API response
      fileUrl: data.url, // For backward compatibility
      ...data
    };
  } catch (error) {
    console.error('Error uploading file:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to upload file',
    };
  }
};

interface MediaDeleteParams {
  endpoint: string; // e.g. '/events/artist_remove'
  mediaId: string | number;
  token?: string;
  extraFields?: Record<string, string | number | undefined>;
}

export const deleteMediaWithContext = async ({
  endpoint,
  mediaId,
  token,
  extraFields,
}: MediaDeleteParams): Promise<FileUploadResponse> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const url = `${getWebhookUrl()}${endpoint}`;
    const payload: Record<string, any> = { mediaId };
    if (token) payload.token = token;
    if (extraFields) {
      Object.entries(extraFields).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          payload[key] = value;
        }
      });
    }

    const response = await apiFetch(url, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const raw = await response.json();
    const data = Array.isArray(raw) ? raw[0] ?? {} : raw ?? {};

    return {
      success: data.success !== false,
      message: data.message || 'File deleted successfully',
      ...data,
    };
  } catch (error) {
    console.error('Error deleting media with context:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to delete file',
    };
  }
};

interface MediaContextParams {
  endpoint: string; // e.g. '/events/artist_upload'
  id: string | number;
  token?: string;
  type?: string;
  extraFields?: Record<string, string | number | undefined>;
}

export const uploadMediaWithContext = async (
  file: File,
  { endpoint, id, token, type, extraFields }: MediaContextParams
): Promise<FileUploadResponse> => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('id', String(id));
  if (token) formData.append('token', token);
  if (type) formData.append('type', type);

  if (extraFields) {
    Object.entries(extraFields).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        formData.append(key, String(value));
      }
    });
  }

  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const url = `${getWebhookUrl()}${endpoint}`;
    const response = await apiFetch(url, {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const raw = await response.json();
    const data = Array.isArray(raw) ? raw[0] ?? {} : raw ?? {};

    return {
      success: true,
      message: 'File uploaded successfully',
      url: data.url || data.fileUrl || data.imageUrl,
      fileUrl: data.url || data.fileUrl || data.imageUrl,
      ...data,
    };
  } catch (error) {
    console.error('Error uploading media with context:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to upload file',
    };
  }
};


export const uploadEventFile = async (file: File, eventId?: string): Promise<FileUploadResponse> => {
  console.log('Uploading file');
  
  const formData = new FormData();
  formData.append('file', file);
  formData.append('event_id', eventId);
  
  // Debug: Log FormData contents
  for (let [key, value] of formData.entries()) {
    console.log(key, value);
  }

  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/file_upload_event`, {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'File uploaded successfully',
      url: data.url, // The URL from the API response
      fileUrl: data.url, // For backward compatibility
      ...data
    };
  } catch (error) {
    console.error('Error uploading file:', error);
    toast.error('Failed to upload file');
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to upload file',
    };
  }
};



export const uploadTmpFile = async (file: File): Promise<FileUploadResponse> => {
  console.log('Uploading file');
  
  const formData = new FormData();
  formData.append('file', file);
  
  // Debug: Log FormData contents
  for (let [key, value] of formData.entries()) {
    console.log(key, value);
  }

  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/upload_tmp`, {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'File uploaded successfully',
      url: data.url, // The URL from the API response
      fileUrl: data.url, // For backward compatibility
      ...data
    };
  } catch (error) {
    console.error('Error uploading file:', error);
    toast.error('Failed to upload file');
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to upload file',
    };
  }
};

export const generateBlogPostImage = async (blogId: string, title: string): Promise<FileUploadResponse> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/media/image_generator`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        blog_id: blogId,
        title: title
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'Blog post image generated successfully',
      url: data.url || data.imageUrl, // Handle different possible response formats
      fileUrl: data.url || data.imageUrl,
      ...data
    };
  } catch (error) {
    console.error('Error generating blog post image:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to generate blog post image',
    };
  }
};

export const generateAIImage = async (prompt: string): Promise<FileUploadResponse> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/file_upload`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt,
        // Add any other required parameters for image generation
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'Image generated successfully',
      fileUrl: data.imageUrl, // Adjust based on your API response
      ...data
    };
  } catch (error) {
    console.error('Error generating image:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to generate image',
    };
  }
};
