import { Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useState } from "react";
import { getServiceProjectDetail } from "../../api/services";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { firstText, resolveMediaUrl } from "../../utils/media";
import "./index.scss";

function formatDateTime(start?: string, end?: string) {
  const startText = start ? String(start).slice(0, 16).replace("T", " ").replaceAll("-", ".") : "-";
  const endText = end ? String(end).slice(11, 16) : "";
  return endText ? `${startText}~${endText}` : startText;
}

function statusText(status?: string) {
  if (["published", "ongoing", "active", "1"].includes(String(status || ""))) return "正在进行";
  if (status === "pending_branch_review" || status === "pending_city_review" || status === "draft") return "等待审核";
  if (status === "ended") return "已结束";
  if (status?.includes("rejected")) return "已驳回";
  return "未开始";
}

export default function ServiceDetailPage() {
  useAuthGuard();
  const { params } = useRouter();
  const id = params?.id;
  const [detail, setDetail] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const coverImageUrl = resolveMediaUrl(firstText(detail?.coverImageUrl, detail?.cover_image_url, detail?.imageUrl, detail?.image_url, detail?.image));
  const startsAt = firstText(detail?.startsAt, detail?.starts_at);
  const endsAt = firstText(detail?.endsAt, detail?.ends_at);
  const branchName = firstText(detail?.branchName, detail?.branch_name);
  const serviceTarget = firstText(detail?.serviceTarget, detail?.service_target);
  const memberCount = Number(detail?.memberCount ?? detail?.member_count ?? 0) || 0;
  const statusLabel = firstText(detail?.statusText, detail?.status_text) || statusText(detail?.status);
  const rejected = ["rejected", "branch_rejected", "city_rejected"].includes(String(detail?.status || ""));
  const reviewReason = firstText(detail?.reviewReason, detail?.review_reason);

  useDidShow(() => {
    if (!id) return;
    void (async () => {
      setLoading(true);
      try {
        const data = await getServiceProjectDetail(id);
        setDetail(data || null);
        setError("");
      } catch (e: any) {
        setError(e?.message || "项目详情加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  return (
    <View className="page-shell service-detail-page">
      {coverImageUrl ? (
        <View className="service-detail-hero">
          <Image className="service-detail-hero__image" src={coverImageUrl} mode="aspectFill" />
          <View className="service-detail-hero__mask" />
          <View className="service-detail-hero__status">
            <Text>{statusLabel}</Text>
          </View>
        </View>
      ) : null}

      <View className={`page-body service-detail-page__body ${coverImageUrl ? "has-hero" : ""}`}>
        {error ? (
          <View className="service-detail-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        {loading && !detail ? (
          <View className="card-surface service-detail-empty">
            <Text>加载中...</Text>
          </View>
        ) : null}

        {detail ? (
          <>
            <View className="card-surface service-detail-main">
              <Text className="service-detail-main__title">{detail.title || "未命名项目"}</Text>
              <View className="service-detail-main__rows">
                <View className="service-detail-main__row">
                  <Text className="service-detail-main__label">服务时间</Text>
                  <Text className="service-detail-main__value">{formatDateTime(startsAt, endsAt)}</Text>
                </View>
                <View className="service-detail-main__row">
                  <Text className="service-detail-main__label">服务地点</Text>
                  <Text className="service-detail-main__value">{detail.location || "-"}</Text>
                </View>
                <View className="service-detail-main__row">
                  <Text className="service-detail-main__label">所属分会</Text>
                  <Text className="service-detail-main__value">{branchName || "待补充"}</Text>
                </View>
                <View className="service-detail-main__row">
                  <Text className="service-detail-main__label">服务对象</Text>
                  <Text className="service-detail-main__value">{serviceTarget || "待补充"}</Text>
                </View>
                <View className="service-detail-main__row">
                  <Text className="service-detail-main__label">项目成员</Text>
                  <Text className="service-detail-main__value">{memberCount} 人</Text>
                </View>
              </View>
            </View>

            <View className="card-surface service-detail-content">
              <Text className="service-detail-content__title">项目详情</Text>
              <Text className="service-detail-content__text">{detail.description || "暂无详情"}</Text>
            </View>

            {rejected ? (
              <View className="card-surface service-detail-review">
                <Text className="service-detail-content__title">审核反馈</Text>
                <Text className="service-detail-content__text">{reviewReason || "暂无驳回说明"}</Text>
                <View className="service-detail-review__btn" onClick={() => void Taro.navigateTo({ url: `/pages/service-create/index?id=${id}&mode=edit-resubmit` })}>
                  <Text>修改后重新提交</Text>
                </View>
              </View>
            ) : null}
          </>
        ) : null}
      </View>
    </View>
  );
}
