import { Button, Image, Input, Picker, Text, Textarea, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { createServiceDemand, getServiceProjects, getServiceTeams } from "../../api/services";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { ensureMemberAccess } from "../../utils/permission";
import { firstText, resolveMediaUrl } from "../../utils/media";
import { useActionDrawer } from "../../components/action-drawer";
import "./index.scss";

const TABS = ["全部", "正在进行", "未开始"];
const URGENCY_OPTIONS = [
  { label: "普通", value: "normal" },
  { label: "较急", value: "medium" },
  { label: "紧急", value: "high" }
];

type ServiceTeamItem = {
  id: number;
  name?: string;
  description?: string;
  coverImageUrl?: string;
  memberCount?: number;
  tags?: string[];
};

type ServiceProjectItem = {
  id: number;
  title?: string;
  location?: string;
  startsAt?: string;
  endsAt?: string;
  status?: string;
  memberCount?: number;
  description?: string;
  serviceTarget?: string;
  coverImageUrl?: string;
};

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

function normalizeTeam(item: any): ServiceTeamItem {
  const rawTags = Array.isArray(item?.tags) && item.tags.length > 0
    ? item.tags
    : splitTags(item?.tagsText || item?.tags_text);
  return {
    id: Number(item?.id),
    name: item?.name || "",
    description: item?.description || "",
    coverImageUrl: resolveMediaUrl(firstText(item?.coverImageUrl, item?.cover_image_url, item?.imageUrl, item?.image_url, item?.image)),
    memberCount: Number(item?.memberCount ?? item?.member_count ?? 0) || 0,
    tags: rawTags.filter(Boolean).slice(0, 3)
  };
}

function normalizeProject(item: any): ServiceProjectItem {
  return {
    id: Number(item?.id),
    title: item?.title || "",
    location: item?.location || "",
    startsAt: item?.startsAt || item?.starts_at || "",
    endsAt: item?.endsAt || item?.ends_at || "",
    status: item?.status || "",
    memberCount: Number(item?.memberCount ?? item?.member_count ?? 0) || 0,
    description: item?.description || "",
    serviceTarget: item?.serviceTarget || item?.service_target || "",
    coverImageUrl: resolveMediaUrl(firstText(item?.coverImageUrl, item?.cover_image_url, item?.imageUrl, item?.image_url, item?.image))
  };
}

function projectStatusText(status?: string) {
  if (status === "ongoing") return "正在进行";
  if (status === "pending_start") return "未开始";
  if (status === "ended") return "已结束";
  if (status === "published") return "正在进行";
  return "未开始";
}

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) : "";
  if (!endText) return startText;
  return `${startText}-${endText}`;
}

