'use client'

import {
  useProductSalesAnalytics,
  useProfitLossAnalytics,
  useSalesAnalytics,
  usePaymentAnalytics,
  useCategoryAnalytics
} from '@/services/queries/analytics'
import { useOutletById } from '@/services/queries/outlets'
import { formatCurrency, formatDate, formatDateDDMMYYYY, formatDatetime } from '@/utils/transform'
import ReportGeneratorComponent from '@/views/dashboards/daily-report/report-generator'
import ReportHeader from '@/views/dashboards/daily-report/report-header'
import React, { useEffect, useRef, useState } from 'react'

const DailyPOSReport = () => {
  const reportRef = useRef<HTMLDivElement | null>(null)

  const [now, setNow] = useState(new Date())
  const [selectedDate, setSelectedDate] = useState(new Date())
  const [dateRange, setDateRange] = useState({
    startDate: new Date(),
    endDate: new Date()
  })
  const [filterType, setFilterType] = useState<'single' | 'range'>('single')
  const [isGeneratingPDF, setIsGeneratingPDF] = useState(false)

  // PDF Font Size Configuration
  const PDF_FONT_SIZES = {
    heading: 20,
    subheading: 20,
    tableContent: 14,
    tableHeader: 14,
    tableFooter: 14,
    grandTotal: 18,
    footer: 11
  }

  // PDF Spacing Configuration
  const PDF_SPACING = {
    cellPadding: 5,
    cellPaddingLarge: 6,
    sectionGap: 20,
    headerGap: 15
  }

  const getDateParams = () => {
    if (filterType === 'single') {
      return {
        date_from: formatDateDDMMYYYY(selectedDate),
        date_to: formatDateDDMMYYYY(selectedDate)
      }
    } else {
      return {
        date_from: formatDateDDMMYYYY(dateRange.startDate),
        date_to: formatDateDDMMYYYY(dateRange.endDate)
      }
    }
  }

  const dateParams = getDateParams()

  const { data: outlet } = useOutletById()
  const { data: sales } = useSalesAnalytics(dateParams)
  const { data: profitLoss } = useProfitLossAnalytics(dateParams)
  const { data: products } = useProductSalesAnalytics(dateParams)
  const { data: paymentAnalytics } = usePaymentAnalytics(dateParams)
  const { data: category } = useCategoryAnalytics(dateParams)

  const productSummary = {
    totalQuantitySold: products?.data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0,
    totalRevenue: products?.data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
    totalOrders: products?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
  }

  const categorySummary = {
    totalRevenue: category?.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
    orderCount: category?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
    productCount: category?.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
    totalQuantity: category?.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0
  }

  useEffect(() => {
    setNow(new Date())
  }, [])

  const formatDateForInput = (date: Date) => {
    return date.toISOString().split('T')[0]
  }

  const getReportPeriodText = () => {
    if (filterType === 'single') {
      return `${formatDateDDMMYYYY(selectedDate)} - ${formatDateDDMMYYYY(selectedDate)}`
    } else {
      return `${formatDateDDMMYYYY(dateRange.startDate)} - ${formatDateDDMMYYYY(dateRange.endDate)}`
    }
  }

  const getReportTitle = () => {
    if (filterType === 'single') {
      return 'Laporan Transaksi'
    } else {
      return `Laporan Transaksi`
    }
  }

  const handleGeneratePDF = async () => {
    const reportElement = reportRef.current

    if (!reportElement) {
      alert('Report element tidak ditemukan')
      return
    }

    setIsGeneratingPDF(true)

    try {
      const jsPDF = (await import('jspdf')).default
      const html2canvas = (await import('html2canvas')).default
      const autoTable = (await import('jspdf-autotable')).default

      const pdf = new jsPDF({
        orientation: 'portrait',
        unit: 'mm',
        format: 'a4',
        compress: true
      })

      // Capture header section only (tanpa tabel kategori)
      const headerElement = reportElement.querySelector('.report-header-section') as HTMLElement
      if (headerElement) {
        const headerCanvas = await html2canvas(headerElement, {
          scale: 2,
          useCORS: true,
          backgroundColor: '#ffffff',
          logging: false,
          windowWidth: 794
        })

        const headerImgWidth = 190
        const headerImgHeight = (headerCanvas.height * headerImgWidth) / headerCanvas.width
        const headerImgData = headerCanvas.toDataURL('image/jpeg', 0.95)

        pdf.addImage(headerImgData, 'JPEG', 10, 10, headerImgWidth, headerImgHeight)
      }

      let currentY = 80 // Start position after header

      // Add summary sections with autoTable
      pdf.setFontSize(PDF_FONT_SIZES.heading)
      pdf.setTextColor(54, 23, 94)
      pdf.setFont('helvetica', 'bold')
      pdf.text('Ringkasan', 14, currentY)
      currentY += 15

      // Summary table
      autoTable(pdf, {
        startY: currentY,
        head: [],
        body: [
          ['Total Penjualan', formatCurrency(profitLoss?.summary.total_revenue ?? 0)],
          ['Total Diskon', formatCurrency(profitLoss?.summary.total_discount ?? 0)],
          ['Total Pajak', formatCurrency(profitLoss?.summary.total_tax ?? 0)],
          ['Total', formatCurrency(profitLoss?.summary.total_revenue ?? 0)]
        ],
        theme: 'plain',
        styles: { fontSize: PDF_FONT_SIZES.tableContent, cellPadding: PDF_SPACING.cellPadding },
        columnStyles: {
          0: { fontStyle: 'normal', textColor: [60, 60, 60] },
          1: { halign: 'right', fontStyle: 'bold', textColor: [60, 60, 60] }
        },
        margin: { left: 14, right: 14 }
      })

      currentY = (pdf as any).lastAutoTable.finalY + 20

      // Invoice section
      pdf.setFontSize(PDF_FONT_SIZES.heading)
      pdf.text('Invoice', 14, currentY)
      currentY += 15

      autoTable(pdf, {
        startY: currentY,
        head: [],
        body: [['Total Invoice', String(profitLoss?.summary.total_orders ?? 0)]],
        theme: 'plain',
        styles: { fontSize: PDF_FONT_SIZES.tableContent, cellPadding: PDF_SPACING.cellPadding },
        columnStyles: {
          0: { fontStyle: 'normal', textColor: [60, 60, 60] },
          1: { halign: 'right', fontStyle: 'bold', textColor: [60, 60, 60] }
        },
        margin: { left: 14, right: 14 }
      })

      pdf.addPage()
      currentY = 20
      // Payment Method Summary
      pdf.setFontSize(PDF_FONT_SIZES.heading)
      pdf.text('Ringkasan Metode Pembayaran', 14, currentY)
      currentY += 15

      const paymentBody =
        paymentAnalytics?.data?.map(payment => [
          payment.payment_method_name,
          payment.payment_method_type.toUpperCase(),
          String(payment.order_count),
          formatCurrency(payment.total_amount),
          `${(payment.percentage ?? 0).toFixed(1)}%`
        ]) || []

      autoTable(pdf, {
        startY: currentY,
        head: [['Metode Pembayaran', 'Tipe', 'Jumlah Order', 'Total Amount', 'Persentase']],
        body: paymentBody,
        foot: [
          [
            'TOTAL',
            '',
            String(paymentAnalytics?.summary.total_orders ?? 0),
            formatCurrency(paymentAnalytics?.summary.total_amount ?? 0),
            ''
          ]
        ],
        theme: 'striped',
        styles: { fontSize: PDF_FONT_SIZES.tableContent, cellPadding: PDF_SPACING.cellPadding },
        headStyles: {
          fillColor: [54, 23, 94],
          textColor: 255,
          fontStyle: 'bold',
          fontSize: PDF_FONT_SIZES.tableHeader
        },
        footStyles: {
          fillColor: [220, 220, 220],
          textColor: [60, 60, 60],
          fontStyle: 'bold',
          fontSize: PDF_FONT_SIZES.tableFooter
        },
        columnStyles: {
          1: { halign: 'center' },
          2: { halign: 'center' },
          3: { halign: 'right' },
          4: { halign: 'center' }
        },
        margin: { left: 14, right: 14 }
      })

      currentY = (pdf as any).lastAutoTable.finalY + 20

      // Category Summary
      pdf.setFontSize(PDF_FONT_SIZES.heading)
      pdf.text('Ringkasan Kategori', 14, currentY)
      currentY += 15

      const categoryBody =
        category?.data?.map(c => [c.category_name, String(c.total_quantity), formatCurrency(c.total_revenue)]) || []

      autoTable(pdf, {
        startY: currentY,
        head: [['Nama', 'Qty', 'Pendapatan']],
        body: categoryBody,
        foot: [
          ['TOTAL', String(categorySummary?.totalQuantity ?? 0), formatCurrency(categorySummary?.totalRevenue ?? 0)]
        ],
        theme: 'striped',
        styles: { fontSize: PDF_FONT_SIZES.tableContent, cellPadding: PDF_SPACING.cellPadding },
        headStyles: {
          fillColor: [54, 23, 94],
          textColor: 255,
          fontStyle: 'bold',
          fontSize: PDF_FONT_SIZES.tableHeader
        },
        footStyles: {
          fillColor: [220, 220, 220],
          textColor: [60, 60, 60],
          fontStyle: 'bold',
          fontSize: PDF_FONT_SIZES.tableFooter
        },
        columnStyles: {
          1: { halign: 'center' },
          2: { halign: 'right' }
        },
        margin: { left: 14, right: 14 }
      })

      // Group products by category
      const groupedProducts =
        products?.data?.reduce(
          (acc, item) => {
            const categoryName = item.category_name || 'Tidak Berkategori'
            if (!acc[categoryName]) {
              acc[categoryName] = []
            }
            acc[categoryName].push(item)
            return acc
          },
          {} as Record<string, any[]>
        ) || {}

      // Add new page for product details
      pdf.addPage()
      currentY = 20

      pdf.setFontSize(PDF_FONT_SIZES.heading)
      pdf.text('Ringkasan Item Per Kategori', 14, currentY)
      currentY += 15

      // Loop through each category
      Object.keys(groupedProducts)
        .sort((a, b) => {
          const productsA = groupedProducts[a]
          const productsB = groupedProducts[b]
          const orderA = productsA[0]?.category_order ?? 999
          const orderB = productsB[0]?.category_order ?? 999
          return orderA - orderB
        })
        .forEach(categoryName => {
          const categoryProducts = groupedProducts[categoryName]
          const categoryTotalQty = categoryProducts.reduce((sum, item) => sum + (item.quantity_sold || 0), 0)
          const categoryTotalRevenue = categoryProducts.reduce((sum, item) => sum + (item.revenue || 0), 0)

          const productBody = categoryProducts.map(item => [
            item.product_name,
            String(item.quantity_sold),
            formatCurrency(item.revenue)
          ])

          // Check if we need a new page
          const estimatedHeight = (productBody.length + 3) * 12 // Adjusted for larger font
          if (currentY + estimatedHeight > 270) {
            pdf.addPage()
            currentY = 20
          }

          // Category header
          pdf.setFontSize(20)
          pdf.setFont('helvetica', 'bold')
          pdf.setTextColor(54, 23, 94)
          pdf.text(categoryName.toUpperCase(), 16, currentY)
          currentY += 15

          // Category table
          autoTable(pdf, {
            startY: currentY,
            head: [['Produk', 'Qty', 'Pendapatan']],
            body: productBody,
            foot: [[`Subtotal ${categoryName}`, String(categoryTotalQty), formatCurrency(categoryTotalRevenue)]],
            theme: 'striped',
            styles: { fontSize: PDF_FONT_SIZES.tableContent, cellPadding: PDF_SPACING.cellPadding },
            headStyles: {
              fillColor: [54, 23, 94],
              textColor: 255,
              fontStyle: 'bold',
              fontSize: PDF_FONT_SIZES.tableHeader
            },
            footStyles: { fillColor: [200, 200, 200], textColor: [60, 60, 60], fontStyle: 'bold', fontSize: 20 },
            columnStyles: {
              0: { cellWidth: 90 },
              1: { halign: 'center', cellWidth: 40 },
              2: { halign: 'right', cellWidth: 52 }
            },
            margin: { left: 14, right: 14 }
          })

          currentY = (pdf as any).lastAutoTable.finalY + 15
        })

      // Grand Total
      if (currentY > 250) {
        pdf.addPage()
        currentY = 20
      }

      autoTable(pdf, {
        startY: currentY,
        head: [],
        body: [
          ['TOTAL KESELURUHAN', String(productSummary.totalQuantitySold), formatCurrency(productSummary.totalRevenue)]
        ],
        theme: 'plain',
        styles: { fontSize: PDF_FONT_SIZES.grandTotal, cellPadding: 6, fontStyle: 'bold', textColor: [54, 23, 94] },
        columnStyles: {
          0: { cellWidth: 90 },
          1: { halign: 'center', cellWidth: 40 },
          2: { halign: 'right', cellWidth: 52 }
        },
        margin: { left: 14, right: 14 },
        didDrawCell: data => {
          pdf.setDrawColor(54, 23, 94)
          pdf.setLineWidth(0.5)
        }
      })

      // Footer
      const pageCount = pdf.getNumberOfPages()
      for (let i = 1; i <= pageCount; i++) {
        pdf.setPage(i)
        pdf.setFontSize(11)
        pdf.setTextColor(120, 120, 120)
        pdf.text('© 2025 Apskel - Sistem POS Terpadu', 14, 287)
        pdf.text(`Dicetak pada: ${now.toLocaleDateString('id-ID')}`, 190, 287, { align: 'right' })
      }

      const fileName =
        filterType === 'single'
          ? `laporan-transaksi-${formatDateForInput(selectedDate)}.pdf`
          : `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`

      pdf.save(fileName)
    } catch (error) {
      console.error('Error generating PDF:', error)
      alert(`Terjadi kesalahan saat membuat PDF: ${error}`)
    } finally {
      setIsGeneratingPDF(false)
    }
  }

  const LoadingOverlay = ({ isVisible, message = 'Generating PDF...' }: { isVisible: boolean; message?: string }) => {
    if (!isVisible) return null

    return (
      <div className='fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm'>
        <div className='bg-white rounded-lg shadow-xl p-8 max-w-sm w-full mx-4'>
          <div className='text-center'>
            <div className='inline-block animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-purple-600 mb-4'></div>
            <h3 className='text-lg font-semibold text-gray-800 mb-2'>{message}</h3>
            <p className='text-sm text-gray-600'>Mohon tunggu, proses ini mungkin membutuhkan beberapa detik...</p>
            <div className='mt-6 space-y-2'>
              <div className='flex items-center text-xs text-gray-500'>
                <div className='w-2 h-2 bg-green-500 rounded-full mr-2 flex-shrink-0'></div>
                <span>Capturing report content</span>
              </div>
              <div className='flex items-center text-xs text-gray-500'>
                <div className='w-2 h-2 bg-blue-500 rounded-full mr-2 flex-shrink-0 animate-pulse'></div>
                <span>Processing pages</span>
              </div>
              <div className='flex items-center text-xs text-gray-500'>
                <div className='w-2 h-2 bg-gray-300 rounded-full mr-2 flex-shrink-0'></div>
                <span>Finalizing PDF</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }

  // Group products by category
  const groupedProducts =
    products?.data?.reduce(
      (acc, item) => {
        const categoryName = item.category_name || 'Tidak Berkategori'
        if (!acc[categoryName]) {
          acc[categoryName] = []
        }
        acc[categoryName].push(item)
        return acc
      },
      {} as Record<string, any[]>
    ) || {}

  return (
    <div className='min-h-screen'>
      <LoadingOverlay isVisible={isGeneratingPDF} message='Membuat PDF Laporan...' />

      <ReportGeneratorComponent
        reportTitle='Laporan Penjualan'
        filterType={filterType}
        selectedDate={selectedDate}
        dateRange={dateRange}
        onFilterTypeChange={setFilterType}
        onSingleDateChange={setSelectedDate}
        onDateRangeChange={setDateRange}
        onGeneratePDF={handleGeneratePDF}
      />

      <div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
        {/* Wrap header in a section for easy capture */}
        <div className='report-header-section'>
          <ReportHeader
            outlet={outlet}
            reportTitle={getReportTitle()}
            reportSubtitle='Laporan Bulanan'
            brandName='Apskel'
            brandColor='#36175e'
            periode={getReportPeriodText()}
          />
        </div>

        {/* Performance Summary */}
        <div className='p-8'>
          <h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
            Ringkasan
          </h3>

          <div className='space-y-5'>
            <div className='flex justify-between items-center py-3 border-b border-gray-200'>
              <span className='text-xl text-gray-700'>Total Penjualan</span>
              <span className='text-xl font-semibold text-gray-800'>
                {formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
              </span>
            </div>
            <div className='flex justify-between items-center py-3 border-b border-gray-200'>
              <span className='text-xl text-gray-700'>Total Diskon</span>
              <span className='text-xl font-semibold text-gray-800'>
                {formatCurrency(profitLoss?.summary.total_discount ?? 0)}
              </span>
            </div>
            <div className='flex justify-between items-center py-3 border-b border-gray-200'>
              <span className='text-xl text-gray-700'>Total Pajak</span>
              <span className='text-xl font-semibold text-gray-800'>
                {formatCurrency(profitLoss?.summary.total_tax ?? 0)}
              </span>
            </div>
            <div className='flex justify-between items-center py-3 border-b-2 border-gray-300'>
              <span className='text-xl text-gray-700 font-bold'>Total</span>
              <span className='text-xl font-bold text-gray-800'>
                {formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
              </span>
            </div>
          </div>
        </div>

        {/* Invoice */}
        <div className='px-8 pb-8'>
          <h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
            Invoice
          </h3>

          <div className='space-y-5'>
            <div className='flex justify-between items-center py-3 border-b border-gray-200'>
              <span className='text-xl text-gray-700'>Total Invoice</span>
              <span className='text-xl font-semibold text-gray-800'>{profitLoss?.summary.total_orders ?? 0}</span>
            </div>
          </div>
        </div>

        {/* Payment Method Summary */}
        <div className='px-8 pb-8'>
          <h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
            Ringkasan Metode Pembayaran
          </h3>

          <div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
            <table className='w-full'>
              <thead>
                <tr className='text-gray-800 border-b-2 border-gray-300'>
                  <th className='text-left text-xl p-4 font-semibold'>Metode Pembayaran</th>
                  <th className='text-center text-xl p-4 font-semibold'>Tipe</th>
                  <th className='text-center text-xl p-4 font-semibold'>Jumlah Order</th>
                  <th className='text-right text-xl p-4 font-semibold'>Total Amount</th>
                  <th className='text-center text-xl p-4 font-semibold'>Persentase</th>
                </tr>
              </thead>
              <tbody>
                {paymentAnalytics?.data?.map((payment, index) => (
                  <tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                    <td className='p-4 text-xl font-medium text-gray-800'>{payment.payment_method_name}</td>
                    <td className='p-4 text-center'>
                      <span
                        className={`px-3 py-1 rounded-full text-lg font-medium ${
                          payment.payment_method_type === 'cash'
                            ? 'bg-green-100 text-green-800'
                            : 'bg-blue-100 text-blue-800'
                        }`}
                      >
                        {payment.payment_method_type.toUpperCase()}
                      </span>
                    </td>
                    <td className='p-4 text-xl text-center text-gray-700'>{payment.order_count}</td>
                    <td className='p-4 text-xl text-right font-semibold text-gray-800'>
                      {formatCurrency(payment.total_amount)}
                    </td>
                    <td className='p-4 text-xl text-center font-medium' style={{ color: '#36175e' }}>
                      {(payment.percentage ?? 0).toFixed(1)}%
                    </td>
                  </tr>
                )) || []}
              </tbody>
              <tfoot>
                <tr className='text-gray-800 border-t-2 border-gray-300'>
                  <td className='p-4 text-xl font-bold'>TOTAL</td>
                  <td className='p-4'></td>
                  <td className='p-4 text-xl text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
                  <td className='p-4 text-xl text-right font-bold'>
                    {formatCurrency(paymentAnalytics?.summary.total_amount ?? 0)}
                  </td>
                  <td className='p-4 text-center font-bold'></td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        {/* Category Summary */}
        <div className='px-8 pb-8'>
          <h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
            Ringkasan Kategori
          </h3>

          <div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
            <table className='w-full'>
              <thead>
                <tr className='text-gray-800 border-b-2 border-gray-300'>
                  <th className='text-left text-xl p-4 font-semibold'>Nama</th>
                  <th className='text-center text-xl p-4 font-semibold'>Qty</th>
                  <th className='text-right text-xl p-4 font-semibold'>Pendapatan</th>
                </tr>
              </thead>
              <tbody>
                {category?.data?.map((c, index) => (
                  <tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                    <td className='p-4 text-xl font-medium text-gray-800'>{c.category_name}</td>
                    <td className='p-4 text-xl text-center text-gray-700'>{c.total_quantity}</td>
                    <td className='p-4 text-xl text-right font-semibold' style={{ color: '#36175e' }}>
                      {formatCurrency(c.total_revenue)}
                    </td>
                  </tr>
                )) || []}
              </tbody>
              <tfoot>
                <tr className='text-gray-800 border-t-2 border-gray-300'>
                  <td className='p-4 text-xl font-bold'>TOTAL</td>
                  <td className='p-4 text-xl text-center font-bold'>{categorySummary?.totalQuantity ?? 0}</td>
                  <td className='p-4 text-xl text-right font-bold'>
                    {formatCurrency(categorySummary?.totalRevenue ?? 0)}
                  </td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        {/* Product Summary - Dipisah per kategori dengan tabel terpisah */}
        <div className='px-8 pb-8'>
          <h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
            Ringkasan Item Per Kategori
          </h3>

          <div className='space-y-12'>
            {Object.keys(groupedProducts)
              .sort((a, b) => {
                const productsA = groupedProducts[a]
                const productsB = groupedProducts[b]
                const orderA = productsA[0]?.category_order ?? 999
                const orderB = productsB[0]?.category_order ?? 999
                return orderA - orderB
              })
              .map((categoryName, catIndex) => {
                const categoryProducts = groupedProducts[categoryName]
                const categoryTotalQty = categoryProducts.reduce((sum, item) => sum + (item.quantity_sold || 0), 0)
                const categoryTotalRevenue = categoryProducts.reduce((sum, item) => sum + (item.revenue || 0), 0)

                return (
                  <div key={categoryName} style={{ display: 'block', marginBottom: '70px' }}>
                    <h4
                      className='text-2xl font-bold mb-0 px-4 py-4 bg-gray-100 rounded-t-lg'
                      style={{ color: '#36175e' }}
                    >
                      {categoryName.toUpperCase()}
                    </h4>

                    <div className='bg-gray-50 rounded-b-lg border-l-2 border-r-2 border-b-2 border-gray-300'>
                      <table
                        className='w-full'
                        style={{ borderCollapse: 'collapse', tableLayout: 'fixed', width: '100%' }}
                      >
                        <colgroup>
                          <col style={{ width: '50%' }} />
                          <col style={{ width: '20%' }} />
                          <col style={{ width: '30%' }} />
                        </colgroup>
                        <thead>
                          <tr className='text-gray-800 border-b-2 border-gray-300 bg-gray-100'>
                            <th className='text-left text-xl p-5 font-semibold border-r border-gray-300'>Produk</th>
                            <th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>Qty</th>
                            <th className='text-right text-xl p-5 font-semibold'>Pendapatan</th>
                          </tr>
                        </thead>
                        <tbody>
                          {categoryProducts.map((item, index) => (
                            <tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                              <td className='p-5 text-xl font-medium text-gray-800 border-r border-gray-200'>
                                {item.product_name}
                              </td>
                              <td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
                                {item.quantity_sold}
                              </td>
                              <td className='p-5 text-xl text-right font-semibold text-gray-800'>
                                {formatCurrency(item.revenue)}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                        <tfoot>
                          <tr className='bg-gray-200 border-t-2 border-gray-400'>
                            <td className='p-5 text-xl font-bold text-gray-800 border-r border-gray-400'>
                              Subtotal {categoryName}
                            </td>
                            <td className='p-5 text-xl text-center font-bold text-gray-800 border-r border-gray-400'>
                              {categoryTotalQty}
                            </td>
                            <td className='p-5 text-xl text-right font-bold text-gray-800'>
                              {formatCurrency(categoryTotalRevenue)}
                            </td>
                          </tr>
                        </tfoot>
                      </table>
                    </div>
                  </div>
                )
              })}

            {/* Grand Total */}
            <div className='bg-purple-50 rounded-lg border-2 border-purple-300 mt-6'>
              <table className='w-full' style={{ borderCollapse: 'collapse' }}>
                <tfoot>
                  <tr className='text-gray-800'>
                    <td
                      className='p-5 text-2xl font-bold border-r-2 border-purple-300'
                      style={{ width: '50%', color: '#36175e' }}
                    >
                      TOTAL KESELURUHAN
                    </td>
                    <td
                      className='p-5 text-2xl text-center font-bold border-r-2 border-purple-300'
                      style={{ width: '20%', color: '#36175e' }}
                    >
                      {productSummary.totalQuantitySold ?? 0}
                    </td>
                    <td className='p-5 text-2xl text-right font-bold' style={{ width: '30%', color: '#36175e' }}>
                      {formatCurrency(productSummary.totalRevenue ?? 0)}
                    </td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className='px-8 py-6 border-t-2 border-gray-200 mt-8'>
          <div className='flex justify-between items-center text-base text-gray-600'>
            <p>© 2025 Apskel - Sistem POS Terpadu</p>
            <p></p>
            <p>Dicetak pada: {now.toLocaleDateString('id-ID')}</p>
          </div>
        </div>
      </div>
    </div>
  )
}

export default DailyPOSReport
