import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import { rentalsApi } from '../../api'
import { MagnifyingGlassIcon, PlusIcon } from '@heroicons/react/24/outline'
import { useDebounce } from '../../hooks/useDebounce'
import { format } from 'date-fns'

export default function RentalsPage() {
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')
  const [page, setPage]     = useState(1)
  const debounced           = useDebounce(search, 400)

  const { data, isLoading } = useQuery({
    queryKey: ['rentals', debounced, status, page],
    queryFn:  () => rentalsApi.list({ search: debounced, status, page, per_page: 20 }).then(r => r.data),
  })

  const rentals = data?.data ?? []
  const meta    = data?.meta  ?? {}

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Rentals</h1>
          <p className="text-slate-400 text-sm mt-0.5">{meta.total ?? 0} total rentals</p>
        </div>
        <Link to="/rentals/new" className="btn-primary flex items-center gap-2">
          <PlusIcon className="w-4 h-4" /> New Rental
        </Link>
      </div>

      <div className="card flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-48">
          <MagnifyingGlassIcon className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input value={search} onChange={(e) => { setSearch(e.target.value); setPage(1) }}
            placeholder="Search by client, rental number…" className="input pl-9" />
        </div>
        <select value={status} onChange={(e) => { setStatus(e.target.value); setPage(1) }} className="input w-44">
          <option value="">All statuses</option>
          <option value="active">Active</option>
          <option value="expired">Expired</option>
          <option value="cancelled">Cancelled</option>
        </select>
      </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">Rental #</th>
              <th className="px-4 py-3">Client</th>
              <th className="px-4 py-3">Locker</th>
              <th className="px-4 py-3">Period</th>
              <th className="px-4 py-3">Amount</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">Key</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-700/50">
            {isLoading && <tr><td colSpan={7} className="text-center py-12 text-slate-400">Loading…</td></tr>}
            {!isLoading && rentals.length === 0 && <tr><td colSpan={7} className="text-center py-12 text-slate-400">No rentals found.</td></tr>}
            {rentals.map((r: any) => (
              <tr key={r.id} className="hover:bg-slate-700/30 transition-colors">
                <td className="px-4 py-3">
                  <Link to={`/rentals/${r.id}`} className="text-blue-400 hover:underline font-mono text-sm">{r.rental_number}</Link>
                </td>
                <td className="px-4 py-3 text-sm text-white">{r.client?.full_name}</td>
                <td className="px-4 py-3 font-mono text-sm text-slate-300">{r.locker?.locker_number}</td>
                <td className="px-4 py-3 text-xs text-slate-400">
                  {r.start_date} → {r.end_date}
                  {r.days_remaining != null && r.status === 'active' && (
                    <span className={`ml-2 font-medium ${r.days_remaining <= 0 ? 'text-red-400' : r.days_remaining <= 3 ? 'text-yellow-400' : 'text-green-400'}`}>
                      ({r.days_remaining <= 0 ? `${r.days_overdue}d overdue` : `${r.days_remaining}d left`})
                    </span>
                  )}
                </td>
                <td className="px-4 py-3 text-sm text-slate-300">৳{Number(r.rental_amount).toLocaleString()}</td>
                <td className="px-4 py-3"><span className={`badge-${r.status}`}>{r.status}</span></td>
                <td className="px-4 py-3">
                  <span className={`text-xs ${r.key_status === 'with_client' ? 'text-blue-400' : r.key_status === 'lost' ? 'text-red-400' : 'text-green-400'}`}>
                    {r.key_status?.replace('_', ' ')}
                  </span>
                </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">Previous</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>
  )
}
