import { Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getSurveys } from "../../api/survey";
import { getMySurveys } from "../../api/me";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { firstText, resolveMediaUrl } from "../../utils/media";
import "./index.scss";

const TABS = ["全部", "进行中", "未开始", "往期调查"];

type SurveyItem = {
  id: number;
  title?: string;
  description?: string;
  status?: string;
  coverImageUrl?: string;
  deadline?: string;
  endsAt?: string;
  hasSubmitted?: boolean;
};

function normalizeSurvey(item: any): SurveyItem {
  const deadline = item?.deadline || item?.endsAt || item?.ends_at || "";
  return {
    id: Number(item?.id),
    title: item?.title || "",
    description: item?.description || "",
    status: item?.status || "",
    coverImageUrl: resolveMediaUrl(firstText(item?.coverImageUrl, item?.cover_image_url, item?.imageUrl, item?.image_url, item?.image)),
    deadline,
    endsAt: item?.endsAt || item?.ends_at || deadline,
    hasSubmitted: item?.hasSubmitted === true || item?.has_submitted === true || Number(item?.submitCount || item?.submit_count || 0) > 0
  };
}

function statusText(status?: string) {
  if (status === "not_started") return "未开始";
  if (status === "ended") return "已结束";
  return "进行中";
}

function isOngoing(status?: string) {
  return !["ended", "closed", "archived", "not_started"].includes(String(status || "").toLowerCase());
}

function endDateText(value?: string) {
  if (!value) return "截止日期待定";
  return `截止日期：${String(value).slice(0, 10).replaceAll("-", ".")}`;
}

function daysLeft(deadline?: string) {
  if (!deadline) return null;
  const time = new Date(deadline).getTime();
  if (Number.isNaN(time)) return null;
  return Math.ceil((time - Date.now()) / 86400000);
}

function isSurveyClosed(item: SurveyItem) {
  const status = String(item.status || "").toLowerCase();
  const left = daysLeft(item.deadline || item.endsAt);
  return ["closed", "ended", "archived"].includes(status) || (left !== null && left < 0);
}

export default function SurveyPage() {
  useMemberGuard("调查问卷仅面向正式会员开放");

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [activeTab, setActiveTab] = useState("全部");
  const [items, setItems] = useState<SurveyItem[]>([]);
  const [mySurveyIds, setMySurveyIds] = useState<Set<string>>(new Set());

  const load = async () => {
    setLoading(true);
    try {
      const [data, mySurveys] = await Promise.all([
        getSurveys(),
        getMySurveys().catch(() => [])
      ]);
      setItems((Array.isArray(data) ? data : []).map(normalizeSurvey));
      setMySurveyIds(new Set((Array.isArray(mySurveys) ? mySurveys : []).map((survey: any) => String(survey?.id))));
      setError("");
    } catch (e: any) {
      setError(e?.message || "调查问卷加载失败");
    } finally {
      setLoading(false);
    }
  };

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

  const filtered = useMemo(() => {
    if (activeTab === "全部") return items;
    if (activeTab === "进行中") return items.filter((item) => !isSurveyClosed(item) && item.status !== "not_started");
    if (activeTab === "未开始") return items.filter((item) => item.status === "not_started");
    return items.filter(isSurveyClosed);
  }, [activeTab, items]);

  const openDetail = async (id: number) => {
    await Taro.navigateTo({ url: `/pages/my-survey-detail/index?id=${id}` });
  };

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

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

        <View className="survey-list">
          {filtered.map((item) => {
            const closed = isSurveyClosed(item);
            const participated = item.hasSubmitted || mySurveyIds.has(String(item.id));
            const left = daysLeft(item.deadline || item.endsAt);
            const actionText = participated || closed ? "查看结果" : "参与问卷";
            return (
              <View key={item.id} className={participated ? "card-surface survey-card is-participated" : "card-surface survey-card"} onClick={() => void openDetail(item.id)}>
                <View className="survey-card__cover-wrap">
                  {item.coverImageUrl ? (
                    <Image className="survey-card__cover" src={item.coverImageUrl} mode="aspectFill" />
                  ) : (
                    <View className="survey-card__cover survey-card__cover--empty">
                      <Text>暂无图片</Text>
                    </View>
                  )}
                  <View className={`survey-card__status ${!closed && isOngoing(item.status) ? "is-ongoing" : "is-ended"}`}>
                    <Text>{closed ? "已截止" : statusText(item.status)}</Text>
                  </View>
                </View>
                <View className="survey-card__bottom">
                  <View className="survey-card__info">
                    <Text className="survey-card__title">{item.title || "未命名问卷"}</Text>
                    <Text className="survey-card__desc">{item.description || "暂无问卷说明"}</Text>
                    <Text className="survey-card__date">{endDateText(item.deadline || item.endsAt)}</Text>
                    <View className="survey-card__action-row">
                      <Text className="survey-card__action">{actionText}</Text>
                      {participated ? <Text className="survey-card__mark done">已完成</Text> : null}
                      {!participated && closed ? <Text className="survey-card__mark">已截止</Text> : null}
                      {!participated && !closed && left !== null && left >= 0 ? <Text className="survey-card__mark warning">剩余{left}天</Text> : null}
                    </View>
                  </View>
                  <View className="survey-card__arrow">
                    <Text>&gt;</Text>
                  </View>
                </View>
              </View>
            );
          })}

          {!loading && filtered.length === 0 ? (
            <View className="card-surface survey-empty">
              <Text>暂无相关调查问卷</Text>
            </View>
          ) : null}
        </View>
      </View>
    </View>
  );
}
