'use client'

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

const ReportPaymentMethodContent = () => {
  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: paymentAnalytics } = usePaymentAnalytics({
    date_from: formatDateDDMMYYYY(startDate!),
    date_to: formatDateDDMMYYYY(endDate!)
  })

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

    try {
      const result = await ExcelExportPaymentService.exportPaymentMethodToExcel(paymentAnalytics)

      if (result.success) {
        console.log(`File exported successfully: ${result.filename}`)
        // Optional: Show success message to user
      } else {
        console.error('Export failed:', result.error)
        // Optional: Show error message to user
      }
    } catch (error) {
      console.error('Export error:', error)
    }
  }

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

    try {
      const result = await PDFExportPaymentService.exportPaymentMethodToPDF(
        paymentAnalytics,
        `Laporan_Metode_Pembayaran_${formatDateDDMMYYYY(startDate!)}_${formatDateDDMMYYYY(endDate!)}.pdf`
      )

      if (result.success) {
        console.log(`PDF exported successfully: ${result.filename}`)
        // Optional: Show success message to user
      } else {
        console.error('PDF export failed:', result.error)
        // Optional: Show error message to user
      }
    } catch (error) {
      console.error('PDF export error:', error)
    }
  }

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

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

  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 Metode Pembayaran'
          date={`${paymentAnalytics?.date_from.split('T')[0]} - ${paymentAnalytics?.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'>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>
        <ReportItemSubheader title='' />
      </CardContent>
    </Card>
  )
}

export default ReportPaymentMethodContent
