import { View, Text, ScrollView } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useCallback, useEffect, useState } from "react";
import AdminGuard from "../../components/AdminGuard";
import { useUserStore } from "../../store/user";
import { getPendingReviews } from "../../api/admin";
import { useInfiniteList } from "../../hooks/useInfiniteList";
import "./index.scss";

type PendingItem = {
  id: number;
  title: string;
  type: string;
  status: string;
  stage?: string;
  reviewStage: string;
  submitterName: string;
  branchName: string;
  createdAt: string;
};

function defaultStage(roleCode?: string) {
  if (roleCode === "PLATFORM_ADMIN") return "";
  if (roleCode === "BRANCH_ADMIN") return "branch_review";
  return "city_review";
}

export default function AdminPendingPage() {
  const adminUser = useUserStore((s) => s.adminUser);
  const [stage, setStage] = useState<string>("");

  const fetcher = useCallback(
    (page: number, pageSize: number) => {
      if (!adminUser?.roleCode) return Promise.resolve({ items: [], total: 0 });
      return getPendingReviews({ stage: stage || undefined, page, size: pageSize }).then((res: any) => ({
        items: res.items || [],
        total: res.total,
      }));
    },
    [adminUser?.roleCode, stage]
  );

  const { items, loading, loadingMore, hasMore, refresh, loadMore } = useInfiniteList<PendingItem>({
    fetcher,
    pageSize: 20,
  });

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

  useEffect(() => {
    if (!adminUser?.roleCode) return;
    const nextStage = defaultStage(adminUser?.roleCode);
    const allowedStages = adminUser?.roleCode === "PLATFORM_ADMIN"
      ? ["", "branch_review", "city_review"]
      : adminUser?.roleCode === "BRANCH_ADMIN"
        ? ["branch_review"]
        : ["city_review"];
    setStage((current) => allowedStages.includes(current) ? current : nextStage);
  }, [adminUser?.roleCode]);

  useEffect(() => {
    if (!adminUser?.roleCode) return;
    void refresh();
  }, [adminUser?.roleCode, stage, refresh]);

  const stageTabs = adminUser?.roleCode === "PLATFORM_ADMIN"
    ? [
        { key: "", label: "全部" },
        { key: "branch_review", label: "待分会初审" },
        { key: "city_review", label: "待市级复审" },
      ]
    : adminUser?.roleCode === "BRANCH_ADMIN"
      ? [{ key: "branch_review", label: "待分会初审" }]
      : [{ key: "city_review", label: "待市级复审" }];

  const onScrollToLower = () => {
    if (hasMore && !loadingMore) void loadMore();
  };

  return (
    <AdminGuard>
      <View className="page-shell admin-pending">
        <View className="page-body admin-pending__body">
          <View className="admin-pending__tabs">
            {stageTabs.map((tab) => (
              <View
                key={tab.key}
                className={`admin-pending__tab ${stage === tab.key ? "is-active" : ""}`}
                onClick={() => setStage(tab.key)}
              >
                <Text>{tab.label}</Text>
              </View>
            ))}
          </View>

          <ScrollView
            className="admin-pending__list"
            scrollY
            refresherEnabled
            refresherTriggered={loading}
            onRefresherRefresh={() => void refresh()}
            onScrollToLower={onScrollToLower}
          >
            {items.length === 0 && !loading ? (
              <View className="admin-pending__empty">
                <Text>暂无待审批内容</Text>
              </View>
            ) : (
              items.map((item) => (
                <View
                  key={item.id}
                  className="admin-pending-card"
                  onClick={() =>
                    Taro.navigateTo({
                      url: `/pages/admin-review-detail/index?id=${item.id}`,
                    })
                  }
                >
                  <View className="admin-pending-card__top">
                    <Text className="admin-pending-card__type">{item.type}</Text>
                    <Text className="admin-pending-card__stage">{item.stage || item.reviewStage || item.status}</Text>
                  </View>
                  <Text className="admin-pending-card__title">{item.title}</Text>
                  <View className="admin-pending-card__bottom">
                    <Text className="admin-pending-card__meta">
                      {item.submitterName || "-"} · {item.branchName || "-"}
                    </Text>
                    <Text className="admin-pending-card__time">{item.createdAt?.slice(5, 16)}</Text>
                  </View>
                </View>
              ))
            )}
            {loadingMore ? (
              <View className="admin-pending__loading-more">
                <Text>加载中...</Text>
              </View>
            ) : null}
          </ScrollView>
        </View>
      </View>
    </AdminGuard>
  );
}
