'use client'

import DateRangePicker from '@/components/RangeDatePicker'
import { ReportItemHeader, ReportItemSubheader } from '@/components/report/ReportItem'
import { ExcelExportSalesProductCategoryService } from '@/services/export/excel/ExcelExportSalesProductCategoryService'
import { PDFExportSalesProductCategoryService } from '@/services/export/pdf/PDFExportSalesProductCategoryService'
import { useCategoryAnalytics } from '@/services/queries/analytics'
import { formatCurrency, formatDateDDMMYYYY } from '@/utils/transform'
import { Button, Card, CardContent, Menu, MenuItem } from '@mui/material'
import { useState } from 'react'

const ReportSalesProductCategoryContent = () => {
  const [startDate, setStartDate] = useState<Date | null>(new Date())
  const [endDate, setEndDate] = useState<Date | null>(new Date())
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)

  const { data: category } = useCategoryAnalytics({
    date_from: formatDateDDMMYYYY(startDate!),
    date_to: formatDateDDMMYYYY(endDate!)
  })

  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
  }

  const handleExportClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget)
  }

  const handleExportClose = () => {
    setAnchorEl(null)
  }

  const handleExportExcel = async () => {
    if (!category) {
      console.warn('No data available for export')
      return
    }

    try {
      const result = await ExcelExportSalesProductCategoryService.exportCategorySalesToExcel(
        category,
        `Penjualan_Kategori_${formatDateDDMMYYYY(startDate!)}_${formatDateDDMMYYYY(endDate!)}.xlsx`
      )

      if (result.success) {
        console.log(`Excel exported successfully: ${result.filename}`)
      } else {
        console.error('Export failed:', result.error)
      }
    } catch (error) {
      console.error('Export error:', error)
    }
  }

  const handleExportPDF = async () => {
    if (!category) {
      console.warn('No data available for export')
      return
    }

    try {
      const result = await PDFExportSalesProductCategoryService.exportCategorySalesToPDF(
        category,
        `Laporan_Penjualan_Kategori_${formatDateDDMMYYYY(startDate!)}_${formatDateDDMMYYYY(endDate!)}.pdf`
      )

      if (result.success) {
        console.log(`PDF exported successfully: ${result.filename}`)
      } else {
        console.error('Export failed:', result.error)
      }
    } catch (error) {
      console.error('Export error:', error)
    }
  }

  return (
    <Card>
      <div className='p-6 border-be'>
        <div className='flex items-center justify-end gap-2'>
          <Button
            color='secondary'
            variant='tonal'
            startIcon={<i className='tabler-upload' />}
            endIcon={<i className='tabler-chevron-down' />}
            className='max-sm:is-full'
            onClick={handleExportClick}
          >
            Ekspor
          </Button>
          <Menu anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleExportClose}>
            <MenuItem
              onClick={() => {
                handleExportExcel()
                handleExportClose()
              }}
            >
              Export Excel
            </MenuItem>
            <MenuItem
              onClick={() => {
                handleExportPDF()
                handleExportClose()
              }}
            >
              Export PDF
            </MenuItem>
          </Menu>
          <DateRangePicker
            startDate={startDate}
            endDate={endDate}
            onStartDateChange={setStartDate}
            onEndDateChange={setEndDate}
          />
        </div>
      </div>
      <CardContent>
        <ReportItemHeader
          title='Ringkasan Kategori'
          date={`${category?.date_from.split('T')[0]} - ${category?.date_to.split('T')[0]}`}
        />
        <div className='bg-gray-50 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>
        <ReportItemSubheader title='' />
      </CardContent>
    </Card>
  )
}

export default ReportSalesProductCategoryContent
