const app = getApp()
const { request } = require('../../utils/request')

Page({
  data: {
    user: {},
    honors: [],
    projects: [],
    filteredProjects: [],
    currentFilter: 'all', // all, enrolled, completed
    showHonorModal: false,
    currentHonor: null
  },

  onLoad() {
    const app = getApp()
    if (app.globalData.token) {
        this.fetchHonors()
        this.fetchProjects()
    }
  },

  onShow() {
    this.getUserInfo()
  },

  getUserInfo() {
      const app = getApp()
      if (!app.globalData.token) {
          // Not logged in, clear data
          this.setData({ user: {}, honors: [], projects: [] })
          return
      }

      // Try to get from globalData first to speed up rendering
      if (app.globalData.userInfo) {
          this.setData({ user: app.globalData.userInfo })
      }
      
      request({ url: '/user/' }).then(user => {
          app.globalData.userInfo = user;
          this.setData({ user: user });
          // Re-fetch data if needed based on user status change
          // this.fetchHonors();
          // this.fetchProjects();
      }).catch(err => {
          console.error('Failed to fetch user info', err)
          if (err && (err.code === 401 || err.code === 403)) {
              // Token invalid, clear it
              app.globalData.token = null;
              app.globalData.userInfo = null;
              this.setData({ user: {}, honors: [], projects: [] });
          }
      })
  },

  onPullDownRefresh() {
    const app = getApp()
    if (!app.globalData.token) {
        wx.stopPullDownRefresh()
        return
    }
    Promise.all([this.fetchHonors(), this.fetchProjects()]).then(() => {
      wx.stopPullDownRefresh()
    })
  },

  fetchHonors() {
    return request({
      url: '/user-honors/',
      method: 'GET'
    }).then(res => {
      this.setData({ honors: res || [] })
    }).catch(err => {
      console.error('Failed to fetch honors', err)
    })
  },

  fetchProjects() {
    return request({
      url: '/user-projects/',
      method: 'GET'
    }).then(res => {
      const list = Array.isArray(res) ? res : []
      const projects = list.map(item => {
          // Format date
          if (item.enrolled_at) {
              item.enrolled_at_formatted = item.enrolled_at.split('T')[0]
          }
          
          const statusMap = {
              'enrolled': '已报名',
              'studying': '在读',
              'graduated': '毕业',
              'finished': '结束',
              'completed': '已完成',
              'cancelled': '已取消'
          };
          item.status_display = statusMap[item.status] || item.status;
          
          return item
      })

      // Sort projects by status: enrolled, studying, finished, graduated
      const sortOrder = {
          'enrolled': 1,
          'studying': 2,
          'finished': 3,
          'graduated': 4
      };
      
      projects.sort((a, b) => {
          const orderA = sortOrder[a.status] || 99;
          const orderB = sortOrder[b.status] || 99;
          return orderA - orderB;
      });

      this.setData({ projects })
      this.filterProjects()
    }).catch(err => {
      console.error('Failed to fetch projects', err)
    })
  },

  setFilter(e) {
    const type = e.currentTarget.dataset.type
    this.setData({ currentFilter: type })
    this.filterProjects()
  },

  filterProjects() {
    const { projects, currentFilter } = this.data
    let filtered = []
    if (currentFilter === 'all') {
      filtered = projects
    } else if (currentFilter === 'enrolled') {
      // 进行中: 已报名, 在读
      const activeStatuses = ['enrolled', 'studying']
      filtered = projects.filter(p => activeStatuses.includes(p.status))
    } else if (currentFilter === 'completed') {
      // 已完成: 毕业, 结束, 已完成
      const completedStatuses = ['graduated', 'finished', 'completed']
      filtered = projects.filter(p => completedStatuses.includes(p.status))
    } else {
      filtered = projects.filter(p => p.status === currentFilter)
    }
    this.setData({ filteredProjects: filtered })
  },

  showHonorDetail(e) {
    const item = e.currentTarget.dataset.item
    this.setData({
      showHonorModal: true,
      currentHonor: item
    })
  },

  closeHonorModal() {
    this.setData({
      showHonorModal: false,
      currentHonor: null
    })
  },

  preventBubble() {
    // Prevent tap event from bubbling to mask
  }
})
