import { Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useState } from "react";
import { getMyServiceHelpRequestDetail, getMyServiceHelpRequests, getMyServiceProjects } from "../../api/me";
import { useActionDrawer } from "../../components/action-drawer";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import "./index.scss";

function projectStatusText(raw?: string, text?: string) {
  if (text) return text;
  const map: Record<string, string> = {
    published: "正在进行",
    active: "正在进行",
    "1": "正在进行",
    draft: "审核中",
    pending: "审核中",
    pending_branch_review: "审核中",
    pending_city_review: "审核中",
    rejected: "已驳回",
    branch_rejected: "已驳回",
    city_rejected: "已驳回",
    archived: "已下架"
  };
  return map[String(raw || "")] || String(raw || "-");
}

function helpStatusText(status?: string, text?: string) {
  if (text) return text;
  const map: Record<string, string> = {
    pending: "待受理",
    pending_branch_review: "审核中",
    pending_city_review: "审核中",
    assigned: "已分派",
    handling: "处理中",
    in_progress: "处理中",
    completed: "已完成",
    resolved: "已解决",
    rejected: "已驳回",
    branch_rejected: "已驳回",
    city_rejected: "已驳回",
    closed: "已关闭"
  };
  return map[String(status || "")] || String(status || "-");
}

function helpDetailText(detail: any) {
  const logs = Array.isArray(detail?.logs) ? detail.logs : [];
  const logLines = logs.slice(0, 5).map((log) => {
    const time = log.created_at || log.createdAt || "-";
    const note = log.note || "暂无备注";
    const action = log.action === "submit" ? "提交求助" : log.action === "resubmit" ? "更新求助" : log.action === "assign" ? "分派经办" : log.action === "status_change" ? "状态变更" : "进度更新";
    return `${time} ${action}：${note}`;
  });
  return [
    `状态：${helpStatusText(detail?.status, detail?.status_text || detail?.statusText)}`,
    `服务团：${detail?.service_team_name || detail?.serviceTeamName || "-"}`,
    `紧急程度：${detail?.urgency_text || detail?.urgencyText || detail?.urgency || "-"}`,
    `经办人：${detail?.assignee_name || detail?.assigneeName || "-"}`,
    `处理结果：${detail?.result_note || detail?.resultNote || "-"}`,
    "",
    "处理进度",
    ...(logLines.length ? logLines : ["暂无进度记录"])
  ].join("\n");
}

