// services/excelExportService.ts
import type { ProfitLossReport } from '@/types/services/analytic'

export class ExcelExportProfitLossService {
  /**
   * Export Profit Loss Report to Excel
   */
  static async exportProfitLossToExcel(profitData: ProfitLossReport, filename?: string) {
    try {
      // Dynamic import untuk xlsx library
      const XLSX = await import('xlsx')

      // Prepare data untuk Excel
      const worksheetData: any[][] = []

      // Header dengan company info (baris 1-2) - update data
      worksheetData.push(['LABA RUGI']) // Row 0 - Main title
      worksheetData.push([`Periode: ${profitData.date_from.split('T')[0]} - ${profitData.date_to.split('T')[0]}`]) // Row 1 - Period
      worksheetData.push([]) // Empty row

      // Add Summary Section
      worksheetData.push(['RINGKASAN PERIODE']) // Section header
      worksheetData.push([]) // Empty row

      const summaryData = [
        ['Total Revenue:', `Rp ${profitData.summary.total_revenue.toLocaleString('id-ID')}`],
        ['Total Cost:', `Rp ${profitData.summary.total_cost.toLocaleString('id-ID')}`],
        ['Gross Profit:', `Rp ${profitData.summary.gross_profit.toLocaleString('id-ID')}`],
        ['Gross Profit Margin:', `${profitData.summary.gross_profit_margin.toFixed(1)}%`],
        ['Total Tax:', `Rp ${profitData.summary.total_tax.toLocaleString('id-ID')}`],
        ['Total Discount:', `Rp ${profitData.summary.total_discount.toLocaleString('id-ID')}`],
        ['Net Profit:', `Rp ${profitData.summary.net_profit.toLocaleString('id-ID')}`],
        ['Net Profit Margin:', `${profitData.summary.net_profit_margin.toFixed(1)}%`],
        ['Total Orders:', profitData.summary.total_orders.toString()],
        ['Average Profit:', `Rp ${profitData.summary.average_profit.toLocaleString('id-ID')}`],
        ['Profitability Ratio:', `${profitData.summary.profitability_ratio.toFixed(1)}%`]
      ]

      summaryData.forEach(row => {
        worksheetData.push([row[0], row[1]]) // Only 2 columns needed
      })

      worksheetData.push([]) // Empty row
      worksheetData.push([]) // Empty row

      // Daily Data Section Header
      worksheetData.push(['RINCIAN HARIAN']) // Section header
      worksheetData.push([]) // Empty row

      // Prepare date columns - ambil dari daily data
      const dateColumns = profitData.data.map(daily => {
        const date = new Date(daily.date)
        return date.toLocaleDateString('id-ID', {
          day: '2-digit',
          month: 'short'
        })
      })

      // Header row untuk tabel daily data (hanya tanggal)
      const headerRow = ['NO', 'KET', '', ...dateColumns]
      worksheetData.push(headerRow)

      // Prepare data rows
      const rows = this.prepareProfitLossRows(profitData)

      // Add data rows ke worksheet (hanya nilai per tanggal)
      rows.forEach(row => {
        const rowData = [
          row.no,
          row.label,
          ':',
          ...row.values.map(val => val.today) // Store as numbers for better Excel handling
        ]
        worksheetData.push(rowData)
      })

      // Create workbook dan worksheet
      const workbook = XLSX.utils.book_new()
      const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)

      // Apply basic formatting
      this.applyBasicFormatting(worksheet, dateColumns.length, worksheetData.length, XLSX)

      // Add worksheet ke workbook
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Laba Rugi')

      // Generate filename
      const exportFilename = filename || this.generateFilename('Laba_Rugi')

      // Download file
      XLSX.writeFile(workbook, exportFilename)

      return { success: true, filename: exportFilename }
    } catch (error) {
      console.error('Error exporting to Excel:', error)
      return { success: false, error: 'Failed to export Excel file' }
    }
  }

  /**
   * Prepare profit loss data rows (tanpa percentage)
   */
  private static prepareProfitLossRows(profitData: ProfitLossReport) {
    return [
      {
        no: 1,
        label: 'TOTAL PENJ',
        values: profitData.data.map(daily => ({
          today: daily.revenue,
          mtd: daily.revenue // TODO: Replace with actual MTD data from API
        }))
      },
      {
        no: 2,
        label: 'HPP',
        values: profitData.data.map(daily => ({
          today: daily.cost,
          mtd: daily.cost
        }))
      },
      {
        no: 3,
        label: 'Laba Kotor (1-2)',
        values: profitData.data.map(daily => ({
          today: daily.gross_profit,
          mtd: daily.gross_profit
        }))
      },
      {
        no: 4,
        label: 'Biaya lain',
        values: profitData.data.map(daily => {
          const totalCosts = daily.tax + daily.discount
          return {
            today: totalCosts,
            mtd: totalCosts
          }
        })
      },
      {
        no: 5,
        label: 'Laba/Rugi (3-4)',
        values: profitData.data.map(daily => ({
          today: daily.net_profit,
          mtd: daily.net_profit
        }))
      }
    ]
  }

  /**
   * Apply basic formatting (SheetJS compatible)
   */
  private static applyBasicFormatting(worksheet: any, dateColumnsCount: number, totalRows: number, XLSX: any) {
    // Set column widths
    const colWidths = [
      { wch: 5 }, // NO
      { wch: 25 }, // KET
      { wch: 3 }, // :
      ...Array(dateColumnsCount).fill({ wch: 18 })
    ]
    worksheet['!cols'] = colWidths

    // Set row heights for better spacing
    worksheet['!rows'] = [
      { hpt: 30 }, // Title row
      { hpt: 25 }, // Period row
      { hpt: 15 }, // Empty row
      { hpt: 25 }, // Summary header
      { hpt: 15 } // Empty row
    ]

    // Merge cells untuk headers
    const merges = [
      { s: { r: 0, c: 0 }, e: { r: 0, c: dateColumnsCount + 2 } }, // Title
      { s: { r: 1, c: 0 }, e: { r: 1, c: dateColumnsCount + 2 } }, // Period
      { s: { r: 3, c: 0 }, e: { r: 3, c: dateColumnsCount + 2 } } // Summary header
    ]

    // Find and add merge for daily data header
    for (let i = 0; i < totalRows; i++) {
      const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
      if (cell && cell.v === 'RINCIAN HARIAN') {
        merges.push({ s: { r: i, c: 0 }, e: { r: i, c: dateColumnsCount + 2 } })
        break
      }
    }

    worksheet['!merges'] = merges

    // Apply number formatting untuk currency cells
    this.applyNumberFormatting(worksheet, totalRows, dateColumnsCount + 3, XLSX)
  }

  /**
   * Apply number formatting for currency
   */
  private static applyNumberFormatting(worksheet: any, totalRows: number, totalCols: number, XLSX: any) {
    // Find table data start (after "NO" header)
    let dataStartRow = -1
    for (let i = 0; i < totalRows; i++) {
      const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
      if (cell && cell.v === 'NO') {
        dataStartRow = i + 1
        break
      }
    }

    if (dataStartRow === -1) return

    // Apply currency formatting to data cells (starting from column 3 - after NO, KET, :)
    for (let row = dataStartRow; row < dataStartRow + 5; row++) {
      // 5 data rows
      for (let col = 3; col < totalCols; col++) {
        const cellAddress = XLSX.utils.encode_cell({ r: row, c: col })
        const cell = worksheet[cellAddress]

        if (cell && typeof cell.v === 'number') {
          // Apply Indonesian currency format
          cell.z = '#,##0'
          cell.t = 'n'
        }
      }
    }
  }

  /**
   * Generate filename with timestamp
   */
  private static generateFilename(prefix: string): string {
    const now = new Date()
    const year = now.getFullYear()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')
    const hour = now.getHours().toString().padStart(2, '0')
    const minute = now.getMinutes().toString().padStart(2, '0')

    return `${prefix}_${year}_${month}_${day}_${hour}${minute}.xlsx`
  }

  /**
   * Export any data to Excel with custom configuration
   */
  static async exportToExcel(
    data: any[][],
    sheetName: string = 'Sheet1',
    filename?: string,
    options?: {
      colWidths?: { wch: number }[]
      merges?: { s: { r: number; c: number }; e: { r: number; c: number } }[]
    }
  ) {
    try {
      const XLSX = await import('xlsx')

      const workbook = XLSX.utils.book_new()
      const worksheet = XLSX.utils.aoa_to_sheet(data)

      // Apply options
      if (options?.colWidths) {
        worksheet['!cols'] = options.colWidths
      }
      if (options?.merges) {
        worksheet['!merges'] = options.merges
      }

      XLSX.utils.book_append_sheet(workbook, worksheet, sheetName)

      const exportFilename = filename || this.generateFilename('Export')
      XLSX.writeFile(workbook, exportFilename)

      return { success: true, filename: exportFilename }
    } catch (error) {
      console.error('Error exporting to Excel:', error)
      return { success: false, error: 'Failed to export Excel file' }
    }
  }
}
