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

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

  // Calculate profit loss product summary
  const profitLossProductSummary = {
    totalRevenue: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
    totalCost: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.cost || 0), 0) || 0,
    totalGrossProfit: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.gross_profit || 0), 0) || 0,
    totalQuantity: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.quantity_sold || 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

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

      // Optimized canvas capture dengan scale lebih rendah
      const canvas = await html2canvas(reportElement!, {
        scale: 1.5, // Reduced from 2 to 1.5
        useCORS: true,
        allowTaint: true,
        backgroundColor: '#ffffff',
        logging: false, // Disable logging for performance
        removeContainer: true, // Clean up after capture
        imageTimeout: 0, // No timeout for image loading
        height: reportElement!.scrollHeight,
        width: reportElement!.scrollWidth
      })

      // Compress canvas using JPEG with quality setting
      const imgData = canvas.toDataURL('image/jpeg', 0.85) // JPEG with 85% quality instead of PNG

      // Create PDF with compression
      const pdf = new jsPDF({
        orientation: 'portrait',
        unit: 'mm',
        format: 'a4',
        compress: true // Enable built-in compression
      })

      const imgWidth = 210
      const pageHeight = 295
      const imgHeight = (canvas.height * imgWidth) / canvas.width
      let heightLeft = imgHeight
      let position = 0

      // Add first page with compressed image
      pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST') // Use FAST compression
      heightLeft -= pageHeight

      // Handle multiple pages if needed
      while (heightLeft >= 0) {
        position = heightLeft - imgHeight
        pdf.addPage()
        pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST')
        heightLeft -= pageHeight
      }

      // Additional compression options
      pdf.setProperties({
        title: `${getReportTitle()}`,
        subject: 'Daily Transaction Report',
        author: 'Apskel POS System',
        creator: 'Apskel'
      })

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

      pdf.save(fileName, {
        returnPromise: true
      })

      // Clean up canvas to free memory
      canvas.width = canvas.height = 0
    } catch (error) {
      console.error('Error generating PDF:', error)
      alert('Terjadi kesalahan saat membuat PDF. Pastikan jsPDF dan html2canvas sudah terinstall.')
    }
  }

  return (
    <div className='min-h-screen'>
      {/* Control Panel */}
      <ReportGeneratorComponent
        // Props wajib
        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' }}>
            1. Ringkasan
          </h3>

          <div className='grid grid-cols-2 gap-6'>
            <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 (termasuk rasik)</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 Terjual</span>
                <span className='font-semibold text-gray-800'>{productSummary.totalQuantitySold}</span>
              </div>
              <div className='flex justify-between items-center py-2 border-b border-gray-200'>
                <span className='text-gray-700'>HPP</span>
                <span className='font-semibold text-gray-800'>
                  {formatCurrency(profitLoss?.summary.total_cost ?? 0)} |{' '}
                  {(((profitLoss?.summary.total_cost ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(
                    0
                  )}
                  %
                </span>
              </div>
              <div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
                <span className='text-lg font-semibold text-green-800'>Laba Kotor</span>
                <span className='text-lg font-bold text-green-800'>
                  {formatCurrency(profitLoss?.summary.gross_profit ?? 0)} |{' '}
                  {(profitLoss?.summary.gross_profit_margin ?? 0).toFixed(0)}%
                </span>
              </div>
            </div>

            <div className='space-y-4'>
              <div className='flex justify-between items-center py-2 border-b border-gray-200'>
                <span className='text-gray-700'>Biaya lain²</span>
                <span className='font-semibold text-gray-800'>
                  {formatCurrency(profitLoss?.summary.total_tax ?? 0)} |{' '}
                  {(((profitLoss?.summary.total_tax ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(0)}
                  %
                </span>
              </div>
              <div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
                <span className='text-lg font-bold text-blue-800'>Laba/Rugi</span>
                <span className='text-lg font-bold text-blue-800'>
                  {formatCurrency(profitLoss?.summary.net_profit ?? 0)} |{' '}
                  {(profitLoss?.summary.net_profit_margin ?? 0).toFixed(0)}%
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* Profit Loss Product Table */}
        <div className='px-8 pb-8'>
          <h3 className='text-lg font-medium mb-6' style={{ color: '#36175e' }}>
            Laba Rugi Per Produk
          </h3>

          <div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
            <table className='w-full'>
              <thead>
                <tr style={{ backgroundColor: '#36175e' }} className='text-white'>
                  <th className='text-left p-3 font-semibold'>Produk</th>
                  <th className='text-center p-3 font-semibold'>Qty</th>
                  <th className='text-right p-3 font-semibold'>Pendapatan</th>
                  <th className='text-right p-3 font-semibold'>HPP</th>
                  <th className='text-right p-3 font-semibold'>Laba Kotor</th>
                  <th className='text-center p-3 font-semibold'>Margin (%)</th>
                </tr>
              </thead>
              <tbody>
                {profitLoss?.product_data?.map((item, index) => (
                  <tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                    <td className='p-3 font-medium text-gray-800'>{item.product_name}</td>
                    <td className='p-3 text-center text-gray-700'>{item.quantity_sold}</td>
                    <td className='p-3 text-right font-semibold text-gray-800'>{formatCurrency(item.revenue)}</td>
                    <td className='p-3 text-right font-semibold text-red-600'>{formatCurrency(item.cost)}</td>
                    <td className='p-3 text-right font-semibold text-green-600'>{formatCurrency(item.gross_profit)}</td>
                    <td className='p-3 text-center font-semibold' style={{ color: '#36175e' }}>
                      {(item.gross_profit_margin ?? 0).toFixed(1)}%
                    </td>
                  </tr>
                )) || []}
              </tbody>
              <tfoot>
                <tr style={{ backgroundColor: '#36175e' }} className='text-white'>
                  <td className='p-3 font-bold'>TOTAL</td>
                  <td className='p-3 text-center font-bold'>{profitLossProductSummary.totalQuantity}</td>
                  <td className='p-3 text-right font-bold'>{formatCurrency(profitLossProductSummary.totalRevenue)}</td>
                  <td className='p-3 text-right font-bold'>{formatCurrency(profitLossProductSummary.totalCost)}</td>
                  <td className='p-3 text-right font-bold'>
                    {formatCurrency(profitLossProductSummary.totalGrossProfit)}
                  </td>
                  <td className='p-3 text-center font-bold'>
                    {profitLossProductSummary.totalRevenue > 0
                      ? (
                          (profitLossProductSummary.totalGrossProfit / profitLossProductSummary.totalRevenue) *
                          100
                        ).toFixed(1)
                      : 0}
                    %
                  </td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

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

          <div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
            <table className='w-full'>
              <thead>
                <tr style={{ backgroundColor: '#36175e' }} className='text-white'>
                  <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 style={{ backgroundColor: '#36175e' }} className='text-white'>
                  <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' }}>
            2. Ringkasan Kategori
          </h3>

          <div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
            <table className='w-full'>
              <thead>
                <tr style={{ backgroundColor: '#36175e' }} className='text-white'>
                  <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'>Jumlah Order</th>
                  <th className='text-center 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-center  text-gray-700'>{c.order_count}</td>
                    <td className='p-3 text-right font-semibold' style={{ color: '#36175e' }}>
                      {formatCurrency(c.total_revenue)}
                    </td>
                  </tr>
                )) || []}
              </tbody>
              <tfoot>
                <tr style={{ backgroundColor: '#36175e' }} className='text-white'>
                  <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-center font-bold'>{categorySummary?.orderCount ?? 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' }}>
            4. Ringkasan Item
          </h3>

          <div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
            <table className='w-full'>
              <thead>
                <tr style={{ backgroundColor: '#36175e' }} className='text-white'>
                  <th className='text-left p-3 font-semibold'>Produk</th>
                  <th className='text-left p-3 font-semibold'>Kategori</th>
                  <th className='text-center p-3 font-semibold'>Qty</th>
                  <th className='text-right p-3 font-semibold'>Order</th>
                  <th className='text-right p-3 font-semibold'>Pendapatan</th>
                  <th className='text-right p-3 font-semibold'>Rata Rata</th>
                </tr>
              </thead>
              <tbody>
                {products?.data?.map((item, index) => (
                  <tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                    <td className='p-3 font-medium text-gray-800'>{item.product_name}</td>
                    <td className='p-3 font-medium text-gray-800'>{item.category_name}</td>
                    <td className='p-3 text-center text-gray-700'>{item.quantity_sold}</td>
                    <td className='p-3 text-center text-gray-700'>{item.order_count ?? 0}</td>
                    <td className='p-3 text-right font-semibold text-gray-800'>{formatCurrency(item.revenue)}</td>
                    <td className='p-3 text-right font-medium text-gray-800'>{formatCurrency(item.average_price)}</td>
                  </tr>
                )) || []}
              </tbody>
              <tfoot>
                <tr style={{ backgroundColor: '#36175e' }} className='text-white'>
                  <td className='p-3 font-bold'>TOTAL</td>
                  <td className='p-3 text-center'></td>
                  <td className='p-3 text-center font-bold'>{productSummary.totalQuantitySold ?? 0}</td>
                  <td className='p-3 text-right font-bold'>{productSummary.totalOrders ?? 0}</td>
                  <td className='p-3 text-right font-bold'>{formatCurrency(productSummary.totalRevenue ?? 0)}</td>
                  <td className='p-3 text-right font-bold'></td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        {/* Profit Loss Product Table */}

        {/* 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
