import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import { lockersApi } from '../../api'
import { MagnifyingGlassIcon, PlusIcon } from '@heroicons/react/24/outline'
import clsx from 'clsx'

const STATUS_COLORS: Record<string, string> = {
  available:   'bg-green-900/50 border-green-700 text-green-300',
  occupied:    'bg-blue-900/50 border-blue-700 text-blue-300',
  maintenance: 'bg-yellow-900/50 border-yellow-700 text-yellow-300',
  reserved:    'bg-purple-900/50 border-purple-700 text-purple-300',
}

export default function LockersPage() {
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')
  const [view, setView]     = useState<'grid' | 'table'>('grid')

  const { data, isLoading } = useQuery({
    queryKey: ['lockers', search, status],
    queryFn: () => lockersApi.list({ search, status, per_page: 100 }).then(r => r.data),
  })

  const lockers = data?.data ?? []

  // Summary counts
  const counts = lockers.reduce((acc: any, l: any) => {
    acc[l.status] = (acc[l.status] || 0) + 1
    return acc
  }, {})

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Lockers</h1>
          <p className="text-slate-400 text-sm mt-0.5">
            {lockers.length} total · {counts.available ?? 0} available · {counts.occupied ?? 0} occupied · {counts.maintenance ?? 0} maintenance
          </p>
        </div>
        <Link to="/lockers/new" className="btn-primary flex items-center gap-2">
          <PlusIcon className="w-4 h-4" />
          Add Locker
        </Link>
      </div>

      {/* Filters */}
      <div className="card flex flex-wrap gap-3 items-center">
        <div className="relative flex-1 min-w-40">
          <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)}
            placeholder="Locker number…"
            className="input pl-9"
          />
        </div>
        <select value={status} onChange={(e) => setStatus(e.target.value)} className="input w-40">
          <option value="">All statuses</option>
          <option value="available">Available</option>
          <option value="occupied">Occupied</option>
          <option value="maintenance">Maintenance</option>
        </select>
        <div className="flex gap-1 bg-slate-700 p-1 rounded-lg">
          <button onClick={() => setView('grid')} className={clsx('px-3 py-1 rounded text-sm', view === 'grid' ? 'bg-slate-500 text-white' : 'text-slate-400')}>Grid</button>
          <button onClick={() => setView('table')} className={clsx('px-3 py-1 rounded text-sm', view === 'table' ? 'bg-slate-500 text-white' : 'text-slate-400')}>Table</button>
        </div>
      </div>

      {isLoading && <div className="text-slate-400 text-center py-20">Loading lockers…</div>}

      {/* Grid view */}
      {view === 'grid' && !isLoading && (
        <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 xl:grid-cols-8 gap-3">
          {lockers.map((l: any) => (
            <Link
              key={l.id}
              to={`/lockers/${l.id}`}
              className={clsx(
                'border rounded-xl p-3 text-center hover:scale-105 transition-all cursor-pointer',
                STATUS_COLORS[l.status] ?? 'bg-slate-700 border-slate-600 text-slate-300'
              )}
            >
              <p className="font-bold text-sm">{l.locker_number}</p>
              <p className="text-xs mt-1 opacity-75">{l.category?.name}</p>
              {l.active_rental && (
                <p className="text-xs mt-1 truncate opacity-75">{l.active_rental.client?.full_name}</p>
              )}
            </Link>
          ))}
        </div>
      )}

      {/* Table view */}
      {view === 'table' && !isLoading && (
        <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">Locker</th>
                <th className="px-4 py-3">Category</th>
                <th className="px-4 py-3">Zone</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Current Tenant</th>
                <th className="px-4 py-3">Key ID</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-700/50">
              {lockers.map((l: any) => (
                <tr key={l.id} className="hover:bg-slate-700/30 transition-colors">
                  <td className="px-4 py-3">
                    <Link to={`/lockers/${l.id}`} className="font-mono font-bold text-blue-400 hover:underline">
                      {l.locker_number}
                    </Link>
                  </td>
                  <td className="px-4 py-3 text-sm text-slate-300">{l.category?.name}</td>
                  <td className="px-4 py-3 text-sm text-slate-300">{l.zone?.name ?? '-'}</td>
                  <td className="px-4 py-3"><span className={`badge-${l.status}`}>{l.status}</span></td>
                  <td className="px-4 py-3 text-sm text-slate-300">
                    {l.active_rental?.client?.full_name ?? <span className="text-slate-500">—</span>}
                  </td>
                  <td className="px-4 py-3 text-sm text-slate-400 font-mono">{l.physical_key_id ?? '-'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
