import React, { useState } from "react";
import Modal from "../../elements/Modal";
import Image from "next/image";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import VerificationBadge from "@/components/main/VerificationBadge";
import ProfileAvatar from "@/components/main/ProfileAvatar";
import RoundedInput from "@/components/elements/RoundedInput";
import useAxios from "@/hooks/useAxios";
import { useRequireAuth } from "@/lib/auth/useRequireAuth";

export interface Comments {
  _id: string;
  text: string;
  createdAt: string;
  updatedAt: string;
  status: string;
  advertisingId: string;
  userId: User;
  __v: never;
}

export interface User {
  profile_image: string | null;
  first_name: string;
  last_name: string;
  user_name: string;
  is_verified: string;
  user_type: string;
  _id: string;
}

type ReportModalProps = {
  isOpen: boolean;
  onClose: () => void;
  advertisingId: string;
};

function BillboardCommentsModal({
  isOpen,
  onClose,
  advertisingId,
}: ReportModalProps) {
  const { data, containerRef, isFetchingNextPage } = useInfiniteScroll({
    endpoint: "/advertising/comments",
    queryKey: ["comments", advertisingId],
    params: { advertisingId: advertisingId },
  });
  const [newMessage, setNewMessage] = useState("");
  const { request } = useAxios();
  const requireAuth = useRequireAuth();
  const sendMessageHandler = async () => {
    if (!requireAuth()) return;
    try {
      const data = {
        text: newMessage,
        advertisingId: advertisingId,
      };
      await request("POST", "/advertising/comment", data);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <div
      onClick={(e) => {
        e.stopPropagation();
      }}
    >
      <Modal isOpen={isOpen} onClose={onClose} height="540px">
        <div
          ref={containerRef}
          className="overflow-y-auto max-h-[500px] p-4 pb-16"
        >
          {data?.pages.length === 0 ||
          (data?.pages[0]?.comments?.length === 0 && !isFetchingNextPage) ? (
            <p className="text-center text-gray-500">نظری وجود ندارد.</p>
          ) : (
            data?.pages?.map((page, pageIndex) => (
              <React.Fragment key={pageIndex}>
                {page?.comments?.map((item: Comments) => (
                  <div key={item?._id} className="mb-4">
                    <div className="flex">
                      <ProfileAvatar
                        src={item?.userId?.profile_image}
                        alt={item?.userId?.user_name || "کاربر"}
                        size="chat"
                        rounded="full"
                        className="ml-2"
                      />
                      <div className="text-sm">
                        <div className="flex items-center gap-1 mt-1 font-semibold">
                          <span className="inline-flex items-center gap-1">
                            {item?.userId?.user_name}
                            <VerificationBadge isVerified={item?.userId?.is_verified} />
                          </span>
                        </div>
                        <p>{item.text}</p>
                      </div>
                    </div>
                  </div>
                ))}
              </React.Fragment>
            ))
          )}

          {isFetchingNextPage && (
            <p className="text-center text-gray-500">
              در حال بارگذاری نظرات...
            </p>
          )}
          <div className="flex items-center w-full p-4 rounded-full max-w-md fixed bottom-24 left-1/2 -translate-x-1/2 px-4 gap-2 ">
            <button onClick={sendMessageHandler}>
              <Image
                width={24}
                height={24}
                alt={"verify icon"}
                src={`/images/icons/send-msg.svg`}
                className="dark:invert min-w-[24px] min-h-[24px]"
              />
            </button>
            <RoundedInput
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
            />
          </div>
        </div>
      </Modal>
    </div>
  );
}

export default BillboardCommentsModal;
