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

function splitTags(value?: string) {
  return String(value || "")
    .split(/[，、,]/)
    .map((item) => item.trim())
    .filter(Boolean)
    .slice(0, 6);
}

export default function ServiceTeamDetailPage() {
  useAuthGuard();
  const { params } = useRouter();
  const id = params?.id;
  const [detail, setDetail] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

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

  const tags = splitTags(detail?.tags_text);
  const members = Array.isArray(detail?.members) ? detail.members : [];
  const coverImageUrl = resolveMediaUrl(firstText(detail?.coverImageUrl, detail?.cover_image_url, detail?.imageUrl, detail?.image_url, detail?.image));
  const memberCount = Number(detail?.memberCount ?? detail?.member_count ?? 0) || members.length || 0;

  return (
    <View className="page-shell service-team-detail-page">
      {coverImageUrl ? (
        <View className="service-team-detail-hero">
          <Image className="service-team-detail-hero__image" src={coverImageUrl} mode="aspectFill" />
          <View className="service-team-detail-hero__mask" />
          <View className="service-team-detail-hero__summary">
            <View className="service-team-detail-hero__logo">
              <Image className="service-team-detail-hero__logo-image" src={coverImageUrl} mode="aspectFill" />
            </View>
            <View>
              <Text className="service-team-detail-hero__title">{detail.name || "未命名服务团"}</Text>
              <Text className="service-team-detail-hero__count">专家成员：{memberCount}位</Text>
            </View>
          </View>
        </View>
      ) : null}

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

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

        {detail ? (
          <>
            <View className="card-surface service-team-detail-tags">
              <Text className="service-team-detail-section-title">服务领域</Text>
              <View className="service-team-detail-tags__list">
                {(tags.length > 0 ? tags : ["服务支持"]).map((tag) => (
                  <Text key={tag} className="service-team-detail-tags__item">
                    {tag}
                  </Text>
                ))}
              </View>
            </View>

            <View className="card-surface service-team-detail-desc">
              <Text className="service-team-detail-section-title">团队介绍</Text>
              <Text className="service-team-detail-desc__text">{detail.description || "暂无团队介绍"}</Text>
            </View>

            <View className="card-surface service-team-detail-members">
              <Text className="service-team-detail-section-title">核心成员</Text>
              <View className="service-team-detail-members__list">
                {members.map((member: any) => (
                  <View key={member.id} className="service-team-detail-members__item">
                    <View className="service-team-detail-members__avatar">
                      <Text>{String(member.name || "成员").slice(0, 1)}</Text>
                    </View>
                    <View className="service-team-detail-members__content">
                      <View className="service-team-detail-members__head">
                        <Text className="service-team-detail-members__name">{member.name || "未命名成员"}</Text>
                        <Text className="service-team-detail-members__role">{member.role_name || "成员"}</Text>
                      </View>
                      <Text className="service-team-detail-members__title">{member.title || "暂无职务"}</Text>
                    </View>
                  </View>
                ))}
              </View>
            </View>
          </>
        ) : null}
      </View>
    </View>
  );
}
