import { Button, Input, Picker, Text, Textarea, View } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { submitEvaluationRecord, type EvaluationRecordType } from "../../api/evaluation";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { uploadImageToBackend } from "../../utils/upload";
import "../evaluation/index.scss";
import "./index.scss";

type Field = { key: string; label: string; multiline?: boolean; number?: boolean };

const TYPES: Array<{ label: string; value: EvaluationRecordType; fields: Field[] }> = [
  { label: "教育经历", value: "EDUCATION", fields: [
    { key: "school", label: "学校" },
    { key: "major", label: "专业" },
    { key: "degree", label: "学历/学位" },
    { key: "startDate", label: "开始日期 YYYY-MM-DD" },
    { key: "endDate", label: "结束日期 YYYY-MM-DD" }
  ] },
  { label: "资质证书", value: "QUALIFICATION", fields: [
    { key: "name", label: "证书名称" },
    { key: "level", label: "等级" },
    { key: "issuer", label: "发证机构" },
    { key: "issuedAt", label: "发证日期 YYYY-MM-DD" }
  ] },
  { label: "社会兼职", value: "POSITION", fields: [
    { key: "organizationName", label: "组织名称" },
    { key: "positionName", label: "职务名称" },
    { key: "level", label: "级别" },
    { key: "startDate", label: "开始日期 YYYY-MM-DD" },
    { key: "endDate", label: "结束日期 YYYY-MM-DD" }
  ] },
  { label: "荣获奖项", value: "AWARD", fields: [
    { key: "awardName", label: "奖项名称" },
    { key: "awardLevel", label: "奖项级别" },
    { key: "awardDate", label: "获奖日期 YYYY-MM-DD" },
    { key: "issuer", label: "颁发单位" },
    { key: "tongzhanRelevance", label: "统战相关性说明", multiline: true },
    { key: "description", label: "补充说明", multiline: true }
  ] },
  { label: "建言献策", value: "PROPOSAL", fields: [
    { key: "title", label: "建言标题" },
    { key: "content", label: "主要内容", multiline: true },
    { key: "fieldTags", label: "领域标签（逗号分隔）" },
    { key: "submissionDate", label: "提交日期 YYYY-MM-DD" },
    { key: "adoptionLevel", label: "采纳级别" },
    { key: "adoptionStatus", label: "采纳状态" },
    { key: "description", label: "补充说明", multiline: true }
  ] },
  { label: "社会服务", value: "SERVICE", fields: [
    { key: "serviceProjectId", label: "服务项目ID（可选）", number: true },
    { key: "impactType", label: "影响类型" },
    { key: "mediaLevel", label: "媒体级别" },
    { key: "resourceAmount", label: "资源投入", number: true },
    { key: "professionalRole", label: "专业角色" },
    { key: "description", label: "服务成效说明", multiline: true }
  ] },
  { label: "履职情况", value: "DUTY", fields: [
    { key: "dutyType", label: "履职类型" },
    { key: "period", label: "周期" },
    { key: "attendanceCount", label: "出席次数", number: true },
    { key: "absenceCount", label: "缺席次数", number: true },
    { key: "proposalCount", label: "建言次数", number: true },
    { key: "researchCount", label: "调研次数", number: true },
    { key: "speechCount", label: "发言次数", number: true },
    { key: "politicalIdentity", label: "政治身份" },
    { key: "ideologyGrade", label: "思想表现等级" },
    { key: "ideologyDetail", label: "思想表现说明", multiline: true },
    { key: "description", label: "补充说明", multiline: true }
  ] }
];

function normalizePayload(type: EvaluationRecordType, values: Record<string, string>, proofUrl: string) {
  const payload: any = {};
  Object.entries(values).forEach(([key, value]) => {
    const text = String(value || "").trim();
    if (!text) return;
    if (["attendanceCount", "absenceCount", "proposalCount", "researchCount", "speechCount", "resourceAmount", "serviceProjectId"].includes(key)) {
      payload[key] = Number(text) || undefined;
    } else {
      payload[key] = text;
    }
  });
  if (proofUrl) {
    if (type === "SERVICE" || type === "DUTY") payload.proofUrls = [proofUrl];
    else if (type === "PROPOSAL") payload.adoptionProofUrl = proofUrl;
    else payload.certificateUrl = proofUrl;
  }
  if (type === "POSITION") {
    payload.isPlatform = false;
    payload.isCurrent = !payload.endDate;
  }
  return payload;
}

