"use client";

import Container from "@/components/elements/Container";
import RoundedInput from "@/components/elements/RoundedInput";
import PageTitle from "@/components/settings/PageTitle";
import UserDetails from "@/components/settings/UserDetails";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import Image from "next/image";
import Link from "next/link";
import React, { useEffect, useState } from "react";

export interface INotification {
  _id: string;
  userId: string;
  project_post_id?: string;
  type: string;
  title: string;
  description: string;
  read: boolean;
  createdAt: string;
}

function Notifications() {
  const [searchText, setSearchText] = useState("");
  const [search, setSearch] = useState("");
  const [userType, setUserType] = useState<string | null>("");

  useEffect(() => {
    if (typeof window !== "undefined") {
      setUserType(localStorage.getItem("usertype"));
    }
  }, []);
  const { data, isFetchingNextPage } = useInfiniteScroll({
    endpoint: "/notifications",
    queryKey: ["notifications", search],
    params: { search: search },
  });

  function getNotificationLink(item: INotification): string {
    const workroomPath =
      userType === "user"
        ? `/settings/workroom/user/${item?.project_post_id}`
        : `/settings/workroom/${item?.project_post_id}`;

    const routes: Record<string, string> = {
      request_accepted: workroomPath,
      payment_progress: workroomPath,
      "recive-project": workroomPath,
      request: workroomPath,
      "accept-project": workroomPath,
      end_project: workroomPath,
      "reject-project": workroomPath,
      invite: `/users/${item?.project_post_id}`,
      vitrine: `/settings/my-billboards/${item?.project_post_id}/b`,
      "vitrine-comment": `/settings/my-billboards/${item?.project_post_id}/b`,
      "ticket-message": `/settings/tickets/${encodeURIComponent(
        item?.title?.split("/").pop() || ""
      )}/${item?.project_post_id}`,
      new_offer: "/settings/offers",
      post_like: `/posts/${item?.project_post_id}`,
      academy_like: `/academy/${item?.project_post_id}/course`,
      billboard_like: `/settings/my-billboards/${item?.project_post_id}/b`,
      post_comment: `/posts/${item?.project_post_id}`,
      profile_comment: "/settings/profile",
      user_comment: "/settings/profile",
      academy_comment: `/academy/${item?.project_post_id}/course`,
      billboard_comment: `/settings/my-billboards/${item?.project_post_id}/b`,
      billboard_rating: `/settings/my-billboards/${item?.project_post_id}/b`,
      "reject-user": `/tickets/new/${
        item?.project_post_id
      }/${encodeURIComponent(item?.title?.split("/").pop() || "")}`,
    };

    return routes[item?.type] || "#";
  }
  return (
    <Container>
      <PageTitle>اعلانات</PageTitle>
      <div className="px-4 text-xs md:text-sm">
        <UserDetails />
        <div className="w-full relative mt-5">
          <RoundedInput
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            placeholder="جستجو"
            className="w-full"
          />
          <Image
            width={25}
            height={25}
            alt="filter icon"
            src="/images/icons/search-normal.svg"
            className=" min-w-[25px] absolute left-3 top-[7px]"
            onClick={() => setSearch(searchText)}
          />
        </div>
        <div className="w-full mt-5 font-semibold">
          {data?.pages.length === 0 ||
          (data?.pages[0]?.notifications?.length === 0 &&
            !isFetchingNextPage) ? (
            <p className="text-center text-gray-500">اعلانی ثبت نشده است.</p>
          ) : (
            data?.pages?.map((page, pageIndex) => (
              <React.Fragment key={pageIndex}>
                {page?.notifications?.map((item: INotification) => (
                  <Link
                    href={getNotificationLink(item)}
                    key={item?._id}
                    className="mb-4 p-4 border-b border-border-primary-light w-full block"
                  >
                    <div className="flex w-full items-center justify-between ">
                      <div className="flex items-center gap-2">
                        {!item?.read ? (
                          <div className="bg-[#05FF00] rounded-full w-4 h-4"></div>
                        ) : (
                          ""
                        )}
                        <p>{item?.title}</p>
                      </div>
                      <span>{item?.createdAt}</span>
                    </div>
                    <p className="mt-4">{item?.description}</p>
                  </Link>
                ))}
              </React.Fragment>
            ))
          )}
        </div>
      </div>
    </Container>
  );
}

export default Notifications;
