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 { updateField } from "app/lib/update"
import { TableInputContainer } from "./inputContainer"

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() {
    if (value === initialValue) {
      setIsActive(false)
      return
    }
    updateField({
      id,
      table,
      text: value,
      column,
      pathname
    })
    initialValue = value
    setIsActive(false)
  }
  function handleExit() {
    setValue(initialValue)
    setIsActive(false)
  }

  return (
    <TableInputContainer isActive={isActive} setIsActive={setIsActive}>
      {isActive ?
        <Input
          value={value}
          onChange={e => setValue(e.target.value)}         // onBlur={handleClose}
          autoFocus={true}
          onBlur={handleExit}
          onKeyDown={e => { if (e.code === "Enter") { handleConfirm() } }}
          className="w-full"
        />
        : <p>{value}</p>
      }
    </TableInputContainer>
  )
}
