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

function statusText(value?: string) {
  const text = String(value || "");
  if (text === "ongoing" || text === "published") return "进行中";
  if (text === "ended") return "已结束";
  if (text === "进行中" || text === "已结束") return text;
  return "进行中";
}

function formatDate(value?: string) {
  if (!value) return "-";
  return String(value).slice(0, 10).replaceAll("-", ".");
}

export default function MySurveysPage() {
  useAuthGuard();
  useMemberGuard("我的调查记录仅面向正式会员开放");

  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const data = await getMySurveys();
        setItems(Array.isArray(data) ? data : []);
        setError("");
      } catch (e: any) {
        setError(e?.message || "调查记录加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  return (
    <View className="page-shell my-surveys-page">
      <View className="page-body my-surveys-page__body">
        {error ? (
          <View className="my-surveys-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        {loading ? (
          <View className="my-surveys-empty card-surface">
            <Text>加载中...</Text>
          </View>
        ) : null}

        {!loading && items.length === 0 ? (
          <View className="my-surveys-empty card-surface">
            <Text>暂无调查记录</Text>
          </View>
        ) : null}

        <View className="my-surveys-list">
          {items.map((item) => {
            const surveyId = item.id || item.survey_id;
            return (
              <View
                key={surveyId || item.title}
                className="card-surface my-surveys-card"
                onClick={() => void Taro.navigateTo({ url: `/pages/my-survey-detail/index?id=${surveyId}` })}
              >
                <View className="my-surveys-card__cover">
                  {item.image ? (
                    <Image className="my-surveys-card__cover-image" src={item.image} mode="aspectFill" />
                  ) : (
                    <View className="my-surveys-card__cover-empty">
                      <Text>暂无图片</Text>
                    </View>
                  )}
                </View>
                <View className="my-surveys-card__content">
                  <Text className="my-surveys-card__title">{item.title || "未命名调查"}</Text>
                  <Text className="my-surveys-card__meta">
                    {formatDate(item.date)} · {statusText(item.status_text || item.status)}
                  </Text>
                  <Text className="my-surveys-card__extra">
                    提交次数：{item.submit_count ?? 0}
                    {item.last_submitted_at ? ` · 最近提交：${formatDate(item.last_submitted_at)}` : ""}
                  </Text>
                </View>
              </View>
            );
          })}
        </View>
      </View>
    </View>
  );
}
