import { useRef, useState } from "react";
import SendIcon from "./icons/SendIcon";
import Button from "./Button";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import api from "../utils/api";
import { Comment } from "../types/Comment";
import SessionCommentItem from "./SessionCommentItem";
import { AnimatePresence, motion } from "motion/react";
import { groupByCreatedAt } from "../utils/groupByCreatedAt";
import { format, isToday } from "date-fns";
import { ru } from "date-fns/locale";

function SessionComments({ sessionId }: { sessionId: string }) {
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const formRef = useRef<HTMLFormElement>(null);

  const handleTextareaInput = () => {
    const textarea = textareaRef.current;
    const form = formRef.current;
    if (!textarea || !form) return;

    textarea.style.height = "auto";

    const minTextareaHeight = (24 / 1440) * window.innerWidth;
    const maxTextareaHeight = (180 / 1440) * window.innerWidth;
    const formPadding = (1.111 / 100) * window.innerWidth * 2;
    const minFormHeight = (80 / 1440) * window.innerWidth;
    const maxFormHeight = (225 / 1440) * window.innerWidth;

    const scrollHeight = textarea.scrollHeight;

    let newTextareaHeight;
    if (scrollHeight <= minTextareaHeight) {
      newTextareaHeight = minTextareaHeight;
    } else if (scrollHeight <= maxTextareaHeight) {
      newTextareaHeight = scrollHeight;
    } else {
      newTextareaHeight = maxTextareaHeight;
    }

    const newFormHeight = Math.max(
      Math.min(newTextareaHeight + formPadding, maxFormHeight),
      minFormHeight
    );

    textarea.style.height = `${newTextareaHeight}px`;
    form.style.height = `${newFormHeight}px`;

    textarea.style.overflowY =
      scrollHeight > maxTextareaHeight ? "auto" : "hidden";
  };

  const queryClient = useQueryClient();

  const { data: grouppedComments } = useQuery({
    queryKey: ["sessions", "comments", sessionId],
    queryFn: () => api.get(`comments/${sessionId}`).json<Comment[]>(),
    select: groupByCreatedAt,
  });

  const { mutate: createComment } = useMutation({
    mutationFn: (comment: string) =>
      api.post("comments", {
        json: {
          sessionId: sessionId,
          text: comment,
        },
      }),
    onSuccess: () =>
      queryClient.invalidateQueries({
        queryKey: ["sessions", "comments"],
      }),
  });

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const textarea = textareaRef.current;
    if (
      !textarea?.value ||
      textarea.value.length > 200 ||
      textarea.value.trim() === ""
    )
      return;

    createComment(textarea.value);
    textarea.value = "";
    setValue("");
    handleTextareaInput();
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSubmit(e as unknown as React.FormEvent<HTMLFormElement>);
    }
  };

  const [value, setValue] = useState("");

  return (
    <div className="outline flex flex-col flex-1 outline-[#D6D6D6]">
      <div className="relative h-full flex flex-col-reverse gap-[0.833vw] overflow-y-auto p-[1.111vw] [scrollbar-width:thin]">
        <AnimatePresence mode="wait">
          {grouppedComments && grouppedComments.length > 0 ? (
            grouppedComments.map(([timestamp, comments], index) => (
              <motion.div layout className="space-y-[1.111vw]" key={index}>
                <p className="text-center text-[#BDBDBD] caption-s">
                  {isToday(new Date(timestamp))
                    ? "Сегодня"
                    : format(new Date(timestamp), "d MMMM", { locale: ru })}
                </p>
                <div className="flex flex-col-reverse gap-[0.833vw]">
                  {comments.map((comment) => (
                    <SessionCommentItem key={comment.id} comment={comment} />
                  ))}
                </div>
              </motion.div>
            ))
          ) : (
            <div className="flex flex-col gap-[1.111vw] items-center justify-center h-full">
              <img
                src="/images/smile-ghost.png"
                className="w-[13.889vw]"
                alt="ghost"
              />
              <div className="flex flex-col gap-[0.556vw] items-center">
                <h3 className="title-m font-medium">Оставьте заметку</h3>
                <p className="caption-s font-medium text-[#BDBDBD] text-center whitespace-pre-line">
                  {`В дальнейшем это поможет быстро найти
            клиента и не запутаться.`}
                </p>
              </div>
            </div>
          )}
        </AnimatePresence>
      </div>
      <form
        ref={formRef}
        className="flex gap-[2.222vw] max-h-[27.778vw] bg-white justify-center items-start p-[1.111vw]"
        name="commment"
        onSubmit={handleSubmit}
      >
        <textarea
          ref={textareaRef}
          rows={1}
          name="comment"
          className="w-[17.083vw] outline-none text-s resize-none self-center"
          placeholder="Расскажите, как все прошло"
          onChange={(e) => {
            setValue(e.target.value);
          }}
          style={{
            wordWrap: "break-word",
            overflowY: "hidden",
          }}
          onInput={handleTextareaInput}
          onKeyDown={handleKeyDown}
        />
        <Button variant="cta" size="large" type="submit" disabled={!value}>
          <span className="size-[1.111vw] text-white">
            <SendIcon />
          </span>
        </Button>
      </form>
    </div>
  );
}

export default SessionComments;
