import { Cell, CellContext, Table } from "@tanstack/react-table"
import { useState, useEffect } from "react"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Check, CircleX } from "lucide-react"
import { updateTextField } from "app/lib/update"

export const TextInputCell = (props: CellContext<any, any>) => {
  let initialValue = props.getValue()
  const [value, setValue] = useState(initialValue)
  const [isActive, setIsActive] = useState(false)

  const table = props.table.options.meta.tableName
  const id = props.row.original.id
  const column = props.column.id
  const pathname = props.table.options.meta.pathname

  function handleConfirm() {
    updateTextField({
      id,
      table,
      text: value,
      column,
      pathname
    })
    initialValue = value
    handleClose()
  }
  function handleOpen() {
    setIsActive(true)
  }
  function handleClose() {
    setValue(initialValue)
    setIsActive(false)
  }
  function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
    if (event.code === "Enter") {
      handleConfirm()
    }
  }


  return (<div
    onDoubleClick={() => setIsActive(prev => !prev)}
    className="w-full h-fit flex items-center justify-center"
    tabIndex={0}
    onKeyDown={e => {
      if (e.code === "Enter" && !isActive) {
        setIsActive(true)
      }
    }}
  >
    {isActive ?
      <Input
        value={value}
        onChange={e => setValue(e.target.value)}         // onBlur={handleClose}
        autoFocus={true}
        onBlur={handleClose}
        onKeyDown={handleKeyDown}
        className="w-full"
      />
      : <p>{value}</p>
    }
  </div>)
}
