import { Button, Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useState } from "react";
import { getMySurveyResponses, getSurveyDetail } from "../../api/survey";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import "./index.scss";

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

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

function formatDateTime(value?: string) {
  if (!value) return "-";
  return String(value).slice(0, 16).replace("T", " ").replaceAll("-", ".");
}

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

  const { params } = useRouter();
  const id = params?.id;
  const [detail, setDetail] = useState<any>(null);
  const [responses, setResponses] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useDidShow(() => {
    if (!id) return;
    void (async () => {
      setLoading(true);
      try {
        const detailData = await getSurveyDetail(id);
        const responseData = await getMySurveyResponses(id).catch(() => []);
        setDetail(detailData || null);
        setResponses(Array.isArray(responseData) ? responseData : []);
        setError("");
      } catch (e: any) {
        setError(e?.message || "调查详情加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  const submitMessage = detail?.submitMessage || detail?.submit_message || "";
  const canSubmit = detail?.canSubmit === true || detail?.can_submit === true;
  const canLoginThenSubmit = submitMessage === "请先登录后提交";
  const actionDisabled = !canSubmit && !canLoginThenSubmit;
  const actionText = canSubmit ? "去问卷页" : canLoginThenSubmit ? "登录后填写" : submitMessage || "当前不可提交";

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

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

        {detail ? (
          <View className="card-surface survey-detail-card">
            {detail.coverImageUrl ? <Image className="survey-detail-card__cover" src={detail.coverImageUrl} mode="aspectFill" /> : null}

            <Text className="survey-detail-card__title">{detail.title || "未命名调查"}</Text>

            <View className="survey-detail-card__status-row">
              <Text className={`survey-detail-card__status ${statusText(detail.status) === "进行中" ? "is-ongoing" : "is-ended"}`}>
                {statusText(detail.status)}
              </Text>
            </View>

            <View className="survey-detail-card__meta">
              <Text className="survey-detail-card__meta-line">
                时间：{formatDate(detail.startsAt || detail.starts_at)} ~ {formatDate(detail.endsAt || detail.ends_at)}
              </Text>
              <Text className="survey-detail-card__meta-line">重复提交：{detail.allowMultipleSubmit || detail.allow_multiple_submit ? "允许" : "不允许"}</Text>
              <Text className="survey-detail-card__meta-line">我的提交次数：{detail.submitCount ?? detail.submit_count ?? 0}</Text>
              <Text className="survey-detail-card__meta-line">
                最近提交时间：{detail.lastSubmittedAt || detail.last_submitted_at ? formatDateTime(detail.lastSubmittedAt || detail.last_submitted_at) : "-"}
              </Text>
              <Text className="survey-detail-card__meta-line">
                提交状态：{submitMessage || "请确认后提交"}
              </Text>
            </View>

            <View className="survey-detail-card__desc">
              <Text>{detail.description || "暂无描述"}</Text>
            </View>
          </View>
        ) : null}

        {detail ? (
          <View className="card-surface survey-detail-responses">
            <Text className="survey-detail-responses__title">历史答卷</Text>
            {responses.length === 0 ? (
              <Text className="survey-detail-responses__empty">暂无答卷记录</Text>
            ) : responses.map((response, index) => (
              <View key={response.id || index} className="survey-detail-response">
                <View className="survey-detail-response__head">
                  <Text className="survey-detail-response__name">第 {responses.length - index} 次提交</Text>
                  <Text className="survey-detail-response__time">{response.submittedAt || response.submitted_at || "-"}</Text>
                </View>
                {(response.answers || []).map((answer, answerIndex) => (
                  <View key={`${response.id || index}-${answer.questionId || answerIndex}`} className="survey-detail-answer">
                    <Text className="survey-detail-answer__question">{answerIndex + 1}. {answer.questionTitle || answer.question_title || "题目"}</Text>
                    <Text className="survey-detail-answer__value">{answer.answerText || answer.answer_text || "-"}</Text>
                  </View>
                ))}
              </View>
            ))}
          </View>
        ) : null}

        <View className="survey-detail-actions">
          <Button
            className="survey-detail-actions__button"
            disabled={actionDisabled}
            onClick={() => void Taro.navigateTo({ url: `/pages/my-survey-answer/index?id=${id}` })}
          >
            {actionText}
          </Button>
        </View>
      </View>
    </View>
  );
}
