import { timestampDate } from "@bufbuild/protobuf/wkt";
import { sortBy } from "lodash-es";
import { BellIcon, CheckIcon, InboxIcon } from "lucide-react";
import { useState } from "react";
import Empty from "@/components/Empty";
import MemoCommentMessage from "@/components/Inbox/MemoCommentMessage";
import MobileHeader from "@/components/MobileHeader";
import useMediaQuery from "@/hooks/useMediaQuery";
import { useInboxUnreadCount, useMarkMemoAsRead, useMemos, useNotifications } from "@/hooks/useUserQueries";
import { cn } from "@/lib/utils";
import { UserNotification, UserNotification_Status, UserNotification_Type } from "@/types/proto/api/v1/user_service_pb";
import { Memo } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";

const Inboxes = () => {
  const t = useTranslate();
  const md = useMediaQuery("md");
  const [filter, setFilter] = useState<"notifications" | "unread">("notifications");

  // Fetch notifications
  const { data: fetchedNotifications = [] } = useNotifications();
  // Fetch unread memos
  const { data: unreadMemosResponse } = useMemos({ isRead: false });
  const unreadMemos = unreadMemosResponse?.memos || [];

  const markAsReadMutation = useMarkMemoAsRead();

  const allNotifications = sortBy(fetchedNotifications, (notification: UserNotification) => {
    return -((notification.createTime ? timestampDate(notification.createTime) : undefined)?.getTime() || 0);
  });

  const notifications = allNotifications.filter((notification) => {
    if (filter === "unread" && notification.type === UserNotification_Type.MEMO_COMMENT) {
      return notification.status === UserNotification_Status.UNREAD;
    }
    return notification.status !== UserNotification_Status.ARCHIVED;
  });

  const unreadNotificationCount = allNotifications.filter((n) => n.status === UserNotification_Status.UNREAD).length;
  const unreadMemoCount = unreadMemos.length;

  // Handler for marking a memo as read
  const handleMarkAsRead = (memo: Memo) => {
    if (memo.name) {
      markAsReadMutation.mutate({ memoName: memo.name, isRead: true });
    }
  };

  return (
    <section className="@container w-full max-w-5xl min-h-full flex flex-col justify-start items-center sm:pt-3 md:pt-6 pb-8">
      {!md && <MobileHeader />}
      <div className="w-full px-4 sm:px-6">
        <div className="w-full border border-border flex flex-col justify-start items-start rounded-xl bg-background text-foreground overflow-hidden">
          {/* Header */}
          <div className="w-full px-4 py-4 border-b border-border">
            <div className="flex flex-row justify-between items-center">
              <div className="flex flex-row items-center gap-2">
                <BellIcon className="w-5 h-auto text-muted-foreground" />
                <h1 className="text-xl font-semibold">{t("common.inbox")}</h1>
                {(unreadNotificationCount + unreadMemoCount > 0) && (
                  <span className="ml-1 px-2 py-0.5 text-xs font-medium rounded-full bg-primary text-primary-foreground">
                    {unreadNotificationCount + unreadMemoCount}
                  </span>
                )}
              </div>
            </div>
          </div>

          {/* Filter Tabs */}
          <div className="w-full px-4 py-2 border-b border-border bg-muted/30">
            <div className="flex flex-row gap-1">
              <button
                onClick={() => setFilter("notifications")}
                className={cn(
                  "px-3 py-1.5 text-sm font-medium rounded-md transition-colors flex items-center gap-1.5",
                  filter === "notifications"
                    ? "bg-background text-foreground shadow-sm"
                    : "text-muted-foreground hover:text-foreground hover:bg-background/50",
                )}
              >
                <BellIcon className="w-3.5 h-auto" />
                {t("inbox.notifications")} ({unreadNotificationCount})
              </button>
              <button
                onClick={() => setFilter("unread")}
                className={cn(
                  "px-3 py-1.5 text-sm font-medium rounded-md transition-colors flex items-center gap-1.5",
                  filter === "unread"
                    ? "bg-background text-foreground shadow-sm"
                    : "text-muted-foreground hover:text-foreground hover:bg-background/50",
                )}
              >
                <InboxIcon className="w-3.5 h-auto" />
                {t("inbox.unread-memos")} ({unreadMemoCount})
              </button>
            </div>
          </div>

          {/* Content List */}
          <div className="w-full">
            {filter === "notifications" ? (
              notifications.length === 0 ? (
                <div className="w-full py-16 flex flex-col justify-center items-center">
                  <Empty />
                  <p className="mt-4 text-sm text-muted-foreground">
                    {t("inbox.no-notifications")}
                  </p>
                </div>
              ) : (
                <div className="flex flex-col">
                  {notifications.map((notification: UserNotification) => {
                    if (notification.type === UserNotification_Type.MEMO_COMMENT) {
                      return <MemoCommentMessage key={notification.name} notification={notification} />;
                    }
                    return null;
                  })}
                </div>
              )
            ) : (
              // Unread Memos tab
              unreadMemos.length === 0 ? (
                <div className="w-full py-16 flex flex-col justify-center items-center">
                  <Empty />
                  <p className="mt-4 text-sm text-muted-foreground">
                    {t("inbox.no-unread-memos")}
                  </p>
                </div>
              ) : (
                <div className="flex flex-col">
                  {unreadMemos.map((memo: Memo) => (
                    <div
                      key={memo.name}
                      className="flex items-start gap-3 p-4 border-b border-border hover:bg-muted/30 transition-colors"
                    >
                      <div className="flex-1 min-w-0">
                        <p className="text-sm text-foreground whitespace-pre-wrap break-words">
                          {memo.content}
                        </p>
                        <div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
                          {memo.tags && memo.tags.length > 0 && (
                            <div className="flex gap-1">
                              {memo.tags.slice(0, 3).map((tag) => (
                                <span key={tag} className="px-1.5 py-0.5 bg-secondary text-secondary-foreground rounded text-[10px]">
                                  #{tag}
                                </span>
                              ))}
                              {memo.tags.length > 3 && (
                                <span className="text-[10px]">+{memo.tags.length - 3}</span>
                              )}
                            </div>
                          )}
                        </div>
                      </div>
                      <button
                        onClick={() => handleMarkAsRead(memo)}
                        disabled={markAsReadMutation.isPending}
                        className={cn(
                          "shrink-0 p-2 rounded-full transition-colors",
                          "text-muted-foreground hover:text-primary hover:bg-primary/10",
                          markAsReadMutation.isPending && "opacity-50 cursor-not-allowed"
                        )}
                        title={t("inbox.mark-as-read")}
                      >
                        <CheckIcon className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                </div>
              )
            )}
          </div>
        </div>
      </div>
    </section>
  );
};

export default Inboxes;
