// ##################################################################

// I AM NOT USING THIS FUNCTION

// ##################################################################

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import Axios from "@/lib/Axios";
import { PaginationStructT } from "@/types/global";
import { NotesT } from "@/types/notes";

import { useQuery } from "@tanstack/react-query";
import { memo, useEffect, useRef, useState } from "react";
import {
  CommentT,
  noteCommentStruct,
  useCommentHandler,
} from "../useCommentHandler";
import { format } from "date-fns";
import SendNote from "./sendNote";
import { getRandomDarkColor } from "@/lib/getRandomDarkColor";

export default function NoteListHandler(id: number) {
  const { data, error, isLoading, isSuccess, refetch } = useQuery({
    queryKey: ["list-customer-comments"],
    queryFn: fetchData,
  });

  const { insertNode } = useCommentHandler();

  async function fetchData() {
    return Axios.get<PaginationStructT<NotesT[]>>("/customer/notes/", {
      params: {
        customer: id,
        ordering: "-created_at",
      },
    }).then((res) => {
      for (let i of res.data.data) {
        insertNode(i, noteCommentStruct);
      }

      return res.data.data;
    });
  }

  function ReturnNote() {
    return (
      <>
        <DisplayNote data={data || []} customerId={id} refetch={refetch} />
      </>
    );
  }

  return {
    ReturnNote,
    refetch,
  };
}

function DisplayNote({
  data,
  refetch,
  customerId,
}: {
  data: NotesT[];
  refetch: () => void;
  customerId: number;
}) {
  const [open, setOpen] = useState(false);
  const [commentToggle, setCommentToggle] = useState(false);

  function toggle() {
    setOpen((prev) => !prev);
  }
  return (
    <div className="space-y-3">
      {data?.map((item) => {
        return (
          <div key={item.id} className="text-black ">
            <div className="flex items-start gap-4 w-full">
              <Avatar>
                <AvatarImage alt="@shadcn" />
                <AvatarFallback
                  style={{
                    backgroundColor: getRandomDarkColor(),
                  }}
                  className=" text-white"
                >
                  {/* {(item.created_by?.name || "").charAt(0)?.toUpperCase()} */}
                </AvatarFallback>
              </Avatar>

              <div className="bg-white rounded-lg p-2 w-full">
                <p className="">
                  <span className="font-semibold">
                    {/* {item.created_by?.name + " "} */}
                  </span>
                  {format(item?.updated_at, "dd MMM, yyyy ") +
                   "at" +
                    format(item?.updated_at, " h:mm aa")}{" "}
                  {/* {item?.updated_at + ""} */}
                </p>
                <div className="">
                  <ClampText key={item.id} text={item?.note} />
                </div>
                {item?.replies?.length > 0 && (
                  <p
                    className="cursor-pointer text-sm" 
                    onClick={() => item?.replies.length && toggle()}
                  >
                    View {item?.replies?.length} replies
                  </p>
                )}

                {/* {item.child_note === null && (
                  <div className="my-2">
                    <SendNote
                      id={customerId}
                      parent_id={item.id}
                      refetch={refetch}
                    />
                  </div>
                )} */}
              </div>
            </div>
            {open && (
              <div className=" ml-16 mt-5">
                <DisplayNote
                  customerId={customerId}
                  refetch={refetch}
                  data={item?.replies}
                />
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

const ClampText = ({ text }: { text: string }) => {
  const pRef = useRef<HTMLParagraphElement>(null);
  const [show, setShow] = useState(false);
  const [showBtn, setShowBtn] = useState(false);

  function countLines() {
    if (!pRef.current) return;
    const divHeight = pRef?.current?.offsetHeight;
    const lineHeight = parseInt(pRef?.current?.style.lineHeight);

    const lines = divHeight / lineHeight;
    return lines;
  }
  useEffect(() => {
    const lines = countLines() || 0;

    if (lines > 2) {
      setShowBtn(true);
    }
  }, []);

  return (
    <div>
      <div
        ref={pRef}
        className={`text-black ${
          !show && " line-clamp-3 "
        } whitespace-pre-wrap my-2`}
        style={{ lineHeight: "20px" }}
      >
        {text}
      </div>

      {showBtn && (
        <p
          onClick={(e) => {
            e.stopPropagation();
            setShow((prev) => !prev);
          }}
          className="text-danger cursor-pointer text-right text-sm"
        >
          {!show ? "View more" : "View less"}
        </p>
      )}
    </div>
  );
};
