import * as XLSX from 'xlsx';
import toast from 'react-hot-toast';

import { BaseApiService } from '@/services/api/base';
import { httpClientFetcher } from '@/services/http/client';
import { BaseApiResponse } from '@/types/api/api-general';
import {
  DailyMarketingReport,
  DailyMarketingReportResponse,
} from '@/types/api/report/marketing';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { formatDate } from '@/lib/helper';

export class MarketingReportApiService extends BaseApiService<
  DailyMarketingReport,
  unknown,
  unknown
> {
  constructor(basePath: string = '/reports/marketing') {
    super(basePath);
  }

  async getAllDailyMarketingFetcher(
    endpoint: string
  ): Promise<DailyMarketingReportResponse> {
    return await httpClientFetcher<DailyMarketingReportResponse>(endpoint);
  }

  async exportDailyMarketingToExcel(initialQueryString: string) {
    const params = new URLSearchParams(initialQueryString);

    params.set('limit', '9999999');

    const queryString = `?${params.toString()}`;

    try {
      const dailyMarketingsReport = await httpClientFetcher<
        BaseApiResponse<DailyMarketingReport>
      >(`${this.basePath}${queryString}`);

      if (isResponseError(dailyMarketingsReport)) {
        toast.error('Gagal melakukan export penjualan harian! Coba lagi.');
        return;
      }

      const rows = dailyMarketingsReport.data;

      const formattedRows = [];

      for (let i = 0; i < rows.length; i++) {
        formattedRows.push({
          ...rows[i],
          // created_user: rows[i].created_user.name,
          // created_at: formatDate(rows[i].created_at, 'YYYY-MM-DD'),
          // updated_at: formatDate(rows[i].updated_at, 'YYYY-MM-DD'),
          so_date: formatDate(rows[i].so_date, 'YYYY-MM-DD'),
          realization_date: formatDate(rows[i].realization_date, 'YYYY-MM-DD'),
          sales: rows[i].sales.name,
          warehouse: rows[i].warehouse.name,
          customer: rows[i].customer.name,
          product: rows[i].product.name,
        });
      }

      const ws = XLSX.utils.json_to_sheet(formattedRows);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'laporan-penjualan-harian');

      // triggers download in browser
      XLSX.writeFile(wb, 'laporan-penjualan-harian.xlsx');
    } catch (error) {
      toast.error('Gagal melakukan export penjualan harian! Coba lagi.');
    }
  }
}

export const MarketingReportApi = new MarketingReportApiService(
  '/reports/marketing'
);
