'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { Receipt, ShoppingCart, TrendingUp, Download, ArrowLeft, HandCoins, Loader2 } from 'lucide-react'
import { formatCurrency } from '@/lib/utils'
import Pagination, { PaginationData } from '@/components/Pagination'
import toast from 'react-hot-toast'

type ReportType = 'all' | 'tax' | 'service'

const TABS: { value: ReportType; label: string }[] = [
  { value: 'all', label: 'Semua' },
  { value: 'tax', label: 'Pajak' },
  { value: 'service', label: 'B. Layanan' },
]

const TITLES: Record<ReportType, { title: string; desc: string }> = {
  all: { title: 'Laporan Pajak & Biaya Layanan', desc: 'Detail pajak dan biaya layanan per transaksi.' },
  tax: { title: 'Laporan Pajak', desc: 'Detail pajak per transaksi.' },
  service: { title: 'Laporan Biaya Layanan', desc: 'Detail biaya layanan per transaksi.' },
}

export default function TaxReportPage() {
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [exporting, setExporting] = useState(false)
  const [stores, setStores] = useState<any[]>([])
  const [storeId, setStoreId] = useState('')
  const [startDate, setStartDate] = useState('')
  const [endDate, setEndDate] = useState('')
  const [page, setPage] = useState(1)
  const [type, setType] = useState<ReportType>('all')

  useEffect(() => {
    const now = new Date()
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
    setStartDate(firstDay.toISOString().slice(0, 10))
    setEndDate(now.toISOString().slice(0, 10))
  }, [])

  useEffect(() => {
    fetch('/api/stores').then(r => r.json()).then(d => setStores(d.stores || []))
  }, [])

  const fetchData = async () => {
    if (!startDate || !endDate) return
    setLoading(true)
    const params = new URLSearchParams({ startDate, endDate, page: String(page), type })
    if (storeId) params.set('storeId', storeId)
    const res = await fetch(`/api/reports/tax?${params}`)
    const d = await res.json()
    setData(d)
    setLoading(false)
  }

  useEffect(() => { fetchData() }, [startDate, endDate, storeId, page, type])

  const handleExport = async () => {
    if (!startDate || !endDate) return
    setExporting(true)
    try {
      const params = new URLSearchParams({ startDate, endDate, page: '1', limit: '10000', type })
      if (storeId) params.set('storeId', storeId)
      const res = await fetch(`/api/reports/tax?${params}`)
      const allData = await res.json()

      const XLSX = await import('xlsx')

      const sheetTitle = TITLES[type].title
      const headers = ['No', 'Tanggal', 'No. Order', 'Cabang', 'Subtotal (Rp)']
      if (type !== 'service') headers.push('Pajak (Rp)')
      if (type !== 'tax') headers.push('B. Layanan (Rp)')
      headers.push('Total (Rp)', 'Metode Pembayaran')

      const wsData: any[][] = [
        [sheetTitle],
        [`Periode: ${startDate} s/d ${endDate}`],
        [],
        headers,
        ...allData.orders.map((order: any, idx: number) => {
          const row: any[] = [
            idx + 1,
            new Date(order.createdAt).toLocaleString('id-ID', {
              day: '2-digit', month: 'short', year: 'numeric',
              hour: '2-digit', minute: '2-digit',
            }),
            order.orderNumber,
            order.storeName,
            order.subtotal,
          ]
          if (type !== 'service') row.push(order.tax)
          if (type !== 'tax') row.push(order.serviceCharge)
          row.push(order.total, (order.paymentMethod || '-').toUpperCase())
          return row
        }),
        [],
      ]

      // Total row
      const totalRow: any[] = ['', '', '', 'TOTAL', allData.summary.totalSubtotal]
      if (type !== 'service') totalRow.push(allData.summary.totalTax)
      if (type !== 'tax') totalRow.push(allData.summary.totalServiceCharge)
      totalRow.push(allData.summary.totalTotal, '')
      wsData.push(totalRow)

      const ws = XLSX.utils.aoa_to_sheet(wsData)
      ws['!cols'] = [
        { wch: 5 }, { wch: 22 }, { wch: 20 }, { wch: 20 },
        { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 18 },
      ]

      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, sheetTitle.slice(0, 31))
      const suffix = type === 'all' ? 'pajak' : type === 'tax' ? 'pajak' : 'layanan'
      XLSX.writeFile(wb, `laporan-${suffix}-${startDate}-${endDate}.xlsx`)
      toast.success('File Excel berhasil diunduh')
    } catch {
      toast.error('Gagal mengekspor data')
    } finally {
      setExporting(false)
    }
  }

  const info = TITLES[type]

  return (
    <div>
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
          <Link href="/dashboard/reports" className="inline-flex items-center gap-1 text-sm text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 mb-2">
            <ArrowLeft className="w-4 h-4" /> Kembali ke Laporan
          </Link>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">{info.title}</h1>
          <p className="text-gray-600 dark:text-gray-300 mt-1">{info.desc}</p>
        </div>
        <button
          onClick={handleExport}
          disabled={exporting || !data?.orders?.length}
          className="btn-primary flex items-center gap-2 self-start"
        >
          {exporting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
          Export Excel
        </button>
      </div>

      {/* Type Tabs */}
      <div className="flex gap-1 bg-gray-100 dark:bg-gray-800 rounded-lg p-1 mb-6 w-fit">
        {TABS.map(tab => (
          <button
            key={tab.value}
            onClick={() => { setType(tab.value); setPage(1) }}
            className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
              type === tab.value
                ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
                : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Filters */}
      <div className="card mb-6">
        <div className="flex flex-wrap gap-3 items-end">
          <div>
            <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Cabang</label>
            <select className="input-field text-sm w-auto" value={storeId} onChange={(e) => { setStoreId(e.target.value); setPage(1) }}>
              <option value="">Semua Cabang</option>
              {stores.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Dari Tanggal</label>
            <input type="date" className="input-field text-sm" value={startDate} onChange={(e) => { setStartDate(e.target.value); setPage(1) }} />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Sampai Tanggal</label>
            <input type="date" className="input-field text-sm" value={endDate} onChange={(e) => { setEndDate(e.target.value); setPage(1) }} />
          </div>
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
        </div>
      ) : data ? (
        <>
          {/* Summary Cards */}
          <div className={`grid grid-cols-2 ${type === 'all' ? 'lg:grid-cols-4' : 'lg:grid-cols-3'} gap-4 mb-6`}>
            {type !== 'service' && (
              <div className="card">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center"><Receipt className="w-5 h-5 text-yellow-600" /></div>
                  <div>
                    <p className="text-sm text-gray-600 dark:text-gray-300">Total Pajak</p>
                    <p className="text-xl font-bold text-gray-900 dark:text-white">{formatCurrency(data.summary.totalTax)}</p>
                  </div>
                </div>
              </div>
            )}
            {type !== 'tax' && (
              <div className="card">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center"><HandCoins className="w-5 h-5 text-purple-600" /></div>
                  <div>
                    <p className="text-sm text-gray-600 dark:text-gray-300">Total B. Layanan</p>
                    <p className="text-xl font-bold text-gray-900 dark:text-white">{formatCurrency(data.summary.totalServiceCharge)}</p>
                  </div>
                </div>
              </div>
            )}
            <div className="card">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center"><ShoppingCart className="w-5 h-5 text-blue-600" /></div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-300">Total Transaksi</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-white">{data.summary.totalTransactions}</p>
                </div>
              </div>
            </div>
            <div className="card">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center"><TrendingUp className="w-5 h-5 text-green-600" /></div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-300">
                    {type === 'service' ? 'Rata-rata B. Layanan' : 'Rata-rata Pajak'}
                  </p>
                  <p className="text-xl font-bold text-gray-900 dark:text-white">
                    {formatCurrency(type === 'service' ? data.summary.avgServiceCharge : data.summary.avgTax)}
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Transaction Table */}
          <div className="card">
            {data.orders.length > 0 ? (
              <>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700">
                        <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">No</th>
                        <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Tanggal</th>
                        <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">No. Order</th>
                        <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Cabang</th>
                        <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Subtotal</th>
                        {type !== 'service' && (
                          <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Pajak</th>
                        )}
                        {type !== 'tax' && (
                          <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">B. Layanan</th>
                        )}
                        <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Total</th>
                        <th className="text-center py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Pembayaran</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.orders.map((order: any, idx: number) => (
                        <tr key={order.id} className="border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800">
                          <td className="py-3 px-3 text-gray-500 dark:text-gray-400">{(page - 1) * 20 + idx + 1}</td>
                          <td className="py-3 px-3 text-gray-600 dark:text-gray-300 whitespace-nowrap">
                            {new Date(order.createdAt).toLocaleString('id-ID', {
                              day: '2-digit', month: 'short', year: 'numeric',
                              hour: '2-digit', minute: '2-digit',
                            })}
                          </td>
                          <td className="py-3 px-3 font-mono text-xs text-gray-700 dark:text-gray-200">{order.orderNumber}</td>
                          <td className="py-3 px-3 text-gray-600 dark:text-gray-300">{order.storeName}</td>
                          <td className="py-3 px-3 text-right text-gray-600 dark:text-gray-300">{formatCurrency(order.subtotal)}</td>
                          {type !== 'service' && (
                            <td className="py-3 px-3 text-right text-yellow-600 font-medium">{formatCurrency(order.tax)}</td>
                          )}
                          {type !== 'tax' && (
                            <td className="py-3 px-3 text-right text-purple-600 font-medium">{formatCurrency(order.serviceCharge)}</td>
                          )}
                          <td className="py-3 px-3 text-right font-bold text-gray-900 dark:text-white">{formatCurrency(order.total)}</td>
                          <td className="py-3 px-3 text-center">
                            <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-gray-100 dark:bg-gray-700/50 text-gray-700 dark:text-gray-200">
                              {order.paymentMethod.toUpperCase()}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <Pagination pagination={data.pagination as PaginationData} onPageChange={setPage} itemLabel="transaksi" />
              </>
            ) : (
              <div className="text-center py-12">
                <Receipt className="w-12 h-12 text-gray-300 dark:text-gray-500 mx-auto mb-3" />
                <p className="text-gray-500 dark:text-gray-400">
                  {type === 'tax' ? 'Tidak ada data pajak untuk periode ini' :
                   type === 'service' ? 'Tidak ada data biaya layanan untuk periode ini' :
                   'Tidak ada data untuk periode ini'}
                </p>
              </div>
            )}
          </div>
        </>
      ) : null}
    </div>
  )
}
