"use client"
import { Input } from "@/components/ui/input";
import { CellContext } from "@tanstack/react-table";
import { updateField } from "app/lib/update";
import { useState } from "react";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "@/components/ui/use-toast";
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
import TitleContainer from "app/ui/titleContainer";
import { useRouter } from "next/navigation";

export function TextInputCell({ cellContext, className }: { className: string, cellContext: CellContext<any, any> }) {
  const [isActive, setIsActive] = useState(false)
  if (cellContext === undefined) {
    console.error("CELL CONTEXT UNDEFINED!")
    return false
  }
  const table = cellContext.table.options.meta.tableName
  const id = cellContext.row.original.id
  const column = cellContext.column.id
  const pathname = cellContext.table.options.meta.pathname
  const value = cellContext.cell.getValue()
  const formSchema = cellContext.column.columnDef.meta.formSchema.pick({ [column]: true })

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      [column]: cellContext.cell.getValue()
    },
  })
  const router = useRouter()
  async function onSubmit(value: z.infer<typeof formSchema>) {
    try {
      const res = await updateField({
        id,
        table,
        datum: value[column],
        column,
        pathname
      })
      if (res === undefined) throw new Error("something went wrong")
      toast({ title: "Field updated successfully." })
      router.refresh()
    } catch (error) {
      console.error(error)
      toast({ title: "Something went wrong." })
    }
    setIsActive(false)
  }

  function onErrors(errors) {
    toast({
      title: "You have errors",
      description: (
        <pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
          <code className="text-white">{JSON.stringify(errors, null, 2)}</code>
        </pre>
      ),
    })
    console.log(JSON.stringify(errors))
  }
  return (
    <div
      onDoubleClick={() => setIsActive(prev => !prev)}
      className={className + " w-full h-fit flex items-center justify-left"}
      tabIndex={0}
      onKeyDown={e => {
        if (e.code === "Enter" && !isActive) {
          e.preventDefault()
          setIsActive(true)
        }
      }}
    >
      {isActive ?
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit, onErrors)}
          >
            <FormField
              control={form.control}
              name={column}
              render={({ field }) => (
                <FormItem
                  onBlur={() => setIsActive(false)}
                >
                  <FormControl
                  >
                    <Input
                      className="w-full"
                      type="text"
                      autoFocus={true}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

          </form>
        </Form>
        : <TitleContainer>{cellContext.cell.getValue()}</TitleContainer>
      }
    </div >
  )
}
