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

function statusLabel(detail: any) {
  if (detail?.statusText || detail?.status_text) return detail.statusText || detail.status_text;
  const map: Record<string, string> = {
    pending: "待受理",
    assigned: "已分派",
    handling: "处理中",
    in_progress: "处理中",
    completed: "已完成",
    resolved: "已解决",
    rejected: "已驳回",
    closed: "已关闭"
  };
  return map[String(detail?.status || "")] || String(detail?.status || "待处理");
}

function logActionText(action: any) {
  const map: Record<string, string> = {
    submit: "提交求助",
    resubmit: "更新求助",
    assign: "分派经办",
    status_change: "状态变更",
    seed: "系统迁移"
  };
  return map[String(action || "")] || "进度更新";
}

export default function ServiceHelpDetailPage() {
  useAuthGuard();
  useMemberGuard("服务求助仅面向正式会员开放");
  const router = useRouter();
  const id = Number(router.params?.id || router.params?.highlightHelpId || 0);
  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 getMyServiceHelpRequestDetail(id);
        setDetail(data || null);
        setError("");
      } catch (e: any) {
        setError(e?.message || "求助详情加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  const logs = Array.isArray(detail?.logs) ? detail.logs : [];

  return (
    <View className="help-detail-page">
      <View className="help-detail-page__body">
        {error ? <Text className="help-state is-error">{error}</Text> : null}
        {loading ? <Text className="help-state">加载中...</Text> : null}
        {detail ? (
          <>
            <View className="help-panel">
              <View className="help-panel__head">
                <Text className="help-title">{detail.title || "服务求助"}</Text>
                <Text className="help-status">{statusLabel(detail)}</Text>
              </View>
              <Text className="help-desc">{detail.description || "暂无求助说明"}</Text>
              <View className="help-grid">
                <Text>服务团：{detail.service_team_name || detail.serviceTeamName || "-"}</Text>
                <Text>紧急程度：{detail.urgency_text || detail.urgencyText || detail.urgency || "-"}</Text>
                <Text>经办人：{detail.assignee_name || detail.assigneeName || "-"}</Text>
                <Text>创建时间：{detail.created_at || detail.createdAt || "-"}</Text>
              </View>
              {detail.result_note || detail.resultNote ? <Text className="help-result">处理结果：{detail.result_note || detail.resultNote}</Text> : null}
              {detail.service_team_id || detail.serviceTeamId ? (
                <View className="help-action" onClick={() => Taro.navigateTo({ url: `/pages/service-team-detail/index?id=${detail.service_team_id || detail.serviceTeamId}` })}>
                  <Text>查看服务团</Text>
                </View>
              ) : null}
            </View>

            <View className="help-panel">
              <Text className="help-section-title">处理进度</Text>
              {logs.length === 0 ? <Text className="help-empty">暂无进度记录</Text> : null}
              {logs.map((log: any, index: number) => (
                <View key={log.id || index} className="help-log">
                  <View className="help-log__top">
                    <Text className="help-log__title">{logActionText(log.action)}</Text>
                    <Text className="help-log__time">{log.created_at || log.createdAt || "-"}</Text>
                  </View>
                  <Text className="help-log__note">{log.note || "暂无备注"}</Text>
                  <Text className="help-log__meta">{log.operator_name || log.operatorName || "系统"} · {log.from_status || "-"} → {log.to_status || "-"}</Text>
                </View>
              ))}
            </View>
          </>
        ) : !loading && !error ? (
          <Text className="help-state">求助记录不存在或已删除</Text>
        ) : null}
      </View>
    </View>
  );
}
