import { Button, Image, Input, Picker, Text, Textarea, View } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getJoinBranches } from "../../api/member";
import { createServiceProject, getServiceProjectDetail, getServiceTeams, resubmitServiceProject, updateServiceProject } from "../../api/services";
import DateTimeField from "../../components/date-time-field";
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";

export default function ServiceCreatePage() {
  useAuthGuard();
  useMemberGuard("仅会员可创建服务项目");

  const [teams, setTeams] = useState<any[]>([]);
  const [teamIndex, setTeamIndex] = useState(0);
  const [cover, setCover] = useState<any>(null);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [editId, setEditId] = useState(0);
  const [reviewReason, setReviewReason] = useState("");
  const { showActionDrawer, actionDrawer } = useActionDrawer();
  const [form, setForm] = useState({
    title: "",
    startsAt: "",
    endsAt: "",
    location: "",
    memberCount: "",
    serviceTarget: "",
    description: ""
  });

  const loadTeams = async (currentEditId = editId) => {
    try {
      const [teamData, branchData] = await Promise.all([getServiceTeams(), getJoinBranches()]);
      const fromTeams = (Array.isArray(teamData) ? teamData : []).map((item: any) => ({
        ...item,
        __source: "service_team"
      }));
      const fromBranches = (Array.isArray(branchData) ? branchData : []).map((item: any) => ({
        ...item,
        __source: "branch"
      }));
      const mergedMap = new Map<number, any>();
      [...fromTeams, ...fromBranches].forEach((item) => {
        const id = Number(item?.id);
        if (!id || mergedMap.has(id)) return;
        mergedMap.set(id, item);
      });
      const merged = Array.from(mergedMap.values());
      setTeams(merged);
      setTeamIndex(0);
      if (currentEditId > 0) {
        const detail: any = await getServiceProjectDetail(currentEditId);
        const branchId = Number(detail?.branchId ?? detail?.branch_id ?? 0);
        const idx = merged.findIndex((item) => Number(item?.id) === branchId);
        setTeamIndex(idx >= 0 ? idx : 0);
        const coverImageUrl = resolveMediaUrl(firstText(detail?.coverImageUrl, detail?.cover_image_url, detail?.imageUrl, detail?.image_url, detail?.image));
        setCover(coverImageUrl ? { url: coverImageUrl } : null);
        setReviewReason(String(detail?.review_reason || detail?.reviewReason || ""));
        setForm({
          title: String(detail?.title || ""),
          startsAt: normalizeDisplayDateTime(firstText(detail?.startsAt, detail?.starts_at)),
          endsAt: normalizeDisplayDateTime(firstText(detail?.endsAt, detail?.ends_at)),
          location: String(detail?.location || ""),
          memberCount: String(detail?.memberCount ?? detail?.member_count ?? ""),
          serviceTarget: String(detail?.serviceTarget || detail?.service_target || ""),
          description: String(detail?.description || "")
        });
      }
      setError("");
    } catch (e: any) {
      setError(e?.message || "服务项目加载失败");
    }
  };

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

  const canSubmit = useMemo(() => {
    return !!form.title.trim() && !!form.location.trim() && teams.length > 0;
  }, [form, teams]);

  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, "service_project_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 team = teams[teamIndex];
      const payload = {
        title: form.title.trim(),
        description: form.description.trim() || undefined,
        branchId: team.id,
        coverImageUrl: cover?.url || undefined,
        location: form.location.trim(),
        startsAt: toIsoFromDisplay(form.startsAt) || undefined,
        endsAt: toIsoFromDisplay(form.endsAt) || undefined,
        memberCount: form.memberCount ? Number(form.memberCount) : undefined,
        serviceTarget: form.serviceTarget.trim() || undefined
      };
      if (editId > 0) {
        await updateServiceProject(editId, payload);
        await resubmitServiceProject(editId);
      } else {
        await createServiceProject(payload);
      }
      await showActionDrawer({
        type: "success",
        title: editId > 0 ? "已重新提交" : "成功提交",
        content: editId > 0 ? "修改内容已重新进入审核流程" : "请等待审核",
        confirmText: "查看我的项目",
        showCancel: false
      });
      await Taro.redirectTo({ url: "/pages/my-service-projects/index" });
    } catch (e: any) {
      setError(e?.message || "提交失败");
    } finally {
      setSubmitting(false);
    }
  };

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

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

        <View className="service-create-card card-surface">
          <Input
            className="service-create-input"
            value={form.title}
            onInput={(e) => setForm((s) => ({ ...s, title: e.detail.value }))}
            placeholder="请输入项目名称"
            placeholderStyle="color:#9ca3af;font-size:24rpx;line-height:88rpx;"
          />
          <View className="service-create-picker">
            <DateTimeField value={form.startsAt} onChange={(v) => setForm((s) => ({ ...s, startsAt: v }))} placeholder="开始时间 YYYY-MM-DD HH:mm" />
          </View>
          <View className="service-create-picker">
            <DateTimeField value={form.endsAt} onChange={(v) => setForm((s) => ({ ...s, endsAt: v }))} placeholder="结束时间 YYYY-MM-DD HH:mm" />
          </View>
          <Input
            className="service-create-input"
            value={form.location}
            onInput={(e) => setForm((s) => ({ ...s, location: e.detail.value }))}
            placeholder="请输入活动地点"
            placeholderStyle="color:#9ca3af;font-size:24rpx;line-height:88rpx;"
          />
          <Picker
            mode="selector"
            range={teams.map((item) => `${item.name}${item.__source === "branch" ? "（分会）" : "（服务团）"}`)}
            value={teamIndex}
            onChange={(e) => setTeamIndex(Number(e.detail.value))}
          >
            <View className="service-create-picker">
              {teams[teamIndex]
                ? `${teams[teamIndex]?.name}${teams[teamIndex]?.__source === "branch" ? "（分会）" : "（服务团）"}`
                : "请选择所属服务团/分会"}
            </View>
          </Picker>
          <Input
            className="service-create-input"
            value={form.memberCount}
            onInput={(e) => setForm((s) => ({ ...s, memberCount: e.detail.value }))}
            placeholder="请输入参与人数（可选）"
            placeholderStyle="color:#9ca3af;font-size:24rpx;line-height:88rpx;"
            type="number"
          />
          <Input
            className="service-create-input"
            value={form.serviceTarget}
            onInput={(e) => setForm((s) => ({ ...s, serviceTarget: e.detail.value }))}
            placeholder="请输入服务对象（可选）"
            placeholderStyle="color:#9ca3af;font-size:24rpx;line-height:88rpx;"
          />
          <Textarea
            className="service-create-textarea"
            value={form.description}
            onInput={(e) => setForm((s) => ({ ...s, description: e.detail.value }))}
            placeholder="请填写服务项目说明"
            placeholderStyle="color:#9ca3af;font-size:24rpx;"
            autoHeight
          />
        </View>

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

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