"use client";
import { Textarea } from "@/components/ui/textarea";
import { useParams, usePathname, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@/components/ui/carousel";
import { Link, useRouter } from "@/i18n/routing";
import { deleteBlogComments, getBlogComments, getDetailIndeks, getPublicSuggestionList, postBlogComments, publicDetailBlog } from "@/service/landing/landing";
import { formatDateToIndonesian } from "@/utils/globals";
import { Icon } from "@iconify/react/dist/iconify.js";
import { getCookiesDecrypt } from "@/lib/utils";
import { close, loading } from "@/config/swal";

const IndeksDetail = () => {
  const searchParams = useSearchParams();
  const id = searchParams?.get("id");
  const [indeksData, setIndeksData] = useState<any>();
  const params = useParams();
  const slug = params?.slug;
  const [indexData, setIndexData] = useState<any>();
  const [message, setMessage] = useState("");
  const userId = getCookiesDecrypt("uie");
  const userRoleId = getCookiesDecrypt("urie");
  const router = useRouter();
  const [listComments, setListComments] = useState([]);

  useEffect(() => {
    initFetch();
    detailFetch();
  }, []);
  const initFetch = async () => {
    const response = await getDetailIndeks();
    console.log(response);
    setIndexData(response?.data?.data?.content);
  };
  const detailFetch = async () => {
    const response = await publicDetailBlog(slug);
    console.log(response);
    setIndeksData(response?.data?.data);
  };

  async function getDataComment(blogId: any) {
    const findId = blogId == undefined ? slug : blogId;
    const response = await getBlogComments(findId);
    console.log(response.data?.data);
    setListComments(response.data?.data);
  }

  const showInput = (e: any) => {
    console.log(document.querySelector(`#${e}`)?.classList);
    document.querySelector(`#${e}`)?.classList.toggle("hidden");
  };

  async function sendCommentParent() {
    if (message?.length > 3) {
      loading();
      const data = {
        blogId: slug,
        message,
        parentId: null,
      };

      const response = await postBlogComments(data);

      console.log(response);
      setMessage("");
      getDataComment(slug);
      close();
    }
  }

  async function sendCommentChild(parentId: any) {
    const inputMsg = document.querySelector(`#input-comment-${parentId}`) as HTMLInputElement;

    if (inputMsg && inputMsg.value.length > 3) {
      loading();
      const data = {
        blogId: slug,
        message: inputMsg,
        parentId,
      };

      console.log(data);
      const response = await postBlogComments(data);
      console.log(response);
      const responseGet = await getPublicSuggestionList(slug);
      console.log(responseGet.data?.data);
      getDataComment(slug);
      $(":input").val("");
      close();
    }
  }

  async function deleteDataComment(dataId: any) {
    loading();
    const response = await deleteBlogComments(dataId);
    console.log(response);
    getDataComment(dataId);
    close();
  }

  const getInputValue = (e: any) => {
    const message = e.target.value;
    console.log(message);
    setMessage(message);
  };

  const postData = () => {
    if (Number(userRoleId) < 1) {
      router.push("/auth");
    } else {
      sendCommentParent();
    }
  };

  const postDataChild = (id: any) => {
    if (Number(userRoleId) < 1) {
      router.push("/auth");
    } else {
      sendCommentChild(slug);
    }
  };

  const deleteData = (dataId: any) => {
    deleteDataComment(dataId);
    console.log(dataId);
  };

  return (
    <>
      <div className="p-4 lg:px-60 lg:p-12">
        {/* Judul */}
        <div className="flex flex-col mb-5">
          <h1 className="text-lg mb-2">Indeks / Detail</h1>
          <h1 className="flex flex-row font-bold text-center text-2xl">{indeksData?.title}</h1>
        </div>
        {/* Gambar Utama */}
        <div className="flex items-center justify-center">
          <img src={indeksData?.thumbnailLink} alt="Main" className="h-[550px] w-full rounded-lg" />
        </div>
        {/* Footer Informasi */}
        <div className="text-sm text-gray-500 flex justify-between items-center border-t mt-4">
          <div className="flex flex-row items-center mt-3 justify-between">
            oleh&nbsp;<span className="font-semibold text-black">{indeksData?.uploaderName}</span>&nbsp; | &nbsp;Diupdate pada {indeksData?.createdAt} WIB &nbsp;
          </div>
        </div>

        {/* Keterangan */}
        <div className="w-auto">
          <p className="font-light text-justify" dangerouslySetInnerHTML={{ __html: indeksData?.description }} />
        </div>
      </div>

      {/* Comment */}
      <div className="w-full">
        <div className="flex flex-col py-5 p-10 bg-[#f7f7f7]">
          <div className="gap-5 flex flex-col px-4 lg:px-16">
            <p className="flex items-start text-lg">Berikan Komentar</p>
            <Textarea placeholder="Type your comments here." className="flex w-full" onChange={getInputValue} />
            <button className="flex items-start bg-[#bb3523] text-white rounded-lg w-fit px-4 py-1" onClick={() => postData()}>
              Kirim
            </button>
          </div>

          <div className="border-b-2  border-slate-300 mt-4 w-auto"></div>

          <div>
            {listComments?.map((data: any) => (
              <div className="flex flex-col">
                <div className="flex flex-row mt-2 px-4 lg:px-14">
                  <img className="h-10 w-10" src="/assets/img/user-avatar-yellow.svg" alt="#" />
                  <div className="border border-slate-300 w-full p-4 bg-white gap-1">
                    <p className="text-slate-500 text-base border-b-2 border-slate-200 mb-2">
                      <b>{Number(data.commentFrom?.roleId) == 2 || Number(data.commentFrom?.roleId) == 3 || Number(data.commentFrom?.roleId) == 4 ? "HUMAS POLRI" : data.commentFrom?.fullname}</b>
                      {`${new Date(data.createdAt).getDate()}/${new Date(data.createdAt).getMonth() + 1}/${new Date(data.createdAt).getFullYear()} ${new Date(data.createdAt).getHours()}:${new Date(data.createdAt).getMinutes()}`}
                    </p>
                    <p className="text-slate-500 text-sm mb-4">{data.message}</p>
                    <div>
                      <a href="javascript:void(0)" className="btn btn-link btn-suggestion-reply" onClick={() => showInput(`comment-id-${data.id}`)}>
                        Balas
                      </a>
                      <a
                        href="javascript:void(0)"
                        style={
                          data.commentFrom?.id == userId
                            ? {}
                            : {
                                display: "none",
                              }
                        }
                        className="btn btn-link btn-suggestion-delete"
                        onClick={() => deleteData(data.id)}
                      >
                        Hapus
                      </a>
                    </div>
                  </div>
                </div>
                <div className="px-4 lg:px-28 mt-2" id={`comment-id-${data.id}`}>
                  <Textarea id={`input-comment-${data.id}`} className="p-4 focus:outline-none focus:border-sky-500" placeholder="Masukkan balasan anda" />
                  <a href="javascript:void(0)" className="btn btn-warning btn-send-comment" onClick={() => postDataChild(data.id)}>
                    Send
                  </a>
                </div>
                {data.children.length > 0
                  ? data.children?.map((child1: any) => (
                      <div className="flex flex-col">
                        <div className="flex flex-row mt-2 px-4 lg:px-32">
                          <img className="h-10 w-10" src="/assets/img/user-avatar-yellow.svg" alt="#" />
                          <div className="border border-slate-300 w-full p-4 bg-white gap-1">
                            <p className="text-slate-500 text-base border-b-2 border-slate-200 mb-2">
                              <b>{Number(child1.commentFrom?.roleId) == 2 || Number(child1.commentFrom?.roleId) == 3 || Number(child1.commentFrom?.roleId) == 4 ? "HUMAS POLRI" : child1.commentFrom?.fullname}</b>
                              {`${new Date(child1.createdAt).getDate()}/${new Date(child1.createdAt).getMonth() + 1}/${new Date(child1.createdAt).getFullYear()} ${new Date(child1.createdAt).getHours()}:${new Date(
                                child1.createdAt
                              ).getMinutes()}`}
                            </p>
                            <p className="text-slate-500 text-sm mb-4">{child1.message}</p>
                            <div>
                              <a href="javascript:void(0)" className="btn btn-link btn-suggestion-reply" onClick={() => showInput(`comment-id-${child1.id}`)}>
                                Balas
                              </a>
                              <a
                                href="javascript:void(0)"
                                className="btn btn-link btn-suggestion-delete"
                                style={
                                  Number(child1.commentFrom?.id) == Number(userId)
                                    ? {}
                                    : {
                                        display: "none",
                                      }
                                }
                                onClick={() => deleteData(child1.id)}
                              >
                                Hapus
                              </a>
                            </div>
                          </div>
                        </div>
                        <div className="px-4 lg:px-28 mt-2" id={`comment-id-${child1.id}`}>
                          <Textarea id={`input-comment-${child1.id}`} className="p-4 focus:outline-none focus:border-sky-500" placeholder="Masukkan balasan anda" />
                          <a href="javascript:void(0)" className="btn btn-warning btn-send-comment" onClick={() => postDataChild(child1.id)}>
                            Send
                          </a>
                        </div>
                        {child1.children.length > 0
                          ? child1.children?.map((child2: any) => (
                              <div className="flex flex-col">
                                <div className="flex flex-row mt-2 px-4 lg:px-48">
                                  <img className="h-10 w-10" src="/assets/img/user-avatar-yellow.svg" alt="#" />
                                  <div className="border border-slate-300 w-full p-4 bg-white gap-1">
                                    <p className="text-slate-500 text-base border-b-2 border-slate-200 mb-2">
                                      <b>{Number(child2.commentFrom?.roleId) == 2 || Number(child2.commentFrom?.roleId) == 3 || Number(child2.commentFrom?.roleId) == 4 ? "HUMAS POLRI" : child2.commentFrom?.fullname}</b>
                                      {`${new Date(child2.createdAt).getDate()}/${new Date(child2.createdAt).getMonth() + 1}/${new Date(child2.createdAt).getFullYear()} ${new Date(child2.createdAt).getHours()}:${new Date(
                                        child2.createdAt
                                      ).getMinutes()}`}
                                    </p>
                                    <p className="text-slate-500 text-sm mb-4">{child2.message}</p>
                                    <div>
                                      <a
                                        href="javascript:void(0)"
                                        className="btn btn-link btn-suggestion-delete"
                                        style={
                                          Number(child2.commentFrom?.id) == Number(userId)
                                            ? {}
                                            : {
                                                display: "none",
                                              }
                                        }
                                        onClick={() => deleteData(child2.id)}
                                      >
                                        Hapus
                                      </a>
                                    </div>
                                  </div>
                                </div>
                                <div className="px-4 lg:px-28 mt-2" id={`comment-id-${child2.id}`}>
                                  <Textarea id={`comment-id-${child2.id}`} className="p-4 focus:outline-none focus:border-sky-500" placeholder="Masukkan balasan anda" />
                                  <a href="javascript:void(0)" className="btn btn-warning btn-send-comment" onClick={() => postDataChild(child1.id)}>
                                    Send
                                  </a>
                                </div>
                              </div>
                            ))
                          : ""}
                      </div>
                    ))
                  : ""}
              </div>
            ))}
          </div>
        </div>

        {/* Konten Serupa */}
        <div className="space-x-5 flex flex-col px-4 lg:px-16 py-16 gap-5">
          <h1 className="font-bold text-base lg:text-xl px-4 lg:px-8">Post Terkait</h1>
          <Carousel>
            <CarouselContent className="w-full max-w-7xl">
              {indexData?.map((relate: any) => (
                <CarouselItem key={relate?.id} className="md:basis-1/2 lg:basis-1/3">
                  <Link href={`/indeks/detail/${relate?.slug}`} className="relative group overflow-hidden shadow-md hover:shadow-lg">
                    <img src={relate?.thumbnailLink} className="w-full rounded-lg h-40 lg:h-60 object-cover group-hover:scale-100 transition-transform duration-300" />
                    <div className="absolute bottom-0 left-0 right-0 bg-gray-600 border-l-4 border-[#bb3523] rounded-lg backdrop-blur-sm text-white p-2">
                      <span className="text-white bg-[#bb3523] rounded-md w-full h-full font-semibold uppercase text-sm px-4 py-1">{relate?.categoryName}</span>
                      <h1 className="text-sm lg:text-lg mb-2 font-semibold h-5 hover:h-auto truncate hover:whitespace-normal hover:overflow-visible">{relate?.title}</h1>
                      <p className="flex flex-row items-center text-[10px] gap-2">
                        {formatDateToIndonesian(new Date(relate?.createdAt))} {relate?.timezone ? relate?.timezone : "WIB"} | <Icon icon="formkit:eye" width="15" height="15" /> {relate.clickCount}{" "}
                      </p>
                    </div>
                  </Link>
                </CarouselItem>
              ))}
            </CarouselContent>
            <CarouselPrevious />
            <CarouselNext />
          </Carousel>
        </div>
      </div>
    </>
  );
};

export default IndeksDetail;
