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

type ContentItem = {
  id: number;
  title: string;
  type: string;
  status: string;
  createdAt: string;
};

const STATUS_TABS = [
  { key: "", label: "全部" },
  { key: "draft", label: "草稿" },
  { key: "pending_branch_review", label: "待初审" },
  { key: "pending_city_review", label: "待终审" },
  { key: "branch_rejected", label: "已驳回" },
  { key: "published", label: "已发布" },
];

const statusTextMap: Record<string, string> = {
  draft: "草稿",
  pending_branch_review: "待分会初审",
  pending_city_review: "待市终审",
  branch_approved: "分会初审通过",
  branch_rejected: "分会初审驳回",
  city_approved: "市终审通过",
  city_rejected: "市终审驳回",
  published: "已发布",
};

export default function AdminContentListPage() {
  const [activeTab, setActiveTab] = useState("");

  const fetcher = useCallback(
    (page: number, pageSize: number) =>
      getAdminContents({ status: activeTab || undefined, page, size: pageSize }).then((res: any) => ({
        items: res.items || res.records || [],
        total: res.total,
      })),
    [activeTab]
  );

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

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

  const canEdit = (status: string) =>
    status === "draft" || status === "branch_rejected" || status === "city_rejected";

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

  return (
    <AdminGuard>
      <View className="page-shell admin-content-list">
        <View className="page-body admin-content-list__body">
          {/* Tabs */}
          <ScrollView scrollX className="admin-content-list__tabs-scroll">
            <View className="admin-content-list__tabs">
              {STATUS_TABS.map((tab) => (
                <View
                  key={tab.key}
                  className={`admin-content-list__tab ${activeTab === tab.key ? "is-active" : ""}`}
                  onClick={() => setActiveTab(tab.key)}
                >
                  <Text>{tab.label}</Text>
                </View>
              ))}
            </View>
          </ScrollView>

          {/* List */}
          <ScrollView
            className="admin-content-list__list"
            scrollY
            refresherEnabled
            refresherTriggered={loading}
            onRefresherRefresh={() => void refresh()}
            onScrollToLower={onScrollToLower}
          >
            {items.length === 0 && !loading ? (
              <View className="admin-content-list__empty">
                <Text>暂无内容</Text>
              </View>
            ) : (
              items.map((item) => (
                <View
                  key={item.id}
                  className="admin-content-card"
                  onClick={() => {
                    if (canEdit(item.status)) {
                      Taro.navigateTo({
                        url: `/pages/admin-content-create/index?id=${item.id}`,
                      });
                    }
                  }}
                >
                  <View className="admin-content-card__top">
                    <Text className="admin-content-card__type">{item.type}</Text>
                    <Text className={`admin-content-card__status status--${item.status}`}>
                      {statusTextMap[item.status] || item.status}
                    </Text>
                  </View>
                  <Text className="admin-content-card__title">{item.title}</Text>
                  <View className="admin-content-card__bottom">
                    <Text className="admin-content-card__time">{item.createdAt?.slice(0, 16)}</Text>
                    {canEdit(item.status) ? (
                      <Text className="admin-content-card__action">
                        {item.status === "draft" ? "编辑" : "编辑重提"}
                      </Text>
                    ) : null}
                  </View>
                </View>
              ))
            )}
          </ScrollView>
        </View>
      </View>
    </AdminGuard>
  );
}