export default function MyServiceProjectsPage() {
  useAuthGuard();
  useMemberGuard("我的服务仅面向正式会员开放");
  const router = useRouter();
  const [items, setItems] = useState<any[]>([]);
  const [helpRequests, setHelpRequests] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const [data, helpData] = await Promise.all([getMyServiceProjects(), getMyServiceHelpRequests()]);
        const helpRows = Array.isArray(helpData) ? helpData : [];
        const highlightHelpId = String(router.params?.highlightHelpId || "").trim();
        setItems(Array.isArray(data) ? data : []);
        if (highlightHelpId) {
          const hitIndex = helpRows.findIndex((item) => String(item?.id || "") === highlightHelpId);
          if (hitIndex >= 0) {
            const hit = helpRows[hitIndex];
            setHelpRequests([hit, ...helpRows.filter((_, index) => index !== hitIndex)]);
            setNotice(`已为你定位求助记录：${hit?.title || highlightHelpId}`);
          } else {
            setHelpRequests(helpRows);
            setNotice("暂未定位到该求助记录，请刷新后再查看。");
          }
        } else {
          setHelpRequests(helpRows);
          setNotice("");
        }
        setError("");
      } catch (e: any) {
        setError(e?.message || "加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  const showReason = async (item: any) => {
    await showActionDrawer({
      type: "info",
      title: "驳回原因",
      content: String(item?.review_reason || item?.reviewReason || "暂无驳回说明"),
      confirmText: "知道了",
      showCancel: false
    });
  };

  const gotoEditResubmit = (item: any) => {
    const id = Number(item?.id || 0);
    if (!id) return;
    void Taro.navigateTo({ url: `/pages/service-create/index?id=${id}&mode=edit-resubmit` });
  };

  const showHelpDetail = async (item: any) => {
    const id = Number(item?.id || 0);
    if (!id) return;
    try {
      const detail = await getMyServiceHelpRequestDetail(id);
      await showActionDrawer({
        type: "info",
        title: detail?.title || item?.title || "服务求助进度",
        content: helpDetailText(detail || item),
        confirmText: "知道了",
        showCancel: false
      });
    } catch (e: any) {
      await showActionDrawer({
        type: "danger",
        title: "加载失败",
        content: e?.message || "暂时无法查看求助详情",
        confirmText: "知道了",
        showCancel: false
      });
    }
  };

  return (
    <View className="my-service-projects-page">
      <View className="my-service-projects-page__body">
        {error ? (
          <View className="my-service-projects-state is-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        {loading ? (
          <View className="my-service-projects-state">
            <Text>加载中...</Text>
          </View>
        ) : null}

        {!loading && !error && notice ? (
          <View className="my-service-projects-state">
            <Text>{notice}</Text>
          </View>
        ) : null}

        <View className="my-service-section">
          <Text className="my-service-section__title">我的社会服务项目</Text>
          {!loading && !error && items.length === 0 ? (
            <View className="my-service-projects-state">
              <Text>暂无社会服务项目</Text>
            </View>
          ) : null}

          <View className="my-service-projects-list">
            {items.map((item) => {
              const canResubmit = Boolean(item.can_resubmit ?? item.canResubmit);
              return (
                <View
                  key={item.id || item.title}
                  className="my-service-projects-card"
                  onClick={() => void Taro.navigateTo({ url: `/pages/service-detail/index?id=${item.id}` })}
                >
                  <View className="my-service-projects-card__media">
                    {item.image ? <Image className="my-service-projects-card__image" src={item.image} mode="aspectFill" /> : null}
                  </View>
                  <View className="my-service-projects-card__content">
                    <Text className="my-service-projects-card__title">{item.title || "-"}</Text>
                    <Text className="my-service-projects-card__meta">{item.location || "-"}</Text>
                    <View className="my-service-projects-card__row">
                      <Text className="my-service-projects-card__date">{item.date || "-"}</Text>
                      <Text className="my-service-projects-card__status">{projectStatusText(item.status, item.statusText || item.status_text)}</Text>
                    </View>
                    {canResubmit ? (
                      <View className="my-service-projects-card__actions">
                        <Text
                          className="my-service-projects-card__link"
                          onClick={(event) => {
                            event.stopPropagation();
                            void showReason(item);
                          }}
                        >
                          查看原因
                        </Text>
                        <Text
                          className="my-service-projects-card__link"
                          onClick={(event) => {
                            event.stopPropagation();
                            gotoEditResubmit(item);
                          }}
                        >
                          修改后重新提交
                        </Text>
                      </View>
                    ) : null}
                  </View>
                </View>
              );
            })}
          </View>
        </View>

        <View className="my-service-section">
          <Text className="my-service-section__title">我的求助记录</Text>
          {!loading && !error && helpRequests.length === 0 ? (
            <View className="my-service-projects-state">
              <Text>暂无求助记录</Text>
            </View>
          ) : null}

          <View className="my-service-projects-list">
            {helpRequests.map((item) => (
              <View key={item.id || item.title} className="my-service-help-card" onClick={() => void Taro.navigateTo({ url: `/pages/service-help-detail/index?id=${item.id}` })}>
                <View className="my-service-help-card__head">
                  <Text className="my-service-help-card__title">{item.title || "社会服务求助"}</Text>
                  <Text className={`my-service-help-card__status ${String(item.status || "")}`}>{helpStatusText(item.status, item.status_text || item.statusText)}</Text>
                </View>
                <Text className="my-service-help-card__meta">{item.service_team_name || "服务团"}</Text>
                <Text className="my-service-help-card__desc">{item.description || "暂无说明"}</Text>
                <View className="my-service-help-card__row">
                  <Text>{item.created_at || "-"}</Text>
                  {item.result_note ? <Text>{item.result_note}</Text> : null}
                </View>
                <Text className="my-service-help-card__link">查看处理进度</Text>
              </View>
            ))}
          </View>
        </View>
      </View>
      {actionDrawer}
    </View>
  );
}
