'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') // 'single' or 'range'
  const [isGeneratingPDF, setIsGeneratingPDF] = useState(false)

  // Use selectedDate for single date filter, or dateRange for range filter
  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())
  }, [])

  // Format date for input field (YYYY-MM-DD)
  const formatDateForInput = (date: Date) => {
    return date.toISOString().split('T')[0]
  }

  // Get display text for the report period
  const getReportPeriodText = () => {
    if (filterType === 'single') {
      return `${formatDateDDMMYYYY(selectedDate)} - ${formatDateDDMMYYYY(selectedDate)}`
    } else {
      return `${formatDateDDMMYYYY(dateRange.startDate)} - ${formatDateDDMMYYYY(dateRange.endDate)}`
    }
  }

  // Get report title based on filter type
  const getReportTitle = () => {
    if (filterType === 'single') {
      return 'Laporan Transaksi'
    } else {
      const daysDiff = Math.ceil((dateRange.endDate.getTime() - dateRange.startDate.getTime()) / (1000 * 3600 * 24)) + 1
      //   return `Laporan Transaksi ${daysDiff} Hari`
      return `Laporan Transaksi`
    }
  }

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

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

    // Set loading state
    setIsGeneratingPDF(true)

    try {
      // Import jsPDF dan html2canvas
      const jsPDF = (await import('jspdf')).default
      const html2canvas = (await import('html2canvas')).default

      // Pastikan element terlihat penuh
      const originalOverflow = reportElement.style.overflow
      reportElement.style.overflow = 'visible'

      // Wait untuk memastikan rendering selesai
      await new Promise(resolve => setTimeout(resolve, 300))

      console.log('Starting PDF generation...')

      // Update loading message
      console.log('Capturing content...')

      // Capture canvas dengan setting yang optimal
      const canvas = await html2canvas(reportElement, {
        scale: 1.5,
        useCORS: true,
        allowTaint: true,
        backgroundColor: '#ffffff',
        logging: false,
        removeContainer: true,
        imageTimeout: 0,
        height: reportElement.scrollHeight,
        width: reportElement.scrollWidth,
        scrollX: 0,
        scrollY: 0,
        // Pastikan capture semua content
        windowWidth: Math.max(reportElement.scrollWidth, window.innerWidth),
        windowHeight: Math.max(reportElement.scrollHeight, window.innerHeight)
      })

      console.log('Canvas captured:', canvas.width, 'x', canvas.height)
      console.log('Generating PDF pages...')

      // Restore overflow
      reportElement.style.overflow = originalOverflow

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

      // A4 dimensions
      const pdfWidth = 210
      const pdfHeight = 297
      const margin = 5 // Small margin to prevent cutoff

      // Calculate scaling
      const availableWidth = pdfWidth - 2 * margin
      const availableHeight = pdfHeight - 2 * margin

      const imgWidth = availableWidth
      const imgHeight = (canvas.height * availableWidth) / canvas.width

      console.log('PDF dimensions - Canvas:', canvas.width, 'x', canvas.height)
      console.log('PDF dimensions - Image:', imgWidth, 'x', imgHeight)
      console.log('Available height per page:', availableHeight)

      // Split content across pages
      let yPosition = margin
      let sourceY = 0
      let pageCount = 1
      let remainingHeight = imgHeight

      while (remainingHeight > 0) {
        console.log(`Processing page ${pageCount}, remaining height: ${remainingHeight}`)

        if (pageCount > 1) {
          pdf.addPage()
          yPosition = margin
        }

        // Calculate how much content fits on this page
        const heightForThisPage = Math.min(remainingHeight, availableHeight)

        // Calculate source dimensions for cropping
        const sourceHeight = (heightForThisPage * canvas.height) / imgHeight

        // Create temporary canvas for this page portion
        const tempCanvas = document.createElement('canvas')
        const tempCtx = tempCanvas.getContext('2d')

        if (!tempCtx) {
          throw new Error('Unable to get 2D context from canvas')
        }

        tempCanvas.width = canvas.width
        tempCanvas.height = sourceHeight

        // Draw the portion we need
        tempCtx.drawImage(
          canvas,
          0,
          sourceY,
          canvas.width,
          sourceHeight, // Source rectangle
          0,
          0,
          canvas.width,
          sourceHeight // Destination rectangle
        )

        // Convert to image data
        const pageImageData = tempCanvas.toDataURL('image/jpeg', 0.9)

        // Add to PDF
        pdf.addImage(pageImageData, 'JPEG', margin, yPosition, imgWidth, heightForThisPage)

        // Update for next page
        sourceY += sourceHeight
        remainingHeight -= heightForThisPage
        pageCount++

        // Safety check to prevent infinite loop
        if (pageCount > 20) {
          console.warn('Too many pages, breaking loop')
          break
        }
      }

      console.log(`Generated ${pageCount - 1} pages`)
      console.log('Finalizing PDF...')

      // Add metadata
      pdf.setProperties({
        title: getReportTitle(),
        subject: 'Transaction Report',
        author: 'Apskel POS System',
        creator: 'Apskel'
      })

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

      console.log('Saving PDF:', fileName)

      // Save PDF
      pdf.save(fileName)

      console.log('PDF generated successfully!')
    } catch (error) {
      console.error('Error generating PDF:', error)
      alert(`Terjadi kesalahan saat membuat PDF: ${error}`)
    } finally {
      // Reset loading state
      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'>
            {/* Animated Spinner */}
            <div className='inline-block animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-purple-600 mb-4'></div>

            {/* Loading Message */}
            <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>

            {/* Progress Steps */}
            <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>
    )
  }

  return (
    <div className='min-h-screen'>
      <LoadingOverlay isVisible={isGeneratingPDF} message='Membuat PDF Laporan...' />
      {/* Control Panel */}
      <ReportGeneratorComponent
        // Props wajib
        className='min-w-full'
        reportTitle='Laporan Penjualan'
        filterType={filterType}
        selectedDate={selectedDate}
        dateRange={dateRange}
        onFilterTypeChange={setFilterType}
        onSingleDateChange={setSelectedDate}
        onDateRangeChange={setDateRange}
        onGeneratePDF={handleGeneratePDF}
        // Props opsional
        // isGenerating={isGenerating}
        // customQuickActions={customQuickActions}
        // labels={customLabels}
      />

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

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

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

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

          <div className='space-y-4'>
            <div className='flex justify-between items-center py-2 border-b border-gray-200'>
              <span className='text-gray-700'>Total Invoice</span>
              <span className='font-semibold text-gray-800'>{profitLoss?.summary.total_orders ?? 0}</span>
            </div>
            <div className='flex justify-between items-center py-2 border-b border-gray-200'>
              <span className='text-gray-700'>Rata-rata Tagihan Per Invoice </span>
              <span className='font-semibold text-gray-800'>
                {formatCurrency(profitLoss?.summary.average_profit ?? 0)}
              </span>
            </div>
          </div>
        </div>

        {/* Payment Method Summary */}
        <div className='px-8 pb-8'>
          <h3 className='text-xl font-bold mb-6' 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 p-3 font-semibold'>Metode Pembayaran</th>
                  <th className='text-center p-3 font-semibold'>Tipe</th>
                  <th className='text-center p-3 font-semibold'>Jumlah Order</th>
                  <th className='text-right p-3 font-semibold'>Total Amount</th>
                  <th className='text-center p-3 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-3 font-medium text-gray-800'>{payment.payment_method_name}</td>
                    <td className='p-3 text-center'>
                      <span
                        className={`px-2 py-1 rounded-full text-xs 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-3 text-center text-gray-700'>{payment.order_count}</td>
                    <td className='p-3 text-right font-semibold text-gray-800'>
                      {formatCurrency(payment.total_amount)}
                    </td>
                    <td className='p-3 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-3 font-bold'>TOTAL</td>
                  <td className='p-3'></td>
                  <td className='p-3 text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
                  <td className='p-3 text-right font-bold'>
                    {formatCurrency(paymentAnalytics?.summary.total_amount ?? 0)}
                  </td>
                  <td className='p-3 text-center font-bold'></td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        {/* Category Summary */}
        <div className='px-8 pb-8'>
          <h3 className='text-xl font-bold mb-6' 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 p-3 font-semibold'>Nama</th>
                  <th className='text-center p-3 font-semibold'>Total Produk</th>
                  <th className='text-center p-3 font-semibold'>Qty</th>
                  <th className='text-right p-3 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-3 font-medium text-gray-800'>{c.category_name}</td>
                    <td className='p-3 text-center text-gray-700'>{c.product_count}</td>
                    <td className='p-3 text-center text-gray-700'>{c.total_quantity}</td>
                    <td className='p-3 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-3 font-bold'>TOTAL</td>
                  <td className='p-3 text-center font-bold'>{categorySummary?.productCount ?? 0}</td>
                  <td className='p-3 text-center font-bold'>{categorySummary?.totalQuantity ?? 0}</td>
                  <td className='p-3 text-right font-bold'>{formatCurrency(categorySummary?.totalRevenue ?? 0)}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

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

          <div className='bg-gray-50 rounded-lg border border-gray-200 overflow-visible'>
            <div className='overflow-x-auto'>
              <table className='w-full table-fixed' style={{ minWidth: '100%' }}>
                <colgroup>
                  <col style={{ width: '40%' }} />
                  <col style={{ width: '15%' }} />
                  <col style={{ width: '15%' }} />
                  <col style={{ width: '15%' }} />
                  <col style={{ width: '15%' }} />
                </colgroup>
                <thead>
                  <tr className='text-gray-800 border-b-2 border-gray-300'>
                    <th className='text-left p-3 font-semibold border-r border-gray-300'>Produk</th>
                    <th className='text-center p-3 font-semibold border-r border-gray-300'>Qty</th>
                    <th className='text-center p-3 font-semibold border-r border-gray-300'>Order</th>
                    <th className='text-right p-3 font-semibold border-r border-gray-300'>Pendapatan</th>
                    <th className='text-right p-3 font-semibold'>Rata Rata</th>
                  </tr>
                </thead>
                <tbody>
                  {(() => {
                    // 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[]>
                      ) || {}

                    const rows: JSX.Element[] = []
                    let globalIndex = 0

                    // Sort categories alphabetically
                    Object.keys(groupedProducts)
                      .sort()
                      .forEach(categoryName => {
                        const categoryProducts = groupedProducts[categoryName]

                        // Category header row
                        rows.push(
                          <tr
                            key={`category-${categoryName}`}
                            className='bg-gray-100 border-b border-gray-300'
                            style={{ pageBreakInside: 'avoid' }}
                          >
                            <td
                              className='p-3 font-bold text-gray-900 border-r border-gray-300'
                              style={{ color: '#36175e' }}
                            >
                              {categoryName.toUpperCase()}
                            </td>
                            <td className='p-3 border-r border-gray-300'></td>
                            <td className='p-3 border-r border-gray-300'></td>
                            <td className='p-3 border-r border-gray-300'></td>
                            <td className='p-3'></td>
                          </tr>
                        )

                        // Product rows for this category
                        categoryProducts.forEach((item, index) => {
                          globalIndex++
                          rows.push(
                            <tr
                              key={`product-${item.product_name}-${index}`}
                              className={`${globalIndex % 2 === 0 ? 'bg-white' : 'bg-gray-50'} border-b border-gray-200`}
                              style={{ pageBreakInside: 'avoid' }}
                            >
                              <td
                                className='p-3 pl-6 font-medium text-gray-800 border-r border-gray-200'
                                style={{ wordWrap: 'break-word' }}
                              >
                                {item.product_name}
                              </td>
                              <td className='p-3 text-center text-gray-700 border-r border-gray-200'>
                                {item.quantity_sold}
                              </td>
                              <td className='p-3 text-center text-gray-700 border-r border-gray-200'>
                                {item.order_count ?? 0}
                              </td>
                              <td className='p-3 text-right font-semibold text-gray-800 border-r border-gray-200'>
                                {formatCurrency(item.revenue)}
                              </td>
                              <td className='p-3 text-right font-medium text-gray-800'>
                                {formatCurrency(item.average_price)}
                              </td>
                            </tr>
                          )
                        })

                        // Category subtotal row
                        const categoryTotalQty = categoryProducts.reduce(
                          (sum, item) => sum + (item.quantity_sold || 0),
                          0
                        )
                        const categoryTotalOrders = categoryProducts.reduce(
                          (sum, item) => sum + (item.order_count || 0),
                          0
                        )
                        const categoryTotalRevenue = categoryProducts.reduce(
                          (sum, item) => sum + (item.revenue || 0),
                          0
                        )

                        rows.push(
                          <tr
                            key={`subtotal-${categoryName}`}
                            className='bg-gray-200 border-b-2 border-gray-400'
                            style={{ pageBreakInside: 'avoid' }}
                          >
                            <td className='p-3 pl-6 font-semibold text-gray-800 border-r border-gray-400'>
                              Subtotal {categoryName}
                            </td>
                            <td className='p-3 text-center font-semibold text-gray-800 border-r border-gray-400'>
                              {categoryTotalQty}
                            </td>
                            <td className='p-3 text-center font-semibold text-gray-800 border-r border-gray-400'>
                              {categoryTotalOrders}
                            </td>
                            <td className='p-3 text-right font-semibold text-gray-800 border-r border-gray-400'>
                              {formatCurrency(categoryTotalRevenue)}
                            </td>
                            <td className='p-3'></td>
                          </tr>
                        )
                      })

                    return rows
                  })()}
                </tbody>
                <tfoot>
                  <tr className='text-gray-800 border-t-2 border-gray-300' style={{ pageBreakInside: 'avoid' }}>
                    <td className='p-3 font-bold border-r border-gray-300'>TOTAL KESELURUHAN</td>
                    <td className='p-3 text-center font-bold border-r border-gray-300'>
                      {productSummary.totalQuantitySold ?? 0}
                    </td>
                    <td className='p-3 text-center font-bold border-r border-gray-300'>
                      {productSummary.totalOrders ?? 0}
                    </td>
                    <td className='p-3 text-right font-bold border-r border-gray-300'>
                      {formatCurrency(productSummary.totalRevenue ?? 0)}
                    </td>
                    <td className='p-3'></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-sm 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
