import { Button, Image, Input, Picker, Text, Textarea, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { createActivity, getActivityDetail, resubmitActivity, updateActivity } from "../../api/events";
import DateTimeField from "../../components/date-time-field";
import { getJoinBranches } from "../../api/member";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { normalizeDisplayDateTime, toIsoFromDisplay } from "../../utils/datetime";
import { firstText, resolveMediaUrl } from "../../utils/media";
import { ensureMemberAccess } from "../../utils/permission";
import { uploadImageToBackend } from "../../utils/upload";
import { useActionDrawer } from "../../components/action-drawer";
import "./index.scss";

const SCOPE_OPTIONS = [
  { label: "仅所属分会会员可报名", value: "branch_members" },
  { label: "仅市会员可报名", value: "city_members" },
  { label: "全体会员可报名", value: "all_members" },
  { label: "所有人可报名", value: "all_people" }
];

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

export default function EventCreatePage() {
  useAuthGuard();
  useMemberGuard("仅会员可发布活动");
  const router = useRouter();
  const editId = Number(router.params?.id || 0);

  const [branches, setBranches] = useState<any[]>([]);
  const [branchIndex, setBranchIndex] = useState(0);
  const [scopeIndex, setScopeIndex] = useState(0);
  const [cover, setCover] = useState<any>(null);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [canEdit, setCanEdit] = useState(true);
  const [reviewReason, setReviewReason] = useState("");
  const { showActionDrawer, actionDrawer } = useActionDrawer();
  const [form, setForm] = useState({
    title: "",
    startsAt: "",
    endsAt: "",
    registerDeadline: "",
    location: "",
    capacity: "",
    description: ""
  });

  const loadPage = async () => {
    try {
      const data = await getJoinBranches();
      const branchRows = Array.isArray(data) ? data : [];
      setBranches(branchRows);
      setBranchIndex(0);
      setCanEdit(true);
      setReviewReason("");
      let nextError = "";

      if (editId > 0) {
        const detail: any = await getActivityDetail(editId);
        const editable = detail?.canResubmit === true || detail?.can_resubmit === true;
        setCanEdit(editable);
        setReviewReason(String(detail?.reviewReason || detail?.review_reason || ""));
        if (!editable) nextError = "当前活动不处于可重新提交状态";

        const ids = branchIdsFrom(detail);
        const hitIndex = branchRows.findIndex((branch) => ids.includes(Number(branch?.id)));
        if (hitIndex >= 0) setBranchIndex(hitIndex);
        const scopeValue = firstText(detail?.participantScope, detail?.participant_scope);
        const scopeHit = SCOPE_OPTIONS.findIndex((item) => item.value === scopeValue);
        if (scopeHit >= 0) setScopeIndex(scopeHit);
        const coverUrl = resolveMediaUrl(firstText(detail?.coverImageUrl, detail?.cover_image_url, detail?.image));
        setCover(coverUrl ? { url: coverUrl } : null);
        setForm({
          title: String(detail?.title || ""),
          startsAt: normalizeDisplayDateTime(firstText(detail?.startsAt, detail?.starts_at)),
          endsAt: normalizeDisplayDateTime(firstText(detail?.endsAt, detail?.ends_at)),
          registerDeadline: normalizeDisplayDateTime(firstText(detail?.registerDeadline, detail?.register_deadline)),
          location: String(detail?.location || ""),
          capacity: String(detail?.capacity ?? detail?.total ?? ""),
          description: String(detail?.description || "")
        });
      }
      setError(nextError);
    } catch (e: any) {
      setError(e?.message || "页面加载失败");
    }
  };

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

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

  const onUploadCover = 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, "activity_cover");
      setCover(uploaded);
      Taro.showToast({ title: "封面上传成功", icon: "none" });
    } catch (e: any) {
      const msg = e?.message || "封面上传失败";
      setError(msg);
      Taro.showToast({ title: msg, icon: "none" });
    }
  };

  const onSubmit = async () => {
    const ok = await ensureMemberAccess("仅会员可发布活动");
    if (!ok || !canSubmit || submitting) return;

    setSubmitting(true);
    setError("");
    try {
      const branch = branches[branchIndex];
      const payload = {
        title: form.title.trim(),
        description: form.description.trim() || undefined,
        location: form.location.trim() || undefined,
        startsAt: toIsoFromDisplay(form.startsAt) || undefined,
        endsAt: toIsoFromDisplay(form.endsAt) || undefined,
        registerDeadline: form.registerDeadline ? toIsoFromDisplay(form.registerDeadline) || undefined : undefined,
        capacity: form.capacity ? Number(form.capacity) : undefined,
        participantScope: SCOPE_OPTIONS[scopeIndex].value,
        coverImageUrl: cover?.url || undefined,
        branchIds: [branch.id]
      };
      if (editId > 0) {
        await updateActivity(editId, payload);
        await resubmitActivity(editId);
      } else {
        await createActivity(payload);
      }
      await showActionDrawer({
        type: "success",
        title: editId > 0 ? "已重新提交" : "成功提交",
        content: editId > 0 ? "修改内容已重新进入审核流程" : "请等待审核",
        confirmText: "查看我发布的活动",
        showCancel: false
      });
      await Taro.redirectTo({ url: "/pages/my-created-activities/index" });
    } catch (e: any) {
      setError(e?.message || "提交失败");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <View className="page-shell event-create-page">
      <View className="page-body event-create-page__body">
        {editId > 0 ? (
          <View className="event-create-error">
            <Text>驳回原因：{reviewReason || "暂无驳回说明"}</Text>
          </View>
        ) : null}

        <View className="card-surface event-create-card">
          <Text className="event-create-section-title">基本信息</Text>

          <View className="event-create-field">
            <Text className="event-create-label">活动标题</Text>
            <Input className="event-create-input" value={form.title} onInput={(e) => setForm((s) => ({ ...s, title: e.detail.value }))} placeholder="请输入活动标题" />
          </View>

          <View className="event-create-field">
            <Text className="event-create-label">活动时间</Text>
            <View className="event-create-picker">
              <DateTimeField value={form.startsAt} onChange={(v) => setForm((s) => ({ ...s, startsAt: v }))} placeholder="开始时间 YYYY-MM-DD HH:mm" />
            </View>
            <View className="event-create-picker event-create-input--sub">
              <DateTimeField value={form.endsAt} onChange={(v) => setForm((s) => ({ ...s, endsAt: v }))} placeholder="结束时间 YYYY-MM-DD HH:mm" />
            </View>
          </View>

          <View className="event-create-field">
            <Text className="event-create-label">报名截止时间</Text>
            <View className="event-create-picker">
              <DateTimeField
                value={form.registerDeadline}
                onChange={(v) => setForm((s) => ({ ...s, registerDeadline: v }))}
                placeholder="YYYY-MM-DD HH:mm（可选）"
              />
            </View>
          </View>

          <View className="event-create-field">
            <Text className="event-create-label">活动地点</Text>
            <Input className="event-create-input" value={form.location} onInput={(e) => setForm((s) => ({ ...s, location: e.detail.value }))} placeholder="请输入活动地点" />
          </View>

          <View className="event-create-grid">
            <View className="event-create-field">
              <Text className="event-create-label">所属分会</Text>
              <Picker mode="selector" range={branches.map((item) => item.name)} value={branchIndex} onChange={(e) => setBranchIndex(Number(e.detail.value))}>
                <View className="event-create-picker">{branches[branchIndex]?.name || "暂无可选分会"}</View>
              </Picker>
            </View>

            <View className="event-create-field">
              <Text className="event-create-label">人数上限</Text>
              <Input className="event-create-input" value={form.capacity} onInput={(e) => setForm((s) => ({ ...s, capacity: e.detail.value }))} type="number" placeholder="可选" />
            </View>
          </View>

          <View className="event-create-field">
            <Text className="event-create-label">参加人员范围</Text>
            <Picker mode="selector" range={SCOPE_OPTIONS.map((item) => item.label)} value={scopeIndex} onChange={(e) => setScopeIndex(Number(e.detail.value))}>
              <View className="event-create-picker">{SCOPE_OPTIONS[scopeIndex].label}</View>
            </Picker>
          </View>
        </View>

        <View className="card-surface event-create-card">
          <Text className="event-create-section-title">活动详情</Text>
          <Textarea className="event-create-textarea" value={form.description} onInput={(e) => setForm((s) => ({ ...s, description: e.detail.value }))} autoHeight placeholder="请输入活动详细介绍..." />
        </View>

        <View className="card-surface event-create-cover">
          <Text className="event-create-section-title">活动封面</Text>
          <View className="event-create-cover__box" onClick={() => void onUploadCover()}>
            {cover?.url ? (
              <Image className="event-create-cover__image" src={cover.url} mode="aspectFill" />
            ) : (
              <View className="event-create-cover__placeholder">
                <Text className="event-create-cover__camera">+</Text>
                <Text className="event-create-cover__placeholder-text">上传封面图片</Text>
              </View>
            )}
          </View>
        </View>

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

        <View className="event-create-submit-bar">
          <Button className="event-create-submit" disabled={!canSubmit || submitting} loading={submitting} onClick={() => void onSubmit()}>
            {editId > 0 ? "修改后重新提交" : "确认发布"}
          </Button>
        </View>
      </View>
      {actionDrawer}
    </View>
  );
}
