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

function statusText(raw?: string, statusTextValue?: string) {
  if (statusTextValue === "已发布") return "已采纳";
  if (statusTextValue) return statusTextValue;
  const status = String(raw || "").toLowerCase();
  if (status === "published" || status === "approved" || status === "adopted") return "已采纳";
  if (status === "rejected" || status === "branch_rejected" || status === "city_rejected") return "已驳回";
  return "审核中";
}

function canResubmit(item: any) {
  return item?.canResubmit === true || item?.can_resubmit === true || ["rejected", "branch_rejected", "city_rejected"].includes(String(item?.status || "").toLowerCase());
}

function reviewReason(item: any) {
  return String(item?.reviewReason || item?.review_reason || "").trim();
}

export default function MySuggestionsPage() {
  useAuthGuard();
  useMemberGuard("我的建言仅面向正式会员开放");
  const router = useRouter();
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const data = await getMySuggestions();
        const rows = Array.isArray(data) ? data : [];
        const highlightId = String(router.params?.highlightId || "").trim();
        if (highlightId) {
          const hitIndex = rows.findIndex((item) => String(item?.id || "") === highlightId);
          if (hitIndex >= 0) {
            const hit = rows[hitIndex];
            setItems([hit, ...rows.filter((_, index) => index !== hitIndex)]);
            setNotice(`已为你定位刚提交的建言：${hit?.title || highlightId}`);
          } else {
            setItems(rows);
            setNotice("暂未定位到刚提交的建言，请刷新后再查看。");
          }
        } else {
          setItems(rows);
          setNotice("");
        }
        setError("");
      } catch (e: any) {
        setError(e?.message || "加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  return (
    <View className="my-suggestions-page">
      <View className="my-suggestions-page__body">
        <View className="my-suggestions-page__action">
          <Button className="my-suggestions-page__button" onClick={() => void Taro.navigateTo({ url: "/pages/suggestion-create/index" })}>
            我要建言
          </Button>
        </View>

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

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

        {!loading && !error && notice ? (
          <View className="my-suggestions-state">
            <Text>{notice}</Text>
          </View>
        ) : null}

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

        <View className="my-suggestions-list">
          {items.map((item) => {
            const reason = reviewReason(item);
            return (
              <View
                key={item.id || item.title}
                className="my-suggestions-card"
                onClick={() => void Taro.navigateTo({ url: `/pages/suggestion-detail/index?id=${item.id}` })}
              >
                <Text className="my-suggestions-card__title">{item.title || "-"}</Text>
                <View className="my-suggestions-card__row">
                  <Text className="my-suggestions-card__date">{item.date || item.created_at || "-"}</Text>
                  <Text className="my-suggestions-card__status">{statusText(item.status, item.status_text)}</Text>
                </View>
                {item.branch_names ? <Text className="my-suggestions-card__branch">{item.branch_names}</Text> : null}
                {reason ? (
                  <View className="my-suggestions-card__reason">
                    <Text>驳回原因：{reason}</Text>
                  </View>
                ) : null}
                {canResubmit(item) ? (
                  <Button
                    className="my-suggestions-card__edit"
                    onClick={(event) => {
                      event.stopPropagation();
                      void Taro.navigateTo({ url: `/pages/suggestion-create/index?id=${item.id}` });
                    }}
                  >
                    修改后重提
                  </Button>
                ) : null}
              </View>
            );
          })}
        </View>
      </View>
    </View>
  );
}
