import { JsonObject } from '@win2win/shared';
import { api } from 'src/boot/axios';
import { run } from 'src/store/helpers';

export function exportJsonToFile(data: object, filename: string) {
  const jsonContent = JSON.stringify(data, null, 2);
  const blob = new Blob([jsonContent], { type: 'application/json' });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
}

export function importJsonFromFile<T = any>(handler: (data: T, size: number) => void) {
  const input = document.createElement('input');
  input.type = 'file';
  input.style.display = 'none';
  input.accept = '.json';
  input.addEventListener('change', (ev: Event) => {
    const target = ev.target as HTMLInputElement;
    if (!target || !target.files || !target.files.length) return;
    const file = target.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target?.result as string) as T;
        const size = file.size / 1024; // in KB
        handler(data, size);
      } catch (e) {
        console.error(e);
      }
    };
    reader.readAsText(file);
  });
  document.body.appendChild(input);
  input.click();
  document.body.removeChild(input);
}

export function openFile(file: File, fileName: string, download = true) {
  const url = URL.createObjectURL(file);
  const a: HTMLAnchorElement = document.createElement('a');
  a.href = url;

  if (download) {
    a.download = fileName;
  } else {
    a.target = '_blank';
  }
  a.click();
  URL.revokeObjectURL(url);
}

export interface DownloadExcelOptions {
  addDateToFileName?: boolean;
}
export function downloadExcel(data: BlobPart, fileName: string, options: DownloadExcelOptions = {}) {
  const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  const date = options.addDateToFileName ? `_${new Date().toISOString()}` : '';
  a.download = `${fileName}${date}.xlsx`;
  a.click();
  window.URL.revokeObjectURL(url);
}

export interface FileDownloadOptions {
  params?: JsonObject;
  fileName?: string;
}

export function downloadFileFromUrl(url: string, options?: FileDownloadOptions) {
  const a = document.createElement('a');
  const parsedURL = new URL(url);
  if (options?.params) {
    Object.keys(options.params).forEach((key) => {
      parsedURL.searchParams.append(key, options.params![key]);
    });
  }
  a.href = url;
  a.download = options?.fileName || url;
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
}

export async function uploadStandaloneFile(file?: File | null): Promise<string> {
  if (!file) return Promise.resolve('');
  const data = new FormData();
  data.append('file', file);
  const url = await run(api.post('/upload_standalone_file', data));
  console.log('File uploaded successfully:', url);
  return url;
}
