import { keepPreviousData, useQuery } from "@tanstack/react-query"
import { TricksterCharacter } from "../lib/trickster"
import { useSessionContext } from "../context/SessionContext"
import { useLtoContext } from "../context/LtoContext"

import 'handsontable/dist/handsontable.full.min.css';

import { registerAllModules } from 'handsontable/registry';
import { HotTable, HotTableClass } from '@handsontable/react';
import { useCallback, useEffect, useRef, useState } from "react";
import { InventoryTable } from "../lib/table";
import { DotLoader } from "react-spinners";
import { useDebounceCallback, useResizeObserver } from "usehooks-ts";
import { Columns } from "../lib/columns";
import { OrderDetails, OrderSender } from "../lib/lifeto/order_manager";
import log from "loglevel";

registerAllModules();
type Size = {
  width?: number
  height?: number
}
export const Inventory = () => {
  const {activeTable, columns, tags, orders} = useSessionContext()
  const {API, loggedIn} = useLtoContext()

  const ref = useRef<HTMLDivElement>(null)
  const [{ height }, setSize] = useState<Size>({
    width: 100,
    height: 100,
  })

  const onResize = useDebounceCallback(setSize, 200)

  useResizeObserver({
    ref,
    onResize,
  })

  const hotTableComponent = useRef<HotTableClass>(null);
  const {data:character, isLoading, isFetching } = useQuery({
    queryKey:["inventory", activeTable],
    queryFn: async ()=> {
      return API.GetInventory(activeTable)
    },
    enabled: loggedIn,
    //   placeholderData: keepPreviousData,
  })
  const {data:characters} = useQuery({
    queryKey:["characters", API.s.user],
    queryFn: async ()=> {
      return API.GetAccounts().then(x=>{
        return x.flatMap(x=>{return x.characters})
      })
    },
    enabled: loggedIn,
    placeholderData: keepPreviousData,
  })


  useEffect(()=>{
    if(!character) {
      hotTableComponent.current?.hotInstance?.updateSettings({
        data: [],
      })
      return
    }
    const it = new InventoryTable(character, {
      columns: columns,
      tags: tags,
      accounts: characters?.map(x=>{
        return x.name
      }) || [],
    })
    const build = it.BuildTable()
    hotTableComponent.current?.hotInstance?.updateSettings(build.settings)
  }, [hotTableComponent, character, height])

  const sendOrders = useCallback(()=>{
    if(!hotTableComponent.current?.hotInstance){
      return
    }
    const hott = hotTableComponent.current?.hotInstance
    const headers = hott.getColHeader()
    const dat = hott.getData()
    const idxNumber = headers.indexOf(Columns.MoveCount.displayName)
    const idxTarget = headers.indexOf(Columns.Move.displayName)
    const origin = activeTable
    const pending:OrderDetails[] = [];
    for(const row of dat) {
      try{
      const nm = Number(row[idxNumber].replace("x",""))
      const target = (row[idxTarget] as string).replaceAll("-","").trim()
      if(!isNaN(nm) && nm > 0 && target.length > 0){
        const info:OrderDetails = {
          item_uid: row[0].toString(),
          count: nm,
          origin_path: activeTable,
          target_path: target,
        }
        pending.push(info)
      }
      }catch(e){
      }
    }
    log.debug("OrderDetails", pending)
    const chars = new Map<string,TricksterCharacter>()
    const manager = new OrderSender(orders, chars)
    for(const d of pending){
      const order = manager.send(d)
      //order.tick(api)
    }
  }, [orders])

  const Loading = ()=>{
    return <div role="status" className="flex align-center justify-center">
      <div className="justify-center py-4">
        <DotLoader color="#dddddd"/>
      </div>
    </div>
  }
  return <div ref={ref} className={``}>
    <div className="flex flex-row py-2 px-3">
      <div
        onClick={(e)=>{
          sendOrders()
        }}
        className="
        hover:cursor-pointer
        border border-black-1
        bg-green-200
        px-2 py-1
      ">ayy lmao button</div>
    </div>
    {(isLoading || isFetching) ? <Loading/> : <></> }
    <div
      className={`${isLoading || isFetching ? "invisible" : ""}`}>
      <HotTable
        ref={hotTableComponent as any}
        licenseKey="non-commercial-and-evaluation"
      />
    </div>
  </div>
}
