import { useMemo, useState } from 'react'

export default function TableShell({
  items,
  loading,
  columns,
  searchKeys,
  rowAction,
}) {
  const [query, setQuery] = useState('')
  const [page, setPage] = useState(1)
  const pageSize = 7

  const filtered = useMemo(() => {
    if (!Array.isArray(items)) return []
    const q = query.trim().toLowerCase()
    if (!q) return items

    return items.filter((row) => {
      return searchKeys.some((k) => {
        if (k === 'product' || k === 'warehouse') return true
        const v = row[k]
        if (v === undefined || v === null) return false
        return String(v).toLowerCase().includes(q)
      })
    })
  }, [items, query, searchKeys])

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize))
  const currentPage = Math.min(page, totalPages)

  const paged = useMemo(() => {
    const start = (currentPage - 1) * pageSize
    return filtered.slice(start, start + pageSize)
  }, [filtered, currentPage])

  return (
    <div>
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-3">
        <div className="flex-1">
          <input
            value={query}
            onChange={(e) => {
              setQuery(e.target.value)
              setPage(1)
            }}
            placeholder="Search..."
            className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none focus:border-fuchsia-400/60"
          />
        </div>
        <div className="text-xs text-slate-400">{filtered.length} results</div>
      </div>

      <div className="overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead className="text-xs text-slate-400">
            <tr>
              {columns.map((c) => (
                <th
                  key={c.header}
                  scope="col"
                  className="sticky top-0 z-10 bg-slate-950/95 backdrop-blur text-left font-semibold py-3 px-3 border-b border-white/10"
                >
                  {c.header}
                </th>
              ))}
              <th className="sticky top-0 z-10 bg-slate-950/95 backdrop-blur text-right font-semibold py-3 px-3 border-b border-white/10">
                Actions
              </th>
            </tr>
          </thead>

          <tbody>
            {loading ? (
              <tr>
                <td colSpan={columns.length + 1} className="py-10 text-center text-slate-500">
                  <div className="inline-flex items-center gap-2">
                    <span className="h-2.5 w-2.5 rounded-full bg-fuchsia-400/70 animate-pulse" />
                    Loading...
                  </div>
                </td>
              </tr>
            ) : paged.length === 0 ? (
              <tr>
                <td colSpan={columns.length + 1} className="py-12 text-center">
                  <div className="mx-auto max-w-sm">
                    <div className="text-sm font-semibold text-slate-200">No records found</div>
                    <div className="mt-1 text-xs text-slate-500">Try adjusting your search.</div>
                  </div>
                </td>
              </tr>
            ) : (
              paged.map((row) => (
                <tr
                  key={row._id}
                  className="border-t border-white/10 transition-colors hover:bg-white/5"
                >
                  {columns.map((c) => (
                    <td key={c.header} className="py-3 px-3">
                      <div className="font-medium text-slate-100">{c.accessor(row) ?? '—'}</div>
                    </td>
                  ))}
                  <td className="py-3 px-3 text-right">{rowAction?.(row)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      <div className="flex items-center justify-between mt-4 gap-3">
        <div className="text-xs text-slate-400">Page {currentPage} of {totalPages}</div>
        <div className="flex gap-2">
          <button
            disabled={currentPage <= 1}
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            className="rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-white/10 transition"
          >
            Prev
          </button>
          <button
            disabled={currentPage >= totalPages}
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            className="rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-white/10 transition"
          >
            Next
          </button>
        </div>
      </div>
    </div>
  )
}

