'use client'

import { useInventoryAnalytics } from '@/services/queries/analytics'
import { useOutletById } from '@/services/queries/outlets'
import { formatDateDDMMYYYY } from '@/utils/transform'
import ReportGeneratorComponent from '@/views/dashboards/daily-report/report-generator'
import ReportHeader from '@/views/dashboards/daily-report/report-header'
import { useRef, useState } from 'react'
const ExportInventoryPage = () => {
  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 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: inventory } = useInventoryAnalytics(dateParams)

  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: `Laporan Inventori`,
        subject: 'Laporan Inventori',
        author: 'Apskel POS System',
        creator: 'Apskel'
      })

      // Save with optimized settings
      const fileName =
        filterType === 'single'
          ? `laporan-inventory-${formatDateForInput(selectedDate)}.pdf`
          : `laporan-inventory-${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.')
    }
  }

  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 productSummary = {
    totalQuantity: inventory?.products?.reduce((sum, item) => sum + (item?.quantity || 0), 0) || 0,
    totalIn: inventory?.products?.reduce((sum, item) => sum + (item?.total_in || 0), 0) || 0,
    totalOut: inventory?.products?.reduce((sum, item) => sum + (item?.total_out || 0), 0) || 0
  }

  const ingredientSummary = {
    totalQuantity: inventory?.ingredients?.reduce((sum, item) => sum + (item?.quantity || 0), 0) || 0,
    totalIn: inventory?.ingredients?.reduce((sum, item) => sum + (item?.total_in || 0), 0) || 0,
    totalOut: inventory?.ingredients?.reduce((sum, item) => sum + (item?.total_out || 0), 0) || 0
  }

  return (
    <div className='min-h-screen'>
      {/* Control Panel */}
      <ReportGeneratorComponent
        // Props wajib
        reportTitle='Laporan Inventori'
        filterType={filterType}
        selectedDate={selectedDate}
        dateRange={dateRange}
        onFilterTypeChange={setFilterType}
        onSingleDateChange={setSelectedDate}
        onDateRangeChange={setDateRange}
        onGeneratePDF={handleGeneratePDF}
        // Props opsional
        // isGenerating={isGenerating}
        // customQuickActions={customQuickActions}
        // labels={customLabels}
      />
      <div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
        {/* Header */}
        <ReportHeader
          outlet={outlet}
          reportTitle='Laporan Inventori'
          reportSubtitle='Laporan'
          brandName='Apskel'
          brandColor='#36175e'
          periode={getReportPeriodText()}
        />

        {/* Ringkasan */}
        <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 Item</span>
                <span className='font-semibold text-gray-800'>{inventory?.summary.total_products}</span>
              </div>
              <div className='flex justify-between items-center py-2 border-b border-gray-200'>
                <span className='text-gray-700'>Total Item Masuk</span>
                <span className='font-semibold text-gray-800'>{inventory?.summary.low_stock_products}</span>
              </div>
              <div className='flex justify-between items-center py-2 border-b border-gray-200'>
                <span className='text-gray-700'>Total Item Keluar</span>
                <span className='font-semibold text-gray-800'>{inventory?.summary.zero_stock_products}</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'>Total Ingredient</span>
                <span className='font-semibold text-gray-800'>{inventory?.summary.total_ingredients}</span>
              </div>
              <div className='flex justify-between items-center py-2 border-b border-gray-200'>
                <span className='text-gray-700'>Total Ingredient Masuk</span>
                <span className='font-semibold text-gray-800'>{inventory?.summary.low_stock_ingredients}</span>
              </div>
              <div className='flex justify-between items-center py-2 border-b border-gray-200'>
                <span className='text-gray-700'>Total Ingredient Keluar</span>
                <span className='font-semibold text-gray-800'>{inventory?.summary.zero_stock_ingredients}</span>
              </div>
            </div>
          </div>
        </div>

        {/* Item */}
        <div className='px-8 pb-8'>
          <h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
            2. 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'>Nama</th>
                  <th className='text-center p-3 font-semibold'>Kategori</th>
                  <th className='text-center p-3 font-semibold'>Stock</th>
                  <th className='text-center p-3 font-semibold'>Masuk</th>
                  <th className='text-center p-3 font-semibold'>Keluar</th>
                </tr>
              </thead>
              <tbody>
                {inventory?.products?.map((product, index) => {
                  let rowClass = index % 2 === 0 ? 'bg-white' : 'bg-gray-50'

                  if (product.is_zero_stock) {
                    rowClass = 'bg-red-300' // Merah untuk stok habis
                  } else if (product.is_low_stock) {
                    rowClass = 'bg-yellow-300' // Kuning untuk stok sedikit
                  }
                  return (
                    <tr key={index} className={rowClass}>
                      <td className='p-3 font-medium text-gray-800'>{product.product_name}</td>
                      <td className='p-3 font-medium text-gray-800'>{product.category_name}</td>

                      <td className='p-3 text-center text-gray-700'>{product.quantity}</td>
                      <td className='p-3 text-center text-gray-700'>{product.total_in}</td>
                      <td className='p-3 text-center text-gray-700'>{product.total_out}</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'>{productSummary.totalQuantity ?? 0}</td>
                  <td className='p-3 text-center font-bold'>{productSummary.totalIn ?? 0}</td>
                  <td className='p-3 text-center font-bold'>{productSummary.totalOut ?? 0}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        {/* Ingredient */}
        <div className='px-8 pb-8'>
          <h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
            3. Ingredient
          </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'>Stock</th>
                  <th className='text-center p-3 font-semibold'>Masuk</th>
                  <th className='text-center p-3 font-semibold'>Keluar</th>
                </tr>
              </thead>
              <tbody>
                {inventory?.ingredients?.map((ingredient, index) => {
                  let rowClass = index % 2 === 0 ? 'bg-white' : 'bg-gray-50'

                  if (ingredient.is_zero_stock) {
                    rowClass = 'bg-red-300' // Merah untuk stok habis
                  } else if (ingredient.is_low_stock) {
                    rowClass = 'bg-yellow-300' // Kuning untuk stok sedikit
                  }
                  return (
                    <tr key={index} className={rowClass}>
                      <td className='p-3 font-medium text-gray-800'>{ingredient.ingredient_name}</td>
                      <td className='p-3 text-center text-gray-700'>{ingredient.quantity}</td>
                      <td className='p-3 text-center text-gray-700'>{ingredient.total_in}</td>
                      <td className='p-3 text-center text-gray-700'>{ingredient.total_out}</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'>{ingredientSummary.totalQuantity ?? 0}</td>
                  <td className='p-3 text-center font-bold'>{ingredientSummary.totalIn ?? 0}</td>
                  <td className='p-3 text-center font-bold'>{ingredientSummary.totalOut ?? 0}</td>
                </tr>
              </tfoot>
            </table>
          </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 ExportInventoryPage
