import { Button, Input, Picker, Text, Textarea, View } from "@tarojs/components";
import Taro, { useDidShow, useLoad } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { createMutualAidPost, getMutualAidDetail, resubmitMutualAidPost, updateMutualAidPost } from "../../api/mutual-aid";
import { getSuggestionBranches } 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";

export default function DemandCreatePage() {
  useAuthGuard();
  useMemberGuard("仅会员可发布需求");
  const [branches, setBranches] = useState<any[]>([]);
  const [branchIndex, setBranchIndex] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [editId, setEditId] = useState<number>(0);
  const [reviewReason, setReviewReason] = useState("");
  const { showActionDrawer, actionDrawer } = useActionDrawer();
  const [form, setForm] = useState({
    title: "",
    tagsText: "",
    contactPhone: "",
    contactWechat: "",
    publisherTitle: "",
    description: ""
  });

  useLoad((params) => {
    const id = Number(params?.id || 0);
    setEditId(Number.isFinite(id) ? id : 0);
  });

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

        if (editId > 0) {
          const detail = await getMutualAidDetail(editId);
          const idx = arr.findIndex((x) => Number(x?.id) === Number((detail as any)?.branch_id ?? (detail as any)?.branchId));
          setBranchIndex(idx >= 0 ? idx : 0);
          setReviewReason(String((detail as any)?.review_reason || (detail as any)?.reviewReason || ""));
          setForm({
            title: String((detail as any)?.title || ""),
            tagsText: String((detail as any)?.tags_text || (detail as any)?.tagsText || ""),
            contactPhone: String((detail as any)?.contact_phone || (detail as any)?.contactPhone || ""),
            contactWechat: String((detail as any)?.contact_wechat || (detail as any)?.contactWechat || ""),
            publisherTitle: String((detail as any)?.publisher_title || (detail as any)?.publisherTitle || ""),
            description: String((detail as any)?.description || (detail as any)?.content || "")
          });
        }
        setError("");
      } catch (e: any) {
        setError(e?.message || "加载失败");
      }
    })();
  });

  const canSubmit = useMemo(() => !!form.title.trim() && branches.length > 0, [form.title, branches.length]);

  const onSubmit = async () => {
    const ok = await ensureMemberAccess("仅会员可发布需求");
    if (!ok || !canSubmit || submitting) return;
    setSubmitting(true);
    setError("");
    try {
      const branchId = Number(branches[branchIndex]?.id || 0);
      if (!branchId) {
        setError("请选择所属分会");
        return;
      }
      const payload = {
        postType: "need" as const,
        title: form.title.trim(),
        description: form.description.trim() || undefined,
        branchId,
        contactPhone: form.contactPhone.trim() || undefined,
        contactWechat: form.contactWechat.trim() || undefined,
        tagsText: form.tagsText.trim() || undefined,
        publisherTitle: form.publisherTitle.trim() || undefined
      };

      if (editId > 0) {
        await updateMutualAidPost(editId, payload);
        await resubmitMutualAidPost(editId);
        await showActionDrawer({
          type: "success",
          title: "成功提交",
          content: "已重新提交，请等待审核",
          confirmText: "查看我发布的需求",
          showCancel: false
        });
      } else {
        await createMutualAidPost(payload);
        await showActionDrawer({
          type: "success",
          title: "发布成功",
          content: "请等待审核",
          confirmText: "查看我发布的需求",
          showCancel: false
        });
      }

      await Taro.redirectTo({ url: "/pages/my-mutual-aid-needs/index" });
    } catch (e: any) {
      setError(e?.message || "提交失败");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <View className="mutual-aid-create-page">
      <View className="mutual-aid-create-page__body">
        {editId > 0 ? (
          <View className="mutual-aid-create-error" style={{ marginBottom: "12rpx" }}>
            <Text>驳回原因：{reviewReason || "暂无驳回说明"}</Text>
          </View>
        ) : null}

        <Input className="mutual-aid-create-input" value={form.title} onInput={(e) => setForm((s) => ({ ...s, title: e.detail.value }))} placeholder="请填写标题" />

        <Input
          className="mutual-aid-create-input"
          value={form.tagsText}
          onInput={(e) => setForm((s) => ({ ...s, tagsText: e.detail.value }))}
          placeholder="需求类型（多个用逗号分隔）"
        />
        <Input
          className="mutual-aid-create-input"
          value={form.publisherTitle}
          onInput={(e) => setForm((s) => ({ ...s, publisherTitle: e.detail.value }))}
          placeholder="发布人头衔（选填）"
        />
        <Input
          className="mutual-aid-create-input"
          value={form.contactPhone}
          onInput={(e) => setForm((s) => ({ ...s, contactPhone: e.detail.value }))}
          placeholder="联系电话（选填）"
        />
        <Input
          className="mutual-aid-create-input"
          value={form.contactWechat}
          onInput={(e) => setForm((s) => ({ ...s, contactWechat: e.detail.value }))}
          placeholder="微信号（选填）"
        />
        <Picker mode="selector" range={branches.map((b) => b.name)} value={branchIndex} onChange={(e) => setBranchIndex(Number(e.detail.value))}>
          <View className="mutual-aid-create-picker">{branches.length ? branches[branchIndex]?.name : "暂无可提交分会"}</View>
        </Picker>
        <Textarea
          className="mutual-aid-create-textarea"
          value={form.description}
          onInput={(e) => setForm((s) => ({ ...s, description: e.detail.value }))}
          autoHeight
          placeholder="请填写详细内容"
        />

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

        <Button className="mutual-aid-create-submit" disabled={!canSubmit || submitting} loading={submitting} onClick={() => void onSubmit()}>
          {editId > 0 ? "修改后提交" : "立即发布"}
        </Button>
      </View>
      {actionDrawer}
    </View>
  );
}
