// services/excelExportCategoryService.ts
import type { CategoryReport } from '@/types/services/analytic'

export class ExcelExportSalesProductCategoryService {
  /**
   * Export Category Sales Report to Excel
   */
  static async exportCategorySalesToExcel(categoryData: CategoryReport, filename?: string) {
    try {
      // Dynamic import untuk xlsx library
      const XLSX = await import('xlsx')

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

      // Header dengan report info (baris 1-2)
      worksheetData.push(['LAPORAN PENJUALAN KATEGORI']) // Row 0 - Main title
      worksheetData.push([`Periode: ${categoryData.date_from.split('T')[0]} - ${categoryData.date_to.split('T')[0]}`]) // Row 1 - Period
      worksheetData.push([]) // Empty row

      // Calculate summary
      const categorySummary = {
        totalRevenue: categoryData.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
        orderCount: categoryData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
        productCount: categoryData.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
        totalQuantity: categoryData.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0,
        totalCategories: categoryData.data?.length || 0
      }

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

      const summaryData = [
        ['Total Kategori:', categorySummary.totalCategories.toString()],
        ['Total Produk:', categorySummary.productCount.toString()],
        ['Total Quantity:', categorySummary.totalQuantity.toString()],
        ['Total Orders:', categorySummary.orderCount.toString()],
        ['Total Revenue:', `Rp ${categorySummary.totalRevenue.toLocaleString('id-ID')}`]
      ]

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

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

      // Category Details Section Header
      worksheetData.push(['RINCIAN KATEGORI']) // Section header
      worksheetData.push([]) // Empty row

      // Header row untuk tabel category data
      const headerRow = ['No', 'Nama', 'Total Produk', 'Qty', 'Total Orders', 'Pendapatan']
      worksheetData.push(headerRow)

      // Add category data rows
      categoryData.data?.forEach((category, index) => {
        const rowData = [
          index + 1, // No
          category.category_name,
          category.product_count,
          category.total_quantity,
          category.order_count,
          category.total_revenue // Store as number for Excel formatting
        ]
        worksheetData.push(rowData)
      })

      // Add total row
      const totalRow = [
        'TOTAL',
        '',
        categorySummary.productCount,
        categorySummary.totalQuantity,
        categorySummary.orderCount,
        categorySummary.totalRevenue
      ]
      worksheetData.push(totalRow)

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

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

      // Add worksheet ke workbook
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Penjualan Kategori')

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

      // 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' }
    }
  }

