"use client";
import React, { useState } from "react";
import Cookies from "js-cookie";
import { useGetUserNotificationQuery } from "../store/api/UserNotificationList";
import groupNotifications from "./groupNotification";
import { ClipLoader } from "react-spinners";
import { useRouter } from "next/navigation";
import { useAppDispatch } from "../hooks/hooks";
import { setUserId } from "../store/Slice/SetUserIdForChatOpen";
import { MdOutlineArrowBackIos } from "react-icons/md";
import PostDetail from "../Explore/Post_Detail";
import ReelComment from "../Explore/Reel_Comment";
import { showModal, hideModal } from "../store/Slice/modalSlice";
import TextTranslate from "../utils/TextTranslate";
import Image from "next/image";
import { createPortal } from "react-dom";
function Notification() {
  const token = Cookies.get("Snapta_auth_token");
  const { data, isLoading } = useGetUserNotificationQuery({
    token: token || "",
  });

  const [selectedPost, setSelectedPost] = useState<{
    postId: string;
    images: string[];
  } | null>(null);

  const [selectedVideo, setSelectedVideo] = useState<{
    postId: string;
    url: string;
    index: number;
  } | null>(null);

  const handleImageClick = (postId: string, images: string[]) => {
    setSelectedPost({ postId, images });
  };

  const handleVideoClick = (postId: string, url: string, index: number) => {
    setSelectedVideo({ postId, url, index });
    dispatch(showModal("ReelDetail"));
  };

  const notificationList = data?.detail || [];
  const grouped = groupNotifications(notificationList);

  const router = useRouter();
  const dispatch = useAppDispatch();

 const handleUsernameClick = (user: any) => {
  if (!user?.username) {
    console.error("Username missing:", user);
    return;
  }
  router.push(`/Profile/${user.username}`);
};

  const renderNotification = (notification: any, index: number) => {
    const time = new Date(notification.created_at).toLocaleTimeString([], {
      hour: "2-digit",
      minute: "2-digit",
    });

    return (
      <div
        key={index}
        className="flex justify-between items-center py-2.5 w-full border-opacity-40"
      >
        <div className="flex gap-3 items-center">
          {/* User Profile Pic for Follow Type */}
          {notification.type === "follow_user" && (
  <img
    src={notification.profile_pic || "/assets/ProfilePicRounded.png"}
    alt="Profile"
    className="h-12 w-12 object-cover rounded-full border border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)] cursor-pointer"
    onClick={() => handleUsernameClick(notification)}
  />
)}

          {/* Post Thumbnail for Post Types */}
          {(notification.type === "comment_post" ||
            notification.type === "like_post" ||
            notification.type === "like_post_comment" ||
            notification.type === "subcomment_post" ||
            notification.type === "tag_post") && (
            <img
              src={notification.post_image[0]?.url}
              className="w-12 h-12 object-cover rounded-md border border-[var(--border-colordark)] cursor-pointer"
              onClick={() =>
                handleImageClick(
                  notification.post_id,
                  notification.post_image.map((img) => img?.url)
                )
              }
            />
          )}

          {/* Reel Thumbnail for Reel Types */}
          {(notification.type === "comment_reel" ||
            notification.type === "like_reel" ||
            notification.type === "like_reel_comment" ||
            notification.type === "subcomment_reel") && (
            <div className="relative">
              <img
                src={notification.post_image[0].post_video_thumbnail}
                className="w-12 h-12 object-cover rounded-md border border-[var(--border-colordark)] cursor-pointer"
                onClick={() =>
                  handleVideoClick(
                    notification.post_id,
                    notification.post_image[0]?.url,
                    index
                  )
                }
              />
            </div>
          )}

          <div className="flex flex-col">
            <button className="text-left">
              <span className="text-[var(--text-secondary)] text-sm font-gilroy_md leading-tight">
               <strong
  className="text-[var(--text-primary)] text-sm font-gilroy_semibold cursor-pointer hover:underline"
  onClick={() => handleUsernameClick(notification)}
>
  {notification.message?.split(" ")[0]}
</strong>{" "}
                {notification.message?.split(" ").slice(1).join(" ")}
              </span>
            </button>
            <p className="text-[var(--text-secondary)] text-xs font-gilroy_regular  ">
              {time}
            </p>
          </div>
        </div>
      </div>
    );
  };

  if (isLoading) {
    return (
      <div className="w-full flex justify-center items-center py-10">
        <ClipLoader color="var(--text-secondary)" size={20} />
      </div>
    );
  }

  return (
    <>
      <div className="w-full max-w-full px-1">
        <div className="h-screen bg-[var(--bg-primary)] overflow-y-auto hide-scrollbar relative z-0">
          {/* Header section matching Search logic */}
       <div className="flex justify-between items-center ">
  <div
    className="flex gap-2 items-center cursor-pointer"
   onClick={() => router.back()}
  >
    {/* Back Arrow - visible only on mobile */}
    <MdOutlineArrowBackIos className="sm:hidden text-[var(--text-primary)] text-lg" />
    
    {/* Notification Heading - visible only on mobile */}
    <h1 className="sm:hidden text-[var(--text-primary)] font-gilroy_bold text-lg">
      Notification
    </h1>
  </div>
</div>

          {grouped.Today.length === 0 &&
            grouped.Yesterday.length === 0 &&
            Object.keys(grouped.Other).length === 0 && (
              <div className="flex flex-col items-center justify-center py-20">
                <img 
                  src="/assets/NoPost.png" 
                  className="w-12 h-12 opacity-30 invert brightness-200" 
                  alt="No notifications"
                />
                <p className="font-gilroy_regular text-sm text-[var(--text-secondary)] opacity-60 mt-2">
                  <TextTranslate text="No Notification" />
                </p>
              </div>
            )}

          {/* Render Today's notifications */}
          {grouped.Today.length > 0 && (
            <div className="mb-2">
              <h2 className="text-[var(--text-primary)] font-gilroy_semibold text-base py-1.5 border-b border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]  border-opacity-20 mb-1">
                <TextTranslate text="Today" />
              </h2>
              {grouped.Today.map(renderNotification)}
            </div>
          )}

          {/* Render Yesterday's notifications */}
          {grouped.Yesterday.length > 0 && (
            <div className="mb-2">
              <h2 className="text-[var(--text-primary)] font-gilroy_semibold text-base py-1.5 border-b border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)] border-opacity-20 mb-1">
                <TextTranslate text="Yesterday" />
              </h2>
              {grouped.Yesterday.map(renderNotification)}
            </div>
          )}

          {/* Render Other date notifications */}
          {Object.entries(grouped.Other).map(([dateLabel, items]) => (
            <div key={dateLabel} className="mb-2">
              <h2 className="text-[var(--text-primary)] font-gilroy_semibold py-1.5 border-b border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)] border-opacity-20 mb-1 text-base">
                {dateLabel}
              </h2>
              {items.map(renderNotification)}
            </div>
          ))}
        </div>
      </div>

     {(selectedVideo || selectedPost) &&
  typeof window !== "undefined" &&
  createPortal(
    <div
      className="fixed inset-0 z-[999999] bg-black/20 backdrop-blur-sm flex items-center justify-center"
      onClick={() => {
        setSelectedPost(null);
        setSelectedVideo(null);
        dispatch(hideModal("ReelDetail"));
      }}
    >
      <div
        className="w-full h-full flex items-center justify-center p-4 md:p-10"
        onClick={(e) => e.stopPropagation()}
      >
        {selectedVideo && (
          <div className="w-full h-full md:w-auto md:h-auto md:max-w-[90vw] md:max-h-[90vh]">
            <ReelComment
              videoSrc={selectedVideo?.url}
              postId={selectedVideo.postId}
              onClose={() => {
                setSelectedVideo(null);
                dispatch(hideModal("ReelDetail"));
              }}
            />
          </div>
        )}

        {selectedPost && (
          <div className="w-full h-full md:w-auto md:h-auto md:max-w-[90vw] md:max-h-[90vh]">
            <PostDetail
              imageSrc={selectedPost.images[0]}
              images={selectedPost.images}
              postId={selectedPost.postId}
              onClose={() => setSelectedPost(null)}
            />
          </div>
        )}
      </div>
    </div>,
    document.body
  )}
    </>
  );
}

export default Notification;