"use client";
import React from "react";
import { Comment } from "@/server/db/schema";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import { commentSchema } from "@/lib/validation/zod/comment";
import CommentEditor from "../editor/comment-editor";
import { createComment } from "@/server/actions/comment";
import { toast } from "sonner";
import { EditorInstance } from "novel";
import { XIcon } from "lucide-react";
import { useSocket } from "../socket-context";
import { ADD_COMMENT_EVENT } from "@/server/socket/event-const";
import { api } from "@/trpc/react";

function CommentForm({
  articleId,
  parentComment,
  removeReplyComment,
  commentRefs,
}: {
  articleId: string;
  parentComment?: Comment;
  commentRefs: React.MutableRefObject<Map<string, HTMLDivElement | null>>;
  removeReplyComment: () => void;
}) {
  const [loading, setLoading] = React.useState(false);
  const { mutate } = api.comment.create.useMutation({
    onSuccess: (comment) => {
      setLoading(false);
      socket?.emit(ADD_COMMENT_EVENT, comment);

      toast.success("Kommentar hinzugefügt.");
    },
    onError: () => {
      setLoading(false);
      toast.error("Etwas ist schief gelaufen.");
    },
  });
  const { socket } = useSocket();
  const form = useForm<z.infer<typeof commentSchema>>({
    resolver: zodResolver(commentSchema),
    defaultValues: {
      parentId: parentComment?.id ?? "",
      content: undefined,
    },
  });
  const editorRef = React.useRef<EditorInstance | null>(null);
  const editor = editorRef.current;

  async function onSubmit(values: z.infer<typeof commentSchema>) {
    setLoading(true);
    mutate({ comment: { ...values, parentId: parentComment?.id }, articleId });

    form.reset();
    editor?.commands?.clearContent();
    removeReplyComment();
    // setTimeout(() => {
    //   const el = commentRefs.current.get(res?.data?.data!);
    //   console.log("el", el);
    //   el?.scrollIntoView({
    //     behavior: "smooth",
    //     block: "start",
    //   });
    //   el?.classList.add("animate-fade-in");
    // }, 500);
  }

  React.useEffect(() => {
    if (parentComment) editor?.commands?.focus();
  }, [parentComment]);

  return (
    <>
      {parentComment && (
        <div className="flex items-center gap-1">
          <Button
            className="size-max p-1"
            variant={"ghost"}
            onClick={removeReplyComment}
          >
            <XIcon className="size-4" />
          </Button>
          <p>answer comment</p>
        </div>
      )}
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="rounded-md bg-muted p-4"
        >
          <FormField
            control={form.control}
            name="content"
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <CommentEditor
                    setEditor={(editor) => {
                      editorRef.current = editor;
                    }}
                    initialContent={field.value}
                    onContentChange={field.onChange}
                  >
                    <Button
                      type="submit"
                      className="ml-auto h-max py-1"
                      size="sm"
                    >
                      Absenden
                    </Button>
                  </CommentEditor>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </form>
      </Form>
    </>
  );
}

export default CommentForm;