  /**
   * Apply basic formatting (SheetJS compatible)
   */
  private static applyBasicFormatting(worksheet: any, totalRows: number, XLSX: any) {
    // Set column widths
    const colWidths = [
      { wch: 8 }, // No
      { wch: 30 }, // Nama
      { wch: 15 }, // Total Produk
      { wch: 12 }, // Qty
      { wch: 15 }, // Total Orders
      { wch: 20 } // Pendapatan
    ]
    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: 5 } }, // Title (span across all columns)
      { s: { r: 1, c: 0 }, e: { r: 1, c: 5 } }, // Period (span across all columns)
      { s: { r: 3, c: 0 }, e: { r: 3, c: 5 } } // Summary header (span across all columns)
    ]

    // Find and add merge for category details header
    for (let i = 0; i < totalRows; i++) {
      const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
      if (cell && cell.v === 'RINCIAN KATEGORI') {
        merges.push({ s: { r: i, c: 0 }, e: { r: i, c: 5 } }) // Span across all columns
        break
      }
    }

    worksheet['!merges'] = merges

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

  /**
   * Apply number formatting for currency and styling
   */
  private static applyNumberFormatting(worksheet: any, totalRows: number, XLSX: any) {
    // Find table data start (after header row)
    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

    // Count actual data rows (excluding total row)
    const dataRowsCount = totalRows - dataStartRow - 1 // -1 for total row

    // Apply currency formatting to Pendapatan column (column 5 - index 5)
    for (let row = dataStartRow; row <= dataStartRow + dataRowsCount; row++) {
      // Include total row
      const cellAddress = XLSX.utils.encode_cell({ r: row, c: 5 }) // Pendapatan column
      const cell = worksheet[cellAddress]

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

    // Apply styling to header row
    const headerRowIndex = dataStartRow - 1
    for (let col = 0; col < 6; col++) {
      const cellAddress = XLSX.utils.encode_cell({ r: headerRowIndex, c: col })
      const cell = worksheet[cellAddress]

      if (cell) {
        // Apply bold formatting (basic approach for SheetJS)
        cell.s = {
          font: { bold: true },
          fill: { fgColor: { rgb: 'F3F4F6' } }, // Light gray background
          border: {
            bottom: { style: 'medium', color: { rgb: '000000' } }
          }
        }
      }
    }

    // Apply styling to total row
    const totalRowIndex = dataStartRow + dataRowsCount
    for (let col = 0; col < 6; col++) {
      const cellAddress = XLSX.utils.encode_cell({ r: totalRowIndex, c: col })
      const cell = worksheet[cellAddress]

      if (cell) {
        // Apply bold formatting for total row
        cell.s = {
          font: { bold: true },
          border: {
            top: { style: 'medium', color: { rgb: '000000' } }
          }
        }
      }
    }
  }

  /**
   * 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 Category Sales data with custom configuration
   */
  static async exportCustomCategoryData(
    categoryData: CategoryReport,
    options?: {
      includeSummary?: boolean
      includeOrderCount?: boolean
      customFilename?: string
      sheetName?: string
    }
  ) {
    try {
      const XLSX = await import('xlsx')
      const worksheetData: any[][] = []

      // Always include title and period
      worksheetData.push(['LAPORAN PENJUALAN KATEGORI'])
      worksheetData.push([`Periode: ${categoryData.date_from.split('T')[0]} - ${categoryData.date_to.split('T')[0]}`])
      worksheetData.push([])

      // Optional summary
      if (options?.includeSummary !== false) {
        const categorySummary = {
          totalRevenue: categoryData.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
          orderCount: categoryData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
          productCount: categoryData.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
          totalQuantity: categoryData.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0,
          totalCategories: categoryData.data?.length || 0
        }

        worksheetData.push(['RINGKASAN PERIODE'])
        worksheetData.push([])
        const summaryData = [
          ['Total Kategori:', categorySummary.totalCategories.toString()],
          ['Total Produk:', categorySummary.productCount.toString()],
          ['Total Quantity:', categorySummary.totalQuantity.toString()],
          ['Total Revenue:', `Rp ${categorySummary.totalRevenue.toLocaleString('id-ID')}`]
        ]
        summaryData.forEach(row => worksheetData.push([row[0], row[1]]))
        worksheetData.push([])
        worksheetData.push([])
      }

      worksheetData.push(['RINCIAN KATEGORI'])
      worksheetData.push([])

      // Header row based on options
      const headerRow =
        options?.includeOrderCount !== false
          ? ['No', 'Nama', 'Total Produk', 'Qty', 'Total Orders', 'Pendapatan']
          : ['No', 'Nama', 'Total Produk', 'Qty', 'Pendapatan']
      worksheetData.push(headerRow)

      // Add category data based on options
      categoryData.data?.forEach((category, index) => {
        const rowData =
          options?.includeOrderCount !== false
            ? [
                index + 1,
                category.category_name,
                category.product_count,
                category.total_quantity,
                category.order_count,
                category.total_revenue
              ]
            : [
                index + 1,
                category.category_name,
                category.product_count,
                category.total_quantity,
                category.total_revenue
              ]
        worksheetData.push(rowData)
      })

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

      this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)

      const sheetName = options?.sheetName || 'Penjualan Kategori'
      XLSX.utils.book_append_sheet(workbook, worksheet, sheetName)

      const exportFilename = options?.customFilename || this.generateFilename('Custom_Category_Sales')
      XLSX.writeFile(workbook, exportFilename)

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