import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import { paymentsApi } from '../../api'
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline'
import { useDebounce } from '../../hooks/useDebounce'

const TYPE_BADGE: Record<string, string> = {
  rental:        'text-blue-300 bg-blue-900/50',
  deposit:       'text-purple-300 bg-purple-900/50',
  deposit_refund:'text-pink-300 bg-pink-900/50',
  lost_key_fee:  'text-red-300 bg-red-900/50',
  renewal:       'text-green-300 bg-green-900/50',
  other:         'text-slate-300 bg-slate-700',
}

export default function PaymentsPage() {
  const [page, setPage]   = useState(1)
  const [status, setStatus] = useState('')
  const [type, setType]   = useState('')
  const [from, setFrom]   = useState('')
  const [to, setTo]       = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['payments', status, type, from, to, page],
    queryFn: () => paymentsApi.list({ status, type, from, to, page, per_page: 25 }).then(r => r.data),
  })

  const payments = data?.data ?? []
  const meta     = data?.meta  ?? {}
  const total    = payments.reduce((sum: number, p: any) => sum + Number(p.amount), 0)

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Payments</h1>
          <p className="text-slate-400 text-sm mt-0.5">{meta.total ?? 0} total transactions</p>
        </div>
      </div>

      <div className="card flex flex-wrap gap-3 items-end">
        <div>
          <label className="label">Status</label>
          <select value={status} onChange={e => { setStatus(e.target.value); setPage(1) }} className="input w-36">
            <option value="">All</option>
            <option value="completed">Completed</option>
            <option value="pending">Pending</option>
            <option value="voided">Voided</option>
            <option value="refunded">Refunded</option>
          </select>
        </div>
        <div>
          <label className="label">Type</label>
          <select value={type} onChange={e => { setType(e.target.value); setPage(1) }} className="input w-40">
            <option value="">All types</option>
            <option value="rental">Rental</option>
            <option value="deposit">Deposit</option>
            <option value="deposit_refund">Deposit Refund</option>
            <option value="lost_key_fee">Lost Key Fee</option>
            <option value="renewal">Renewal</option>
          </select>
        </div>
        <div>
          <label className="label">From</label>
          <input type="date" value={from} onChange={e => { setFrom(e.target.value); setPage(1) }} className="input w-40" />
        </div>
        <div>
          <label className="label">To</label>
          <input type="date" value={to} onChange={e => { setTo(e.target.value); setPage(1) }} className="input w-40" />
        </div>
      </div>

      {/* Summary */}
      <div className="card bg-slate-700/50">
        <p className="text-sm text-slate-400">Showing page total</p>
        <p className="text-2xl font-bold text-white">৳{total.toLocaleString()}</p>
      </div>

      <div className="card p-0 overflow-hidden">
        <table className="w-full">
          <thead className="border-b border-slate-700">
            <tr className="text-left text-xs text-slate-400 uppercase tracking-wider">
              <th className="px-4 py-3">Ref</th>
              <th className="px-4 py-3">Client</th>
              <th className="px-4 py-3">Type</th>
              <th className="px-4 py-3">Method</th>
              <th className="px-4 py-3">Amount</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">Date</th>
              <th className="px-4 py-3">By</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-700/50">
            {isLoading && <tr><td colSpan={8} className="text-center py-12 text-slate-400">Loading…</td></tr>}
            {!isLoading && payments.length === 0 && (
              <tr><td colSpan={8} className="text-center py-12 text-slate-400">No payments found.</td></tr>
            )}
            {payments.map((p: any) => (
              <tr key={p.id} className="hover:bg-slate-700/30 transition-colors">
                <td className="px-4 py-3 font-mono text-xs text-slate-400">{p.transaction_ref ?? '-'}</td>
                <td className="px-4 py-3">
                  {p.client ? (
                    <Link to={`/clients/${p.client.id}`} className="text-sm text-blue-400 hover:underline">{p.client.full_name}</Link>
                  ) : '—'}
                </td>
                <td className="px-4 py-3">
                  <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${TYPE_BADGE[p.type] ?? TYPE_BADGE.other}`}>
                    {p.type?.replace('_', ' ')}
                  </span>
                </td>
                <td className="px-4 py-3 text-sm text-slate-300">{p.payment_method?.name ?? '-'}</td>
                <td className="px-4 py-3 text-sm font-semibold text-white">৳{Number(p.amount).toLocaleString()}</td>
                <td className="px-4 py-3">
                  <span className={`text-xs ${p.status === 'completed' ? 'text-green-400' : p.status === 'voided' ? 'text-slate-400' : 'text-red-400'}`}>
                    {p.status}
                  </span>
                </td>
                <td className="px-4 py-3 text-xs text-slate-400">
                  {p.paid_at ? new Date(p.paid_at).toLocaleDateString() : '—'}
                </td>
                <td className="px-4 py-3 text-xs text-slate-400">{p.collected_by?.name ?? '-'}</td>
              </tr>
            ))}
          </tbody>
        </table>

        {meta.last_page > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t border-slate-700">
            <p className="text-sm text-slate-400">Showing {meta.from}–{meta.to} of {meta.total}</p>
            <div className="flex gap-2">
              <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1} className="btn-secondary text-sm px-3 py-1">Prev</button>
              <button onClick={() => setPage(p => Math.min(meta.last_page, p + 1))} disabled={page === meta.last_page} className="btn-secondary text-sm px-3 py-1">Next</button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