export default function ServicesPage() {
  useAuthGuard();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [activeTab, setActiveTab] = useState("全部");
  const [teams, setTeams] = useState<ServiceTeamItem[]>([]);
  const [projects, setProjects] = useState<ServiceProjectItem[]>([]);
  const [demandingTeamId, setDemandingTeamId] = useState<number | null>(null);
  const [demandTeam, setDemandTeam] = useState<ServiceTeamItem | null>(null);
  const [demandForm, setDemandForm] = useState({ title: "", description: "", urgency: "normal" });
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  const load = async () => {
    setLoading(true);
    try {
      const [teamData, projectData] = await Promise.all([getServiceTeams(), getServiceProjects()]);
      setTeams((Array.isArray(teamData) ? teamData : []).map(normalizeTeam));
      setProjects((Array.isArray(projectData) ? projectData : []).map(normalizeProject));
      setError("");
    } catch (e: any) {
      setError(e?.message || "社会服务加载失败");
    } finally {
      setLoading(false);
    }
  };

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

  const filteredProjects = useMemo(() => {
    if (activeTab === "全部") return projects;
    return projects.filter((item) => projectStatusText(item.status) === activeTab);
  }, [activeTab, projects]);

  const onDemand = async (teamId: number) => {
    const ok = await ensureMemberAccess("仅会员可提交服务需求");
    if (!ok) return;
    const team = teams.find((item) => item.id === teamId) || null;
    setDemandTeam(team);
    setDemandForm({
      title: `${team?.name || "服务团"}服务求助`,
      description: "",
      urgency: "normal"
    });
  };

  const submitDemand = async () => {
    if (!demandTeam || demandingTeamId) return;
    const description = demandForm.description.trim();
    if (!description) {
      Taro.showToast({ title: "请填写求助说明", icon: "none" });
      return;
    }
    setDemandingTeamId(demandTeam.id);
    try {
      await createServiceDemand(demandTeam.id, {
        title: demandForm.title.trim() || `${demandTeam.name || "服务团"}服务求助`,
        description,
        urgency: demandForm.urgency
      });
      setDemandTeam(null);
      await load();
      await showActionDrawer({
        type: "success",
        title: "需求已提交",
        content: "服务团将查看你的求助说明，并在后台跟进处理。",
        confirmText: "知道了",
        showCancel: false
      });
    } finally {
      setDemandingTeamId(null);
    }
  };

  const openTeamDetail = async (id: number) => {
    await Taro.navigateTo({ url: `/pages/service-team-detail/index?id=${id}` });
  };

  const openProjectDetail = async (id: number) => {
    await Taro.navigateTo({ url: `/pages/service-detail/index?id=${id}` });
  };

  const gotoCreateProject = async () => {
    const ok = await ensureMemberAccess("仅会员可创建服务项目");
    if (!ok) return;
    await Taro.navigateTo({ url: "/pages/service-create/index" });
  };

  const gotoCreateTeam = async () => {
    const ok = await ensureMemberAccess("仅正式会员可申请创建服务团");
    if (!ok) return;
    await Taro.navigateTo({ url: "/pages/service-team-create/index" });
  };
  const urgencyIndex = Math.max(0, URGENCY_OPTIONS.findIndex((item) => item.value === demandForm.urgency));


  return (
    <View className="page-shell services-page">
      <View className="page-body services-page__body">
        {error ? (
          <View className="services-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        <View className="services-section">
          <Text className="services-section__title">服务团</Text>
          <View className="services-team-list">
            {teams.length === 0 && !loading ? (
              <View className="card-surface services-empty">
                <Text>暂无服务团</Text>
              </View>
            ) : null}

            {teams.map((team) => (
              <View key={team.id} className="card-surface services-team-card">
                <View className="services-team-card__row">
                  {team.coverImageUrl ? (
                    <View className="services-team-card__cover">
                      <Image className="services-team-card__cover-image" src={team.coverImageUrl} mode="aspectFill" />
                    </View>
                  ) : null}

                  <View className="services-team-card__content">
                    <View>
                      <Text className="services-team-card__name">{team.name || "未命名服务团"}</Text>
                      <View className="services-team-card__tags">
                        {(team.tags && team.tags.length > 0 ? team.tags : ["法律咨询", "服务支持"]).map((tag) => (
                          <Text key={`${team.id}-${tag}`} className="services-team-card__tag">
                            {tag}
                          </Text>
                        ))}
                      </View>
                    </View>

                    <View className="services-team-card__footer">
                      <Text className="services-team-card__count">专家成员：{team.memberCount || 0}位</Text>
                      <View className="services-team-card__actions">
                        <Button className="services-team-card__mini-button services-team-card__mini-button--light" size="mini" loading={demandingTeamId === team.id} onClick={() => void onDemand(team.id)}>
                          我需要帮助
                        </Button>
                        <View className="services-team-card__detail" onClick={() => void openTeamDetail(team.id)}>
                          <Text>详情</Text>
                        </View>
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            ))}
          </View>
        </View>

        <View className="services-section">
          <Text className="services-section__title">社会服务项目</Text>
          <View className="services-tabs">
            {TABS.map((tab) => (
              <View key={tab} className={`services-tab ${activeTab === tab ? "is-active" : ""}`} onClick={() => setActiveTab(tab)}>
                <Text>{tab}</Text>
              </View>
            ))}
          </View>

          <View className="services-project-list">
            {filteredProjects.length === 0 && !loading ? (
              <View className="card-surface services-empty">
                <Text>暂无社会服务项目</Text>
              </View>
            ) : null}

            {filteredProjects.map((project) => {
              const statusLabel = projectStatusText(project.status);
              const actionText = statusLabel === "正在进行" ? "详情" : "未开始";
              return (
                <View key={project.id} className="card-surface services-project-card" onClick={() => void openProjectDetail(project.id)}>
                  <View className="services-project-card__top">
                    {project.coverImageUrl ? (
                      <View className="services-project-card__cover">
                        <Image className="services-project-card__cover-image" src={project.coverImageUrl} mode="aspectFill" />
                      </View>
                    ) : null}

                    <View className="services-project-card__content">
                      <Text className="services-project-card__title">{project.title || "未命名服务项目"}</Text>
                      <View className="services-project-card__meta">
                        <Text className="services-project-card__meta-line">{formatDateTime(project.startsAt, project.endsAt)}</Text>
                        <Text className="services-project-card__meta-line">专家成员：{project.memberCount || 0}人</Text>
                        <Text className="services-project-card__meta-line">{project.location || "地点待补充"}</Text>
                      </View>
                    </View>
                  </View>

                  <View className="services-project-card__bottom">
                    <Text className="services-project-card__description">{project.description || project.serviceTarget || "暂无服务说明"}</Text>
                    <View className={`services-project-card__action ${statusLabel === "正在进行" ? "is-primary" : "is-muted"}`}>
                      <Text>{actionText}</Text>
                    </View>
                  </View>
                </View>
              );
            })}
          </View>
        </View>

        <View className="services-create-bar">
          <Button className="services-create-button services-create-button--light" onClick={() => void gotoCreateTeam()}>
            申请创建服务团
          </Button>
          <Button className="services-create-button" onClick={() => void gotoCreateProject()}>
            创建服务项目
          </Button>
        </View>
      </View>
      {demandTeam ? (
        <View className="services-demand-mask" onClick={() => setDemandTeam(null)}>
          <View className="services-demand-panel" onClick={(event) => event.stopPropagation()}>
            <Text className="services-demand-panel__title">提交服务求助</Text>
            <Text className="services-demand-panel__team">{demandTeam.name || "服务团"}</Text>
            <Input
              className="services-demand-panel__input"
              value={demandForm.title}
              onInput={(event) => setDemandForm((state) => ({ ...state, title: event.detail.value }))}
              placeholder="求助标题"
              placeholderStyle="color:#9ca3af;"
            />
            <Picker
              mode="selector"
              range={URGENCY_OPTIONS.map((item) => item.label)}
              value={urgencyIndex}
              onChange={(event) => {
                const next = URGENCY_OPTIONS[Number(event.detail.value)] || URGENCY_OPTIONS[0];
                setDemandForm((state) => ({ ...state, urgency: next.value }));
              }}
            >
              <View className="services-demand-panel__picker">
                紧急度：{URGENCY_OPTIONS[urgencyIndex]?.label || "普通"}
              </View>
            </Picker>
            <Textarea
              className="services-demand-panel__textarea"
              value={demandForm.description}
              onInput={(event) => setDemandForm((state) => ({ ...state, description: event.detail.value }))}
              placeholder="请说明你需要什么帮助、希望如何对接"
              placeholderStyle="color:#9ca3af;"
              autoHeight
            />
            <View className="services-demand-panel__actions">
              <View className="services-demand-panel__btn is-cancel" onClick={() => setDemandTeam(null)}>
                <Text>取消</Text>
              </View>
              <View className={`services-demand-panel__btn ${demandingTeamId === demandTeam.id ? "is-disabled" : ""}`} onClick={() => void submitDemand()}>
                <Text>{demandingTeamId === demandTeam.id ? "提交中" : "提交"}</Text>
              </View>
            </View>
          </View>
        </View>
      ) : null}
      {actionDrawer}
    </View>
  );
}