export default function EvaluationMaterialPage() {
  useAuthGuard();
  useMemberGuard("补充成就材料仅面向正式会员开放");

  const [activeType, setActiveType] = useState<EvaluationRecordType>("EDUCATION");
  const [values, setValues] = useState<Record<string, string>>({});
  const [proofUrl, setProofUrl] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  useLoad((params) => {
    const type = String(params?.type || "").toUpperCase() as EvaluationRecordType;
    if (TYPES.some((item) => item.value === type)) setActiveType(type);
  });

  const active = useMemo(() => TYPES.find((item) => item.value === activeType) || TYPES[0], [activeType]);
  const typeIndex = Math.max(0, TYPES.findIndex((item) => item.value === activeType));

  const updateValue = (key: string, value: string) => setValues((state) => ({ ...state, [key]: value }));

  const uploadProof = async () => {
    try {
      const picked = await Taro.chooseImage({ count: 1, sizeType: ["compressed"], sourceType: ["album", "camera"] });
      const filePath = picked?.tempFilePaths?.[0];
      if (!filePath) return;
      const uploaded = await uploadImageToBackend(filePath, "evaluation_proof");
      const url = String(uploaded?.url || uploaded?.publicUrl || "");
      setProofUrl(url);
      Taro.showToast({ title: "凭证上传成功", icon: "none" });
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "凭证上传失败", icon: "none" });
    }
  };

  const submit = async () => {
    if (submitting) return;
    const payload = normalizePayload(activeType, values, proofUrl);
    if (Object.keys(payload).length === 0) {
      Taro.showToast({ title: "请至少填写一项材料内容", icon: "none" });
      return;
    }
    setSubmitting(true);
    setError("");
    try {
      await submitEvaluationRecord(activeType, payload);
      Taro.showToast({ title: "已提交审核", icon: "none" });
      await Taro.redirectTo({ url: "/pages/evaluation/index" });
    } catch (e: any) {
      setError(e?.message || "提交失败");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <View className="evaluation-page">
      <View className="evaluation-page__body">
        <View className="evaluation-panel material-panel">
          <Text className="evaluation-panel__title">材料类型</Text>
          <Picker
            mode="selector"
            range={TYPES.map((item) => item.label)}
            value={typeIndex}
            onChange={(event) => {
              const next = TYPES[Number(event.detail.value)] || TYPES[0];
              setActiveType(next.value);
              setValues({});
              setProofUrl("");
            }}
          >
            <View className="material-picker">{active.label}</View>
          </Picker>
        </View>

        <View className="evaluation-panel material-panel">
          <Text className="evaluation-panel__title">材料内容</Text>
          {active.fields.map((field) => (
            <View key={field.key} className="material-field">
              {field.multiline ? (
                <Textarea className="material-textarea" value={values[field.key] || ""} onInput={(e) => updateValue(field.key, e.detail.value)} placeholder={field.label} placeholderStyle="color:#9ca3af;" autoHeight />
              ) : (
                <Input className="material-input" value={values[field.key] || ""} onInput={(e) => updateValue(field.key, e.detail.value)} type={field.number ? "number" : "text"} placeholder={field.label} placeholderStyle="color:#9ca3af;" />
              )}
            </View>
          ))}
          <View className="material-proof" onClick={() => void uploadProof()}>
            <Text>{proofUrl ? "凭证已上传，点击可重新上传" : "上传证明材料（可选）"}</Text>
          </View>
        </View>

        {error ? <Text className="evaluation-state is-error">{error}</Text> : null}
        <Button className="material-submit" loading={submitting} disabled={submitting} onClick={() => void submit()}>
          提交材料
        </Button>
      </View>
    </View>
  );
}
