'use client'

import { useEffect, useState } from 'react'
import { Wallet, Loader2, CheckCircle, XCircle, Clock, Filter, Building2, CreditCard, MessageSquare } from 'lucide-react'
import toast from 'react-hot-toast'
import { WITHDRAWAL_STATUSES } from '@/lib/constants'
import Pagination, { PaginationData } from '@/components/Pagination'

interface Withdrawal {
  id: string
  tenantName: string
  tenantSlug: string
  amount: number
  bankName: string
  bankAccount: string
  bankHolder: string
  status: string
  notes: string | null
  adminNotes: string | null
  processedAt: string | null
  processedBy: string | null
  createdAt: string
}

export default function WithdrawalsPage() {
  const [loading, setLoading] = useState(true)
  const [withdrawals, setWithdrawals] = useState<Withdrawal[]>([])
  const [filterStatus, setFilterStatus] = useState('all')
  const [processingId, setProcessingId] = useState<string | null>(null)
  const [showNotesModal, setShowNotesModal] = useState<{ id: string; action: 'approve' | 'reject' } | null>(null)
  const [adminNotes, setAdminNotes] = useState('')
  const [pagination, setPagination] = useState<PaginationData>({ page: 1, limit: 20, total: 0, totalPages: 0 })
  const [stats, setStats] = useState<Record<string, { count: number; total: number }>>({})

  const fetchWithdrawals = (page = 1) => {
    setLoading(true)
    fetch(`/api/superadmin/withdrawals?status=${filterStatus}&page=${page}`)
      .then(r => r.json())
      .then(d => {
        if (d.withdrawals) setWithdrawals(d.withdrawals)
        if (d.pagination) setPagination(d.pagination)
        if (d.stats) setStats(d.stats)
      })
      .catch(() => toast.error('Gagal memuat data penarikan'))
      .finally(() => setLoading(false))
  }

  useEffect(() => { fetchWithdrawals(1) }, [filterStatus])

  const handleAction = async (id: string, action: 'approve' | 'reject', notes?: string) => {
    setProcessingId(id)
    try {
      const res = await fetch(`/api/superadmin/withdrawals/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action, adminNotes: notes || '' }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      toast.success(action === 'approve' ? 'Penarikan disetujui' : 'Penarikan ditolak')
      setShowNotesModal(null)
      setAdminNotes('')
      fetchWithdrawals(pagination.page)
    } catch (err: any) {
      toast.error(err.message || 'Gagal memproses')
    } finally {
      setProcessingId(null)
    }
  }

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Penarikan Dana</h1>
        <p className="text-gray-600 mt-1">Kelola permintaan penarikan dana dari tenant.</p>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-4 gap-4 mb-6">
        <div className="card">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center">
              <Clock className="w-5 h-5 text-yellow-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-900">{stats.pending?.count || 0}</p>
              <p className="text-xs text-gray-500">Menunggu</p>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
              <CheckCircle className="w-5 h-5 text-green-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-900">{stats.approved?.count || 0}</p>
              <p className="text-xs text-gray-500">Disetujui</p>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center">
              <XCircle className="w-5 h-5 text-red-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-900">{stats.rejected?.count || 0}</p>
              <p className="text-xs text-gray-500">Ditolak</p>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
              <Wallet className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-900">
                Rp {(stats.approved?.total || 0).toLocaleString('id-ID')}
              </p>
              <p className="text-xs text-gray-500">Total Disetujui</p>
            </div>
          </div>
        </div>
      </div>

      {/* Filter */}
      <div className="card mb-6">
        <div className="flex items-center gap-3">
          <Filter className="w-4 h-4 text-gray-500" />
          <span className="text-sm font-medium text-gray-700">Filter Status:</span>
          <div className="flex gap-2 flex-wrap">
            {[
              { value: 'all', label: 'Semua' },
              { value: 'pending', label: 'Menunggu' },
              { value: 'approved', label: 'Disetujui' },
              { value: 'rejected', label: 'Ditolak' },
              { value: 'completed', label: 'Selesai' },
            ].map(f => (
              <button
                key={f.value}
                onClick={() => setFilterStatus(f.value)}
                className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                  filterStatus === f.value
                    ? 'bg-indigo-100 text-indigo-700'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                {f.label}
                {f.value === 'pending' && (stats.pending?.count || 0) > 0 && (
                  <span className="ml-1.5 bg-yellow-500 text-white text-xs px-1.5 py-0.5 rounded-full">{stats.pending?.count}</span>
                )}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Withdrawals Table */}
      <div className="card overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center h-32">
            <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
          </div>
        ) : withdrawals.length === 0 ? (
          <div className="text-center py-12">
            <Wallet className="w-12 h-12 text-gray-300 mx-auto mb-3" />
            <p className="text-gray-500">Belum ada permintaan penarikan</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-gray-200 bg-gray-50">
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Tanggal</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Tenant</th>
                  <th className="text-right py-3 px-4 font-medium text-gray-600">Jumlah</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Bank</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">No. Rekening</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Atas Nama</th>
                  <th className="text-center py-3 px-4 font-medium text-gray-600">Status</th>
                  <th className="text-center py-3 px-4 font-medium text-gray-600">Aksi</th>
                </tr>
              </thead>
              <tbody>
                {withdrawals.map(w => {
                  const statusConfig = WITHDRAWAL_STATUSES[w.status] || { label: w.status, color: 'bg-gray-100 text-gray-800' }
                  return (
                    <tr key={w.id} className="border-b border-gray-100 hover:bg-gray-50">
                      <td className="py-3 px-4 text-gray-600">
                        {new Date(w.createdAt).toLocaleDateString('id-ID', {
                          day: 'numeric', month: 'short', year: 'numeric',
                        })}
                        <br />
                        <span className="text-xs text-gray-400">
                          {new Date(w.createdAt).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2">
                          <Building2 className="w-4 h-4 text-gray-400" />
                          <div>
                            <p className="font-medium text-gray-900">{w.tenantName}</p>
                            <p className="text-xs text-gray-400">{w.tenantSlug}</p>
                          </div>
                        </div>
                      </td>
                      <td className="py-3 px-4 text-right font-semibold text-gray-900">
                        Rp {w.amount.toLocaleString('id-ID')}
                      </td>
                      <td className="py-3 px-4 text-gray-700 font-medium">{w.bankName}</td>
                      <td className="py-3 px-4 text-gray-600 font-mono text-xs">{w.bankAccount}</td>
                      <td className="py-3 px-4 text-gray-700">{w.bankHolder}</td>
                      <td className="py-3 px-4 text-center">
                        <span className={`badge ${statusConfig.color}`}>{statusConfig.label}</span>
                        {w.adminNotes && (
                          <p className="text-xs text-gray-400 mt-1" title={w.adminNotes}>
                            <MessageSquare className="w-3 h-3 inline mr-1" />
                            {w.adminNotes.length > 30 ? w.adminNotes.slice(0, 30) + '...' : w.adminNotes}
                          </p>
                        )}
                      </td>
                      <td className="py-3 px-4 text-center">
                        {w.status === 'pending' ? (
                          <div className="flex items-center justify-center gap-2">
                            <button
                              onClick={() => { setShowNotesModal({ id: w.id, action: 'approve' }); setAdminNotes('') }}
                              disabled={processingId === w.id}
                              className="px-3 py-1.5 bg-green-600 text-white text-xs font-medium rounded-lg hover:bg-green-700 disabled:opacity-50 transition-colors"
                            >
                              {processingId === w.id ? <Loader2 className="w-3 h-3 animate-spin" /> : 'Setuju'}
                            </button>
                            <button
                              onClick={() => { setShowNotesModal({ id: w.id, action: 'reject' }); setAdminNotes('') }}
                              disabled={processingId === w.id}
                              className="px-3 py-1.5 bg-red-600 text-white text-xs font-medium rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors"
                            >
                              Tolak
                            </button>
                          </div>
                        ) : (
                          <span className="text-xs text-gray-400">
                            {w.processedAt && new Date(w.processedAt).toLocaleDateString('id-ID', {
                              day: 'numeric', month: 'short',
                            })}
                          </span>
                        )}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
        <Pagination pagination={pagination} onPageChange={(page) => fetchWithdrawals(page)} itemLabel="penarikan" />
      </div>

      {/* Notes Modal */}
      {showNotesModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl max-w-md w-full p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-1">
              {showNotesModal.action === 'approve' ? 'Setujui Penarikan' : 'Tolak Penarikan'}
            </h3>
            <p className="text-sm text-gray-500 mb-4">
              {showNotesModal.action === 'approve'
                ? 'Saldo tenant akan dikurangi sesuai jumlah penarikan.'
                : 'Penarikan akan ditolak dan saldo tenant tidak berubah.'}
            </p>
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-1">Catatan Admin (opsional)</label>
              <textarea
                className="input-field"
                rows={3}
                placeholder={showNotesModal.action === 'approve' ? 'Contoh: Transfer sudah dilakukan' : 'Contoh: Data rekening tidak valid'}
                value={adminNotes}
                onChange={(e) => setAdminNotes(e.target.value)}
              />
            </div>
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => { setShowNotesModal(null); setAdminNotes('') }}
                className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
              >
                Batal
              </button>
              <button
                onClick={() => handleAction(showNotesModal.id, showNotesModal.action, adminNotes)}
                disabled={processingId === showNotesModal.id}
                className={`px-4 py-2 text-sm font-medium text-white rounded-lg disabled:opacity-50 flex items-center gap-2 ${
                  showNotesModal.action === 'approve'
                    ? 'bg-green-600 hover:bg-green-700'
                    : 'bg-red-600 hover:bg-red-700'
                }`}
              >
                {processingId === showNotesModal.id && <Loader2 className="w-4 h-4 animate-spin" />}
                {showNotesModal.action === 'approve' ? 'Ya, Setujui' : 'Ya, Tolak'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
