import { Button, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getContents } from "../../api/contents";
import { getMySuggestions } from "../../api/me";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import "./index.scss";

type SuggestionItem = {
  id: number;
  title?: string;
  author?: string;
  date?: string;
  created_at?: string;
  createdAt?: string;
  published_at?: string;
  publishedAt?: string;
  status?: string;
  status_text?: string;
  statusText?: string;
};

const TABS = ["全部", "已采纳", "审核中"] as const;
type TabType = (typeof TABS)[number];

function normalizeStatus(item: SuggestionItem) {
  const text = String(item?.statusText || item?.status_text || "").trim();
  if (text === "已发布") return "已采纳";
  if (text) return text;
  const s = String(item?.status || "").toLowerCase();
  if (s === "published" || s === "approved" || s === "adopted") return "已采纳";
  if (s === "rejected" || s === "branch_rejected" || s === "city_rejected") return "已驳回";
  return "审核中";
}

function statusClass(status: string) {
  if (status === "已采纳") return "is-adopted";
  if (status === "已驳回") return "is-rejected";
  return "is-pending";
}

export default function SuggestionsPage() {
  useAuthGuard();
  const [activeTab, setActiveTab] = useState<TabType>("全部");
  const [publicItems, setPublicItems] = useState<SuggestionItem[]>([]);
  const [myItems, setMyItems] = useState<SuggestionItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const loadData = async () => {
    setLoading(true);
    try {
      const pub = await getContents({ type: "suggestion", page: 1, pageSize: 50 });
      const mine = await getMySuggestions().catch(() => []);
      setPublicItems(Array.isArray(pub) ? pub : []);
      setMyItems(Array.isArray(mine) ? mine : []);
      setError("");
    } catch (e: any) {
      setError(e?.message || "加载失败");
      setPublicItems([]);
      setMyItems([]);
    } finally {
      setLoading(false);
    }
  };

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

  const merged = useMemo(() => {
    const map = new Map<number, SuggestionItem>();
    [...myItems, ...publicItems].forEach((item) => {
      if (item?.id) map.set(item.id, item);
    });
    return Array.from(map.values()).sort((a, b) =>
      String(b.createdAt || b.created_at || b.publishedAt || b.published_at || "").localeCompare(
        String(a.createdAt || a.created_at || a.publishedAt || a.published_at || "")
      )
    );
  }, [myItems, publicItems]);

  const myIds = useMemo(() => new Set(myItems.map((item) => Number(item.id)).filter(Boolean)), [myItems]);

  const items = useMemo(() => {
    if (activeTab === "全部") return merged;
    if (activeTab === "已采纳") return merged.filter((it) => normalizeStatus(it) === "已采纳");
    return merged.filter((it) => normalizeStatus(it) !== "已采纳");
  }, [activeTab, merged]);

  const onCardClick = (item: SuggestionItem) => {
    const status = normalizeStatus(item);
    if (status === "审核中" && !myIds.has(Number(item.id))) {
      void Taro.showToast({ title: "正在审核", icon: "none" });
      return;
    }
    void Taro.navigateTo({ url: `/pages/suggestion-detail/index?id=${item.id}` });
  };

  return (
    <View className="suggestions-page">
      <View className="suggestions-page__body">
        <View className="suggestions-tabs">
          {TABS.map((tab) => (
            <View key={tab} className={`suggestions-tab ${activeTab === tab ? "is-active" : ""}`} onClick={() => setActiveTab(tab)}>
              <Text>{tab}</Text>
            </View>
          ))}
        </View>

        {error ? (
          <View className="suggestions-state is-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        {loading ? (
          <View className="suggestions-state">
            <Text>加载中...</Text>
          </View>
        ) : null}

        {!loading && !error && items.length === 0 ? (
          <View className="suggestions-state">
            <Text>暂无建言</Text>
          </View>
        ) : null}

        <View className="suggestions-list">
          {items.map((item) => (
            <View
              key={item.id}
              className="suggestions-card"
              onClick={() => onCardClick(item)}
            >
              <View className="suggestions-card__content">
                <View className="suggestions-card__main">
                  <View className="suggestions-card__icon">
                    <Text>建言</Text>
                    <Text>献策</Text>
                  </View>
                  <Text className="suggestions-card__title">{item.title || "-"}</Text>
                  <Text className={`suggestions-card__status ${statusClass(normalizeStatus(item))}`}>
                    {normalizeStatus(item)}
                  </Text>
                </View>
                <View className="suggestions-card__row">
                  <Text className="suggestions-card__author">建言人：{item.author || "匿名"}</Text>
                  <Text className="suggestions-card__date">
                    {String(item.date || item.publishedAt || item.published_at || item.createdAt || item.created_at || "-").slice(0, 10).replaceAll("-", ".")}
                  </Text>
                </View>
              </View>
            </View>
          ))}
        </View>

        <View className="suggestions-create">
          <Button className="suggestions-create__button" onClick={() => void Taro.navigateTo({ url: "/pages/suggestion-create/index" })}>
            <Text className="suggestions-create__button-icon">✎</Text>
            <Text>我要建言</Text>
          </Button>
        </View>
      </View>
    </View>
  );
}
