import { Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { getMyPerformanceRecords, getMyPointRecords, getMyPointTasks } from "../../api/me";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { useUserStore } from "../../store/user";
import "./index.scss";

function flattenTasks(data: any): any[] {
  if (!Array.isArray(data)) return [];
  return data.flatMap((item) => {
    if (Array.isArray(item?.tasks)) {
      return item.tasks.map((task: any) => ({ ...task, category: item.category }));
    }
    return item;
  });
}

export default function MyPointsPage() {
  useAuthGuard();
  useMemberGuard("我的积分仅面向正式会员开放");

  const me = useUserStore((s) => s.me);
  const bootstrap = useUserStore((s) => s.bootstrap);
  const [tasks, setTasks] = useState<any[]>([]);
  const [records, setRecords] = useState<any[]>([]);
  const [performanceRecords, setPerformanceRecords] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        await bootstrap();
        const [taskData, recordData, performanceData] = await Promise.all([getMyPointTasks(), getMyPointRecords(), getMyPerformanceRecords()]);
        setTasks(flattenTasks(taskData));
        setRecords(Array.isArray(recordData) ? recordData : []);
        setPerformanceRecords(Array.isArray(performanceData) ? performanceData : []);
        setError("");
      } catch (e: any) {
        setError(e?.message || "积分数据加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  return (
    <View className="page-shell my-points-page">
      <View className="page-body my-points-page__body">
        {error ? (
          <View className="card-surface my-points-block">
            <Text className="my-points-empty">{error}</Text>
          </View>
        ) : null}

        <View className="my-points-hero">
          <Text className="my-points-hero__label">我的积分</Text>
          <Text className="my-points-hero__value">{me?.points || 0}</Text>
        </View>

        <View className="card-surface my-points-block">
          <View className="my-points-block__head">
            <Text className="my-points-block__title">补充履职记录</Text>
            <View className="my-points-block__action" onClick={() => Taro.navigateTo({ url: "/pages/performance-create/index" })}>
              <Text>增加履职记录</Text>
            </View>
          </View>
          {loading && performanceRecords.length === 0 ? <Text className="my-points-empty">加载中...</Text> : null}
          {!loading && performanceRecords.length === 0 ? <Text className="my-points-empty">暂无履职记录</Text> : null}
          <View className="my-points-list">
            {performanceRecords.map((item, idx) => (
              <View key={item.id || idx} className="my-points-item my-points-performance">
                <View className="my-points-item__row">
                  <Text className="my-points-item__name">{item.title || "履职记录"}</Text>
                  <Text className={`my-points-status ${String(item.status || "")}`}>{item.statusText || item.status_text || "-"}</Text>
                </View>
                <View className="my-points-item__row my-points-item__row--meta">
                  <Text className="my-points-item__meta">{item.date || "-"}</Text>
                  <Text className="my-points-item__value">{item.points || ""}</Text>
                </View>
                {item.reviewReason || item.review_reason ? <Text className="my-points-item__reason">原因：{item.reviewReason || item.review_reason}</Text> : null}
              </View>
            ))}
          </View>
        </View>

        <View className="card-surface my-points-block">
          <Text className="my-points-block__title">积分任务</Text>
          {loading && tasks.length === 0 ? <Text className="my-points-empty">加载中...</Text> : null}
          {!loading && tasks.length === 0 ? <Text className="my-points-empty">暂无积分任务</Text> : null}
          <View className="my-points-list">
            {tasks.map((item, idx) => (
              <View key={item.id || item.code || idx} className="my-points-item">
                <View className="my-points-item__row">
                  <Text className="my-points-item__name">{item.name || item.task_name || "积分任务"}</Text>
                  <Text className="my-points-item__value">+{item.points || item.point_value || 0}</Text>
                </View>
                <Text className="my-points-item__meta">{item.completed ? "已完成" : "未完成"}</Text>
              </View>
            ))}
          </View>
        </View>

        <View className="card-surface my-points-block">
          <Text className="my-points-block__title">积分记录</Text>
          {loading && records.length === 0 ? <Text className="my-points-empty">加载中...</Text> : null}
          {!loading && records.length === 0 ? <Text className="my-points-empty">暂无积分记录</Text> : null}
          <View className="my-points-list">
            {records.slice(0, 20).map((item, idx) => (
              <View key={item.id || item.record_id || idx} className="my-points-item">
                <View className="my-points-item__row">
                  <Text className="my-points-item__name">{item.title || item.rule_name || item.business_type || "积分记录"}</Text>
                  <Text className="my-points-item__value">{item.points_text || `${item.points || item.delta || 0}`}</Text>
                </View>
                <Text className="my-points-item__meta">{item.created_at || item.date || item.status_text || "-"}</Text>
              </View>
            ))}
          </View>
        </View>
      </View>
    </View>
  );
}
