"use client";

import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import UserDetails from "@/components/settings/UserDetails";
import NotificationRow from "@/components/settings/NotificationRow";
import ListDateSeparator from "@/components/settings/ListDateSeparator";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { groupItemsByDate } from "@/lib/groupItemsByDate";
import React, { useEffect, useMemo, useState } from "react";
import BoldIcon from "@/components/ui/BoldIcon";
import {
  NOTIFICATION_FILTERS,
  NotificationFilterId,
  notificationMatchesFilter,
} from "@/constants/notificationFilters";
import { useTranslation } from "react-i18next";

const LIKE_NOTIFICATION_TYPES = new Set([
  "post_like",
  "academy_like",
  "billboard_like",
]);

const COMMENT_NOTIFICATION_TYPES = new Set([
  "post_comment",
  "profile_comment",
  "user_comment",
  "academy_comment",
  "billboard_comment",
  "vitrine-comment",
]);

const RATING_NOTIFICATION_TYPES = new Set([
  "post_rating",
  "profile_rating",
  "academy_rating",
  "billboard_rating",
]);

export interface NotificationActor {
  _id: string;
  user_name?: string;
  profile_image?: string;
  first_name?: string;
  last_name?: string;
}

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

function Notifications() {
  const { t, i18n } = useTranslation("common");
  const listLang = i18n.language === "en" ? "en" : "fa";
  const [searchInput, setSearchInput] = useState("");
  const [search, setSearch] = useState("");
  const [activeFilter, setActiveFilter] = useState<NotificationFilterId>("all");
  const [userType, setUserType] = useState<string | null>("");

  useEffect(() => {
    if (typeof window !== "undefined") {
      setUserType(localStorage.getItem("usertype"));
    }
  }, []);

  useEffect(() => {
    const timer = window.setTimeout(() => setSearch(searchInput.trim()), 400);
    return () => window.clearTimeout(timer);
  }, [searchInput]);

  const { data, isFetchingNextPage } = useInfiniteScroll({
    endpoint: "/notifications",
    queryKey: ["notifications", search],
    params: { search },
  });

  const getNotificationTitle = (item: INotification): string => {
    if (item.actor?.user_name) {
      return item.actor.user_name;
    }
    if (LIKE_NOTIFICATION_TYPES.has(item.type)) return t("settings.notifications.newLike");
    if (COMMENT_NOTIFICATION_TYPES.has(item.type)) return t("settings.notifications.newComment");
    if (RATING_NOTIFICATION_TYPES.has(item.type)) return t("settings.notifications.newRating");
    return item.title;
  };

  const getNotificationDescription = (item: INotification): string => {
    if (item.description && item.description !== item.title) {
      return item.description;
    }
    if (LIKE_NOTIFICATION_TYPES.has(item.type)) return t("settings.notifications.likedPost");
    if (COMMENT_NOTIFICATION_TYPES.has(item.type)) return t("settings.notifications.commented");
    if (RATING_NOTIFICATION_TYPES.has(item.type)) return t("settings.notifications.ratedYou");
    return item.description || item.title;
  };

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

    const routes: Record<string, string> = {
      // پیشنهاد جدید برای کارفرما → صفحه اتاق کار سازنده (تایید درخواست)
      request: creatorWorkroom,
      request_accepted: applicantWorkroom,
      payment_progress: workroomPath,
      "recive-project": applicantWorkroom,
      "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}`,
      post_rating: `/posts/${item?.project_post_id}`,
      post_tag: `/posts/${item?.project_post_id}`,
      profile_comment: "/settings/profile",
      profile_rating: "/settings/profile",
      user_comment: "/settings/profile",
      academy_comment: `/academy/${item?.project_post_id}/course`,
      academy_rating: `/academy/${item?.project_post_id}/course`,
      academy_purchase: `/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": "/settings/edit/Authentication",
      verify: "/settings/edit/Authentication",
    };

    return routes[item?.type] || "#";
  }

  const filteredItems = useMemo(() => {
    const all = data?.pages?.flatMap((page) => page?.notifications ?? []) ?? [];
    return all.filter((item: INotification) =>
      notificationMatchesFilter(item.type, activeFilter)
    );
  }, [data?.pages, activeFilter]);

  const groupedItems = useMemo(
    () =>
      groupItemsByDate(
        filteredItems,
        (item) => item.createdAt,
        (item) => item._id,
        listLang,
        { includeTime: true }
      ),
    [filteredItems, listLang]
  );

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.nav.notifications")}</PageTitle>
        <div className="text-xs md:text-sm">
          <UserDetails />
          <div className="mt-4 space-y-2">
            <form
              className="flex items-center gap-2 rounded-full border border-neutral-200 bg-background px-3 py-2.5 dark:border-neutral-800"
              onSubmit={(event) => {
                event.preventDefault();
                setSearch(searchInput.trim());
              }}
            >
              <BoldIcon
                name="search-normal"
                size={18}
                className="shrink-0 text-neutral-500"
              />
              <input
                type="search"
                value={searchInput}
                onChange={(event) => setSearchInput(event.target.value)}
                placeholder={t("settings.notifications.searchPlaceholder")}
                className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-neutral-500"
              />
            </form>
            <div className="flex gap-2 overflow-x-auto pb-1 scrollbar-none">
              {NOTIFICATION_FILTERS.map((item) => (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => setActiveFilter(item.id)}
                  className={`shrink-0 rounded-full px-3 py-1.5 text-xs font-semibold transition ${
                    activeFilter === item.id
                      ? "bg-[#FF107D] text-white"
                      : "bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-200"
                  }`}
                >
                  {t(item.labelKey)}
                </button>
              ))}
            </div>
          </div>

          <div className="mt-5 font-semibold">
            {filteredItems.length === 0 && !isFetchingNextPage ? (
              <p className="text-center text-gray-500">
                {t("settings.notifications.empty")}
              </p>
            ) : (
              groupedItems.map((entry) =>
                entry.type === "date" ? (
                  <ListDateSeparator key={entry.key} label={entry.label} />
                ) : (
                  <NotificationRow
                    key={entry.key}
                    item={entry.item}
                    href={getNotificationLink(entry.item)}
                    title={getNotificationTitle(entry.item)}
                    description={getNotificationDescription(entry.item)}
                  />
                )
              )
            )}
          </div>
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default Notifications;
