import { StatsColumns } from "@/lib/columns"
import { ItemWithSelection } from "@/lib/table/defs"
import { InventoryColumns } from "@/lib/table/tanstack"
import { inventoryItemsCurrentPageAtom, preferenceInventoryTab } from "@/state/atoms"
import { flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
import { atom, useAtom, useAtomValue } from "jotai"
import { useMemo } from "react"


const columnVisibilityAtom = atom((get)=>{
  const itemTab = get(preferenceInventoryTab)
  if(!["2","4"].includes(itemTab)) {
    return Object.fromEntries([
      ...StatsColumns.map(x=>["stats."+x,false]),
      ["slots",false]
    ])
  }
  return {
  }
})
export const InventoryTable = () => {

  const items = useAtomValue(inventoryItemsCurrentPageAtom)

  const columns = useMemo(()=>{
    return [
      ...Object.values(InventoryColumns)
    ]
  }, [])

  const columnVisibility = useAtomValue(columnVisibilityAtom)
  console.log(columnVisibility)

  const table = useReactTable<ItemWithSelection>({
    getRowId: row =>row.item.unique_id.toString(),
    data: items,
    state: {
      columnVisibility,
    },
    columns,
    getCoreRowModel: getCoreRowModel(),
  })

  return (
    <div className="overflow-y-auto h-full mb-32">
      <table
        onContextMenu={(e)=>{
          e.preventDefault()
          return
        }}
        className="border-spacing-x-2 border-separate">
        <thead className="sticky top-0 z-10 select-none bg-white">
          {table.getHeaderGroups().map(headerGroup => (
            <tr
              className=""
              key={headerGroup.id}>
              {headerGroup.headers.map(header => (
                <th
                  key={header.id}
                  className="text-left"
                >
                  {header.isPlaceholder
                    ? null
                    : flexRender(
                      header.column.columnDef.header,
                      header.getContext()
                    )}
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody className="divide-y divide-gray-200">
          {table.getRowModel().rows.map(row => (
            <tr
              key={row.id}
              className={""}
            >
              {row.getVisibleCells().map(cell => (
                <td key={cell.id}>
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
