import { Button, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { getNotifications, markAllNotificationsRead, markNotificationRead, type NotificationItem } from "../../api/notifications";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useUserStore } from "../../store/user";
import { setSocialDefaultTab } from "../../utils/navFlags";
import "./index.scss";

const TAB_PAGES = new Set([
  "/pages/home/index",
  "/pages/mutual-aid/index",
  "/pages/live/index",
  "/pages/social/index",
  "/pages/profile/index"
]);

function relatedType(item: NotificationItem) {
  return String(item.relatedType || item.related_type || item.targetType || "").trim();
}

function relatedId(item: NotificationItem) {
  return item.targetId || item.relatedId || item.related_id || 0;
}

function isRead(item: NotificationItem) {
  return item.isRead || !!item.readAt || !!item.read_at;
}

function fallbackTarget(item: NotificationItem) {
  const type = relatedType(item);
  const id = relatedId(item);
  if (type === "member_application") return "/pages/join/index";
  if (type === "friendship") return "/pages/social/index";
  if (type === "activity" && id) return `/pages/activity-detail/index?id=${id}`;
  if (type === "content" && id) return `/pages/content-detail/index?id=${id}`;
  if (type === "proposal" && id) return `/pages/suggestion-detail/index?id=${id}`;
  if (type === "survey" && id) return `/pages/my-survey-detail/index?id=${id}`;
  if (type === "service_project" && id) return `/pages/service-detail/index?id=${id}`;
  if (type === "service_team" && id) return `/pages/service-team-detail/index?id=${id}`;
  if ((type === "mutual_aid" || type === "mutual_aid_contact_request") && id) return `/pages/mutual-aid-detail/index?id=${id}`;
  if (type === "help_request" || type === "service_help_request") return id ? `/pages/service-help-detail/index?id=${id}` : "/pages/my-service-projects/index";
  if (type === "performance_record") return "/pages/my-points/index";
  if (type === "evaluation" || type === "achievement" || type === "award" || type === "service_impact" || type === "duty_record") return "/pages/evaluation/index";
  if (type === "agent_action" || type === "ai_action" || type === "action_request") return "/pages/ai-approvals/index";
  if (type === "agent_grant" || type === "ai_grant") return "/pages/ai-grants/index";
  if (type === "passport" && id) return `/pages/passport-detail/index?passportId=${encodeURIComponent(String(id))}`;
  if (type === "report" || type === "social_block") return "/pages/social-settings/index";
  return "";
}

function notificationTarget(item: NotificationItem) {
  return String(item.pageTarget || item.page_target || fallbackTarget(item)).trim();
}

function typeLabel(item: NotificationItem) {
  const type = relatedType(item) || String(item.type || "");
  if (type === "member_application") return "入会";
  if (type === "friendship") return "好友";
  if (type === "activity") return "活动";
  if (type === "content") return "内容";
  if (type === "proposal") return "建言";
  if (type === "survey") return "问卷";
  if (type === "service_project") return "服务";
  if (type === "service_team") return "服务团";
  if (type === "mutual_aid" || type === "mutual_aid_contact_request") return "互助";
  if (type === "help_request" || type === "service_help_request") return "求助";
  if (type === "performance_record") return "履职";
  if (type === "evaluation" || type === "achievement" || type === "award" || type === "service_impact" || type === "duty_record") return "成就";
  if (type === "agent_action" || type === "ai_action" || type === "action_request") return "AI确认";
  if (type === "agent_grant" || type === "ai_grant") return "AI授权";
  if (type === "passport") return "通行证";
  if (type === "report" || type === "social_block") return "社交";
  if (type === "review") return "审核";
  if (type === "todo") return "待办";
  return "消息";
}

function displayTime(item: NotificationItem) {
  return String(item.createdAt || item.created_at || "").replace("T", " ").slice(0, 16) || "-";
}

export default function NotificationsPage() {
  useAuthGuard();
  const bootstrap = useUserStore((state) => state.bootstrap);
  const [items, setItems] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const load = async () => {
    setLoading(true);
    try {
      const rows = await getNotifications();
      setItems(Array.isArray(rows) ? rows : []);
      setError("");
    } catch (e: any) {
      setError(e?.message || "消息加载失败");
    } finally {
      setLoading(false);
    }
  };

  useDidShow(() => {
    void load();
  });

  const markLocalRead = (id: number) => {
    setItems((prev) => prev.map((item) => item.id === id ? { ...item, isRead: true, readAt: item.readAt || new Date().toISOString() } : item));
  };

  const openItem = async (item: NotificationItem) => {
    if (item.id && !isRead(item)) {
      try {
        await markNotificationRead(item.id);
        markLocalRead(item.id);
        void bootstrap();
      } catch {
        // Navigation should still work if the read marker is temporarily unavailable.
      }
    }

    const type = relatedType(item);
    if (type === "friendship") {
      setSocialDefaultTab("inbox");
      await Taro.switchTab({ url: "/pages/social/index" });
      return;
    }

    const target = notificationTarget(item);
    if (!target) {
      Taro.showToast({ title: "暂未配置跳转页面", icon: "none" });
      return;
    }

    const pagePath = target.split("?")[0];
    if (TAB_PAGES.has(pagePath)) {
      await Taro.switchTab({ url: pagePath });
      return;
    }
    await Taro.navigateTo({ url: target });
  };

  const readAll = async () => {
    try {
      await markAllNotificationsRead();
      setItems((prev) => prev.map((item) => ({ ...item, isRead: true, readAt: item.readAt || new Date().toISOString() })));
      void bootstrap();
      Taro.showToast({ title: "已全部标记已读", icon: "none" });
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "操作失败", icon: "none" });
    }
  };

  const unreadCount = items.filter((item) => !isRead(item)).length;

  return (
    <View className="notifications-page">
      <View className="notifications-page__body">
        <View className="notifications-head">
          <View>
            <Text className="notifications-head__title">消息通知</Text>
            <Text className="notifications-head__sub">{unreadCount ? `${unreadCount} 条未读` : "暂无未读消息"}</Text>
          </View>
          <Button className="notifications-head__button" disabled={!items.length || unreadCount === 0} onClick={() => void readAll()}>
            全部已读
          </Button>
        </View>

        {error ? <Text className="notifications-state is-error">{error}</Text> : null}
        {loading ? <Text className="notifications-state">加载中...</Text> : null}
        {!loading && !error && items.length === 0 ? <Text className="notifications-state">暂无消息</Text> : null}

        <View className="notifications-list">
          {items.map((item) => (
            <View
              key={item.id}
              className={isRead(item) ? "notification-card" : "notification-card is-unread"}
              onClick={() => void openItem(item)}
            >
              <View className="notification-card__top">
                <Text className="notification-card__type">{typeLabel(item)}</Text>
                <Text className="notification-card__time">{displayTime(item)}</Text>
              </View>
              <Text className="notification-card__title">{item.title || "消息通知"}</Text>
              {item.content ? <Text className="notification-card__content">{item.content}</Text> : null}
              <View className="notification-card__footer">
                {!isRead(item) ? <Text className="notification-card__dot">未读</Text> : <Text className="notification-card__read">已读</Text>}
                <Text className="notification-card__action">{item.actionText || "查看详情"}</Text>
              </View>
            </View>
          ))}
        </View>
      </View>
    </View>
  );
}
