import { Button, Input, Picker, Text, Textarea, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { createSuggestion, getContentDetail, getSuggestionBranches, updateSuggestion } from "../../api/contents";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { ensureMemberAccess } from "../../utils/permission";
import { useActionDrawer } from "../../components/action-drawer";
import "./index.scss";

const DEDUP_TTL_MS = 30 * 1000;
const DEDUP_KEY = "suggestion:last_submit_fingerprint";

function buildFingerprint(title: string, body: string, branchId: number) {
  return `${branchId}::${title.trim()}::${body.trim()}`;
}

function bodyTextFrom(detail: any) {
  const blocks = Array.isArray(detail?.bodyParsed) ? detail.bodyParsed : [];
  const text = blocks
    .filter((block) => String(block?.type || "") === "text")
    .map((block) => String(block?.content || "").trim())
    .filter(Boolean)
    .join("\n");
  return text || String(detail?.content || detail?.body || detail?.summary || "");
}

function branchIdsFrom(detail: any) {
  const raw = detail?.branchIds || detail?.branch_ids;
  if (Array.isArray(raw)) return raw.map((item) => Number(item)).filter(Boolean);
  return [];
}

export default function SuggestionCreatePage() {
  useAuthGuard();
  useMemberGuard("需要加入会员后才能建言");
  const router = useRouter();
  const editId = Number(router.params?.id || 0);
  const [branches, setBranches] = useState<any[]>([]);
  const [branchIndex, setBranchIndex] = useState(0);
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [canEdit, setCanEdit] = useState(true);
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  const loadPage = async () => {
    try {
      const list = await getSuggestionBranches();
      const arr = Array.isArray(list) ? list : [];
      setBranches(arr);
      setBranchIndex(0);
      setCanEdit(true);
      if (arr.length === 0) {
        setError("暂无可提交分会，请先加入分会或联系管理员配置权限");
      } else {
        setError("");
      }

      if (editId) {
        const detail = await getContentDetail(editId);
        setTitle(String(detail?.title || ""));
        setBody(bodyTextFrom(detail));
        const editable = detail?.canResubmit === true || detail?.can_resubmit === true;
        setCanEdit(editable);
        if (!editable) {
          setError("当前建言不处于可重新提交状态");
        }
        const ids = branchIdsFrom(detail);
        const hitIndex = arr.findIndex((branch) => ids.includes(Number(branch?.id)));
        if (hitIndex >= 0) setBranchIndex(hitIndex);
      }
    } catch (e: any) {
      setError(e?.message || "页面加载失败");
      setBranches([]);
    }
  };

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

  const canSubmit = useMemo(() => {
    return !!title.trim() && !!body.trim() && branches.length > 0 && canEdit;
  }, [title, body, branches, canEdit]);

  const onSubmit = async () => {
    const ok = await ensureMemberAccess("需要加入会员后才能建言");
    if (!ok || !canSubmit || submitting) return;

    setSubmitting(true);
    setError("");

    try {
      const branch = branches[branchIndex];
      const branchId = Number(branch?.id || 0);
      if (!branchId) {
        setError("请选择提交分会");
        return;
      }

      const fingerprint = `${editId || "new"}::${buildFingerprint(title, body, branchId)}`;
      const lastRaw = Taro.getStorageSync(DEDUP_KEY);
      if (lastRaw && typeof lastRaw === "object") {
        const last = lastRaw as { fp?: string; at?: number };
        if (last.fp === fingerprint && Date.now() - Number(last.at || 0) < DEDUP_TTL_MS) {
          Taro.showToast({ title: "请勿重复提交", icon: "none" });
          return;
        }
      }

      const payload = {
        type: "suggestion",
        title: title.trim(),
        summary: title.trim(),
        body: body.trim(),
        branchIds: [branchId]
      };

      const created = editId ? await updateSuggestion(editId, payload) : await createSuggestion(payload);

      Taro.setStorageSync(DEDUP_KEY, { fp: fingerprint, at: Date.now() });
      const createdId = Number((created as any)?.contentId || (created as any)?.id || editId || 0);
      await showActionDrawer({
        type: "success",
        title: editId ? "已重新提交" : "成功提交",
        content: "请等待审核",
        confirmText: createdId ? "查看建言详情" : "查看建言列表",
        showCancel: false
      });

      setTitle("");
      setBody("");
      setBranchIndex(0);

      await Taro.redirectTo({ url: createdId ? `/pages/suggestion-detail/index?id=${createdId}` : "/pages/suggestions/index" });
    } catch (e: any) {
      setError(e?.message || "提交失败");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <View className="suggestion-create-page">
      <View className="suggestion-create-page__body">
        <Input className="suggestion-create-input" value={title} onInput={(e) => setTitle(e.detail.value)} placeholder="请填写标题" />
        <Textarea className="suggestion-create-textarea" value={body} onInput={(e) => setBody(e.detail.value)} placeholder="请填写建言内容" autoHeight />

        <View className="suggestion-create-branch">
          <Text className="suggestion-create-branch__label">选择提交分会</Text>
          <Picker mode="selector" range={branches.map((b) => b.name)} value={branchIndex} onChange={(e) => setBranchIndex(Number(e.detail.value))}>
            <View className="suggestion-create-branch__picker">{branches.length > 0 ? branches[branchIndex]?.name : "暂无可提交分会"}</View>
          </Picker>
        </View>

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

        <Button className="suggestion-create-submit" disabled={!canSubmit || submitting} loading={submitting} onClick={() => void onSubmit()}>
          {editId ? "重新提交" : "提交"}
        </Button>
      </View>
      {actionDrawer}
    </View>
  );
}
