import { Button, Checkbox, CheckboxGroup, Input, Radio, RadioGroup, Text, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getSurveyDetail, getSurveyQuestions, submitSurveyAnswers } from "../../api/survey";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { ensureMemberAccess } from "../../utils/permission";
import { useActionDrawer } from "../../components/action-drawer";
import "./index.scss";

function normalizeType(type?: string) {
  if (type === "single_choice") return "single";
  if (type === "multiple_choice") return "multiple";
  if (type === "text" || type === "text_input") return "text";
  return type || "single";
}

function friendlyError(message?: string) {
  const text = String(message || "");
  if (text.includes("This survey only allows one submission")) return "该问卷仅允许提交一次，您已提交过";
  if (text.includes("Survey is not open for submission")) return "该问卷当前不可提交";
  if (text.includes("Member required")) return "仅会员可提交问卷";
  if (text.includes("仅允许提交一次")) return "该问卷仅允许提交一次，您已提交过";
  if (text.includes("尚未开始")) return "问卷尚未开始";
  if (text.includes("截止")) return "问卷已截止";
  if (text.includes("仅正式会员")) return "仅会员可提交问卷";
  return text || "提交失败";
}

export default function MySurveyAnswerPage() {
  useAuthGuard();
  useMemberGuard("仅正式会员可填写问卷");

  const { params } = useRouter();
  const surveyId = params?.id;
  const [detail, setDetail] = useState<any>(null);
  const [questions, setQuestions] = useState<any[]>([]);
  const [answers, setAnswers] = useState<Record<string, any>>({});
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  useDidShow(() => {
    if (!surveyId) return;
    void (async () => {
      setLoading(true);
      try {
        const detailData = await getSurveyDetail(surveyId);
        setDetail(detailData || null);
        if (detailData?.canSubmit !== true && detailData?.can_submit !== true) {
          setQuestions([]);
          setCurrentStep(0);
          setError(detailData?.submitMessage || detailData?.submit_message || "当前问卷不可提交");
          return;
        }
        const data = await getSurveyQuestions(surveyId);
        setQuestions(Array.isArray(data) ? data : []);
        setCurrentStep(0);
        setError("");
      } catch (e: any) {
        setError(friendlyError(e?.message));
      } finally {
        setLoading(false);
      }
    })();
  });

  const currentQuestion = questions[currentStep];
  const progress = questions.length > 0 ? Math.round(((currentStep + 1) / questions.length) * 100) : 0;

  const isCurrentValid = useMemo(() => {
    if (!currentQuestion) return false;
    if (!currentQuestion.required) return true;
    const questionType = normalizeType(currentQuestion.question_type);
    const value = answers[currentQuestion.id];
    if (questionType === "multiple") return Array.isArray(value) && value.length > 0;
    if (questionType === "text") return String(value || "").trim().length > 0;
    return value !== undefined && value !== null && String(value) !== "";
  }, [currentQuestion, answers]);

  const canSubmitAll = useMemo(() => {
    return questions.every((question) => {
      if (!question.required) return true;
      const questionType = normalizeType(question.question_type);
      const value = answers[question.id];
      if (questionType === "multiple") return Array.isArray(value) && value.length > 0;
      if (questionType === "text") return String(value || "").trim().length > 0;
      return value !== undefined && value !== null && String(value) !== "";
    });
  }, [questions, answers]);

  const onSubmit = async () => {
    if (!surveyId || submitting) return;
    const ok = await ensureMemberAccess("仅会员可提交问卷");
    if (!ok) return;
    if (detail?.canSubmit !== true && detail?.can_submit !== true) {
      setError(detail?.submitMessage || detail?.submit_message || "当前问卷不可提交");
      return;
    }

    const payload: Array<Record<string, any>> = [];
    questions.forEach((question) => {
      const questionType = normalizeType(question.question_type);
      const value = answers[question.id];
      if (value === undefined || value === null || value === "") return;

      if (questionType === "multiple") {
        const list = Array.isArray(value) ? value : [];
        list.forEach((optionId) => payload.push({ questionId: question.id, optionId: Number(optionId) }));
      } else if (questionType === "single") {
        payload.push({ questionId: question.id, optionId: Number(value) });
      } else {
        payload.push({ questionId: question.id, textAnswer: String(value).trim() });
      }
    });

    setSubmitting(true);
    try {
      await submitSurveyAnswers(surveyId, payload);
      await showActionDrawer({
        type: "success",
        title: "提交成功",
        content: "感谢你的参与",
        confirmText: "返回",
        showCancel: false
      });
      await Taro.navigateBack();
    } catch (e: any) {
      setError(friendlyError(e?.message));
    } finally {
      setSubmitting(false);
    }
  };

  const goNext = () => {
    if (currentStep < questions.length - 1) setCurrentStep((value) => value + 1);
  };

  const goPrev = () => {
    if (currentStep > 0) setCurrentStep((value) => value - 1);
  };

  const renderQuestionType = (type?: string) => {
    const questionType = normalizeType(type);
    if (questionType === "single") return "单选题";
    if (questionType === "multiple") return "多选题";
    return "问答题";
  };

  return (
    <View className="page-shell survey-answer-page">
      <View className="page-body survey-answer-page__body">
        <View className="card-surface survey-answer-progress">
          <View className="survey-answer-progress__head">
            <Text className="survey-answer-progress__label">答题进度</Text>
            <Text className="survey-answer-progress__count">{questions.length === 0 ? "0/0" : `${currentStep + 1}/${questions.length}`}</Text>
          </View>
          <View className="survey-answer-progress__bar">
            <View className="survey-answer-progress__inner" style={{ width: `${progress}%` }} />
          </View>
        </View>

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

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

        {!loading && !currentQuestion && error ? (
          <View className="card-surface survey-answer-empty">
            <Text>{error}</Text>
          </View>
        ) : null}

        {currentQuestion ? (
          <View className="card-surface survey-answer-card">
            <View className="survey-answer-card__head">
              <Text className="survey-answer-card__type">{renderQuestionType(currentQuestion.question_type)}</Text>
              <Text className="survey-answer-card__title">
                {currentQuestion.title}
                {currentQuestion.required ? " *" : ""}
              </Text>
            </View>

            <View className="survey-answer-card__body">
              {normalizeType(currentQuestion.question_type) === "single" ? (
                <RadioGroup className="survey-answer-options" onChange={(e) => setAnswers((prev) => ({ ...prev, [currentQuestion.id]: e.detail.value }))}>
                  {(currentQuestion.options || []).map((option: any) => {
                    const selected = String(answers[currentQuestion.id] || "") === String(option.id);
                    return (
                      <View key={option.id} className={`survey-answer-option ${selected ? "is-selected" : ""}`}>
                        <LabelLine>
                          <View className="survey-answer-option__label-wrap">
                            <Text className={`survey-answer-option__text ${selected ? "is-selected" : ""}`}>{option.label}</Text>
                          </View>
                          <Radio value={String(option.id)} checked={selected} />
                        </LabelLine>
                      </View>
                    );
                  })}
                </RadioGroup>
              ) : null}

              {normalizeType(currentQuestion.question_type) === "multiple" ? (
                <CheckboxGroup className="survey-answer-options" onChange={(e) => setAnswers((prev) => ({ ...prev, [currentQuestion.id]: e.detail.value || [] }))}>
                  {(currentQuestion.options || []).map((option: any) => {
                    const selected = Array.isArray(answers[currentQuestion.id]) && answers[currentQuestion.id].includes(String(option.id));
                    return (
                      <View key={option.id} className={`survey-answer-option ${selected ? "is-selected" : ""}`}>
                        <LabelLine>
                          <View className="survey-answer-option__label-wrap">
                            <Text className={`survey-answer-option__text ${selected ? "is-selected" : ""}`}>{option.label}</Text>
                          </View>
                          <Checkbox value={String(option.id)} checked={selected} />
                        </LabelLine>
                      </View>
                    );
                  })}
                </CheckboxGroup>
              ) : null}

              {normalizeType(currentQuestion.question_type) === "text" ? (
                <Input
                  className="survey-answer-input"
                  value={String(answers[currentQuestion.id] || "")}
                  onInput={(e) => setAnswers((prev) => ({ ...prev, [currentQuestion.id]: e.detail.value }))}
                  placeholder="请输入你的答案"
                />
              ) : null}
            </View>
          </View>
        ) : null}

        <View className="survey-answer-actions">
          {currentStep > 0 ? (
            <Button className="survey-answer-actions__secondary" onClick={() => goPrev()}>
              上一题
            </Button>
          ) : null}

          {currentStep < questions.length - 1 ? (
            <Button className="survey-answer-actions__primary" disabled={!isCurrentValid} onClick={() => goNext()}>
              下一题
            </Button>
          ) : (
            <Button className="survey-answer-actions__primary" disabled={!canSubmitAll} loading={submitting} onClick={() => void onSubmit()}>
              提交问卷
            </Button>
          )}
        </View>
      </View>
      {actionDrawer}
    </View>
  );
}

function LabelLine({ children }: { children: any }) {
  return <View className="survey-answer-option__row">{children}</View>;
}
