import { View, Text } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import AdminGuard from "../../components/AdminGuard";
import { useUserStore } from "../../store/user";
import { getAdminDashboard } from "../../api/admin";
import { isLoggedInAsAdmin } from "../../utils/adminAuth";
import { useActionDrawer } from "../../components/action-drawer";
import "./index.scss";

function roleLabel(roleCode: string) {
  const map: Record<string, string> = {
    CITY_ADMIN: "市管理员",
    BRANCH_ADMIN: "分会管理员",
    PLATFORM_ADMIN: "平台管理员"
  };
  return map[roleCode] || roleCode;
}

function reviewTypeLabel(type?: string) {
  const map: Record<string, string> = {
    content: "内容",
    activity: "活动",
    survey: "问卷",
    service_project: "服务项目",
    mutual_aid: "企业互助",
    performance_record: "履职记录",
    proposal: "建言献策"
  };
  return map[String(type || "")] || type || "审核";
}

function reviewStageLabel(status?: string) {
  if (status === "branch_review" || status === "pending_branch_review") return "待分会初审";
  if (status === "city_review" || status === "pending_city_review") return "待市级复审";
  return status || "待审核";
}

export default function AdminDashboardPage() {
  const adminUser = useUserStore((s) => s.adminUser);
  const clearAdmin = useUserStore((s) => s.clearAdmin);
  const [dashboard, setDashboard] = useState<any>(null);
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  useDidShow(() => {
    if (isLoggedInAsAdmin()) {
      getAdminDashboard().then(setDashboard).catch(() => setDashboard(null));
    }
  });

  const logoutAdmin = async () => {
    const res = await showActionDrawer({
      type: "confirm",
      title: "退出管理员身份",
      content: "确定退出管理员身份？",
      confirmText: "退出",
      cancelText: "取消"
    });
    if (res.confirm) {
      clearAdmin();
      Taro.navigateBack({ delta: 1 }).catch(() => {
        Taro.switchTab({ url: "/pages/profile/index" });
      });
    }
  };

  const pendingBranch = dashboard?.pendingBranchReview || 0;
  const pendingCity = dashboard?.pendingCityReview || 0;
  const totalPending = pendingBranch + pendingCity;

  return (
    <AdminGuard>
      <View className="page-shell admin-dashboard">
        <View className="page-body admin-dashboard__body">
          {/* Header */}
          <View className="admin-dashboard__header">
            <View className="admin-dashboard__header-info">
              <Text className="admin-dashboard__header-name">{adminUser?.name || "管理员"}</Text>
              <Text className="admin-dashboard__header-role">
                {roleLabel(adminUser?.roleCode || "")}
                {adminUser?.branchNames?.length ? ` · ${adminUser.branchNames.join("、")}` : ""}
              </Text>
            </View>
            <View className="admin-dashboard__logout" onClick={logoutAdmin}>
              <Text>退出登录</Text>
            </View>
          </View>

          {/* Stat Cards */}
          <View className="admin-dashboard__stats">
            <View className="admin-stat-card">
              <Text className="admin-stat-card__number">{dashboard?.publishedThisMonth ?? "-"}</Text>
              <Text className="admin-stat-card__label">本月发布</Text>
            </View>
            <View className="admin-stat-card">
              <Text className="admin-stat-card__number">{dashboard?.announcementsActive ?? "-"}</Text>
              <Text className="admin-stat-card__label">活跃公告</Text>
            </View>
          </View>

          {/* Function Entries */}
          <View className="admin-dashboard__grid">
            <View
              className="admin-entry-card"
              onClick={() => Taro.navigateTo({ url: "/pages/admin-activity-checkin/index" })}
            >
              <View className="admin-entry-card__icon-wrap admin-entry-card__icon-wrap--blue">
                <Text className="admin-entry-card__icon admin-entry-card__icon--text">签</Text>
              </View>
              <Text className="admin-entry-card__label">活动签到</Text>
            </View>

            <View
              className="admin-entry-card"
              onClick={() => Taro.navigateTo({ url: "/pages/admin-pending/index" })}
            >
              <View className="admin-entry-card__icon-wrap admin-entry-card__icon-wrap--orange">
                <Text className="admin-entry-card__icon">📋</Text>
              </View>
              <Text className="admin-entry-card__label">待审批</Text>
              {totalPending > 0 ? (
                <View className="admin-entry-card__badge">
                  <Text className="admin-entry-card__badge-text">{totalPending}</Text>
                </View>
              ) : null}
            </View>

            <View
              className="admin-entry-card"
              onClick={() => Taro.navigateTo({ url: "/pages/admin-content-create/index" })}
            >
              <View className="admin-entry-card__icon-wrap admin-entry-card__icon-wrap--blue">
                <Text className="admin-entry-card__icon">📝</Text>
              </View>
              <Text className="admin-entry-card__label">内容发布</Text>
            </View>

            <View
              className="admin-entry-card"
              onClick={() => Taro.navigateTo({ url: "/pages/admin-announcement/index" })}
            >
              <View className="admin-entry-card__icon-wrap admin-entry-card__icon-wrap--green">
                <Text className="admin-entry-card__icon">📢</Text>
              </View>
              <Text className="admin-entry-card__label">公告管理</Text>
            </View>

            <View
              className="admin-entry-card"
              onClick={() => Taro.navigateTo({ url: "/pages/admin-content-list/index" })}
            >
              <View className="admin-entry-card__icon-wrap admin-entry-card__icon-wrap--purple">
                <Text className="admin-entry-card__icon">📄</Text>
              </View>
              <Text className="admin-entry-card__label">我的内容</Text>
            </View>

            <View
              className="admin-entry-card"
              onClick={() => Taro.navigateTo({ url: "/pages/admin-live/index" })}
            >
              <View className="admin-entry-card__icon-wrap admin-entry-card__icon-wrap--teal">
                <Text className="admin-entry-card__icon admin-entry-card__icon--text">AI</Text>
              </View>
              <Text className="admin-entry-card__label">连小新后台</Text>
            </View>

            <View
              className="admin-entry-card"
              onClick={() => Taro.navigateTo({ url: "/pages/admin-knowledge-governance/index" })}
            >
              <View className="admin-entry-card__icon-wrap admin-entry-card__icon-wrap--slate">
                <Text className="admin-entry-card__icon admin-entry-card__icon--knowledge">KG</Text>
              </View>
              <Text className="admin-entry-card__label">知识治理</Text>
            </View>
          </View>

          {/* Change Password */}
          <View
            className="admin-dashboard__action-row"
            onClick={() => Taro.navigateTo({ url: "/pages/admin-change-password/index" })}
          >
            <Text className="admin-dashboard__action-icon">🔑</Text>
            <Text className="admin-dashboard__action-text">修改密码</Text>
            <Text className="admin-dashboard__action-arrow">›</Text>
          </View>

          {/* Recent Activities */}
          {dashboard?.recentActivities?.length ? (
            <View className="admin-dashboard__recent">
              <Text className="admin-dashboard__recent-title">最近审批动态</Text>
              {dashboard.recentActivities.map((item: any, idx: number) => (
                <View key={item.id || idx} className="admin-activity-item">
                  <View className="admin-activity-item__info">
                    <Text className="admin-activity-item__title">{item.title}</Text>
                    <Text className="admin-activity-item__meta">
                      {reviewTypeLabel(item.type)} · {reviewStageLabel(item.status)} · {item.submitterName}
                    </Text>
                  </View>
                  <Text className="admin-activity-item__time">{item.createdAt?.slice(5, 16)}</Text>
                </View>
              ))}
            </View>
          ) : null}
        </View>
        {actionDrawer}
      </View>
    </AdminGuard>
  );
}
