'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { CreditCard, Download, ArrowLeft, QrCode, Landmark, Loader2, AlertTriangle } from 'lucide-react'
import { formatCurrency } from '@/lib/utils'
import Pagination, { PaginationData } from '@/components/Pagination'
import toast from 'react-hot-toast'

const METHOD_BADGE: Record<string, { label: string; color: string }> = {
  qris: { label: 'QRIS', color: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' },
  card: { label: 'CARD', color: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300' },
  transfer: { label: 'TRANSFER', color: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300' },
}

function getMethodBadge(method: string) {
  if (method.startsWith('va_')) return METHOD_BADGE.transfer
  return METHOD_BADGE[method] || { label: method.toUpperCase(), color: 'bg-gray-100 text-gray-700 dark:bg-gray-700/50 dark:text-gray-200' }
}

function getMethodLabel(method: string) {
  if (method.startsWith('va_')) {
    const bank = method.replace('va_', '').toUpperCase()
    return `VA ${bank}`
  }
  return METHOD_BADGE[method]?.label || method.toUpperCase()
}

export default function PaymentReportPage() {
  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 [paymentMethod, setPaymentMethod] = useState('')
  const [page, setPage] = useState(1)

  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) })
    if (storeId) params.set('storeId', storeId)
    if (paymentMethod) params.set('paymentMethod', paymentMethod)
    const res = await fetch(`/api/reports/payments?${params}`)
    const d = await res.json()
    setData(d)
    setLoading(false)
  }

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

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

      const XLSX = await import('xlsx')

      const wsData = [
        ['Laporan Pembayaran Non-Cash'],
        [`Periode: ${startDate} s/d ${endDate}`],
        [],
        ['No', 'Tanggal', 'No. Order', 'Cabang', 'Total (Rp)', 'Metode Bayar', 'Kode Approval', 'Customer'],
        ...allData.orders.map((order: any, idx: number) => [
          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.total,
          getMethodLabel(order.paymentMethod),
          order.approvalCode || '-',
          order.customerName || '-',
        ]),
        [],
        ['', '', '', 'TOTAL', allData.summary.totalAmount, '', '', ''],
      ]

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

      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Laporan Pembayaran')
      XLSX.writeFile(wb, `laporan-pembayaran-${startDate}-${endDate}.xlsx`)
      toast.success('File Excel berhasil diunduh')
    } catch {
      toast.error('Gagal mengekspor data')
    } finally {
      setExporting(false)
    }
  }

  const bd = data?.summary?.breakdown || {}

  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">Laporan Pembayaran Non-Cash</h1>
          <p className="text-gray-600 dark:text-gray-300 mt-1">Rekonsiliasi pembayaran QRIS, Card, dan Transfer untuk tim finance.</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>

      {/* 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">Metode Bayar</label>
            <select className="input-field text-sm w-auto" value={paymentMethod} onChange={(e) => { setPaymentMethod(e.target.value); setPage(1) }}>
              <option value="">Semua Non-Cash</option>
              <option value="qris">QRIS</option>
              <option value="card">Card</option>
              <option value="transfer">Transfer / VA</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 lg:grid-cols-4 gap-4 mb-6">
            <div className="card">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-primary-100 dark:bg-primary-900/30 rounded-lg flex items-center justify-center"><CreditCard className="w-5 h-5 text-primary-600" /></div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-300">Total Non-Cash</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-white">{formatCurrency(data.summary.totalAmount)}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">{data.summary.totalTransactions} transaksi</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"><QrCode className="w-5 h-5 text-green-600" /></div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-300">QRIS</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-white">{formatCurrency(bd.qris?.amount || 0)}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">{bd.qris?.count || 0} transaksi</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"><CreditCard className="w-5 h-5 text-blue-600" /></div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-300">Card</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-white">{formatCurrency(bd.card?.amount || 0)}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">{bd.card?.count || 0} transaksi</p>
                </div>
              </div>
            </div>
            <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"><Landmark className="w-5 h-5 text-purple-600" /></div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-300">Transfer / VA</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-white">{formatCurrency(bd.transfer?.amount || 0)}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">{bd.transfer?.count || 0} transaksi</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">Total</th>
                        <th className="text-center py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Metode Bayar</th>
                        <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Kode Approval</th>
                        <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Customer</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.orders.map((order: any, idx: number) => {
                        const badge = getMethodBadge(order.paymentMethod)
                        const noApproval = !order.approvalCode
                        return (
                          <tr key={order.id} className={`border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 ${noApproval ? 'bg-yellow-50/50 dark:bg-yellow-900/10' : ''}`}>
                            <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 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 ${badge.color}`}>
                                {getMethodLabel(order.paymentMethod)}
                              </span>
                            </td>
                            <td className="py-3 px-3">
                              {order.approvalCode ? (
                                <span className="font-mono text-xs text-gray-700 dark:text-gray-200">{order.approvalCode}</span>
                              ) : (
                                <span className="inline-flex items-center gap-1 text-xs text-yellow-600 dark:text-yellow-400">
                                  <AlertTriangle className="w-3 h-3" /> Belum diisi
                                </span>
                              )}
                            </td>
                            <td className="py-3 px-3 text-gray-600 dark:text-gray-300">{order.customerName}</td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
                <Pagination pagination={data.pagination as PaginationData} onPageChange={setPage} itemLabel="transaksi" />
              </>
            ) : (
              <div className="text-center py-12">
                <CreditCard 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">Tidak ada transaksi non-cash untuk periode ini</p>
              </div>
            )}
          </div>
        </>
      ) : null}
    </div>
  )
}
