import { defineStore } from 'pinia'
import activityService from '../services/activity'

// 检测是否在真实模式
// 与 auth.ts 和 router/index.ts 保持一致
// demo: 强制演示模式
// auto 或未配置: 未登录自动进入演示模式（PRD默认行为）
// real: 真实模式
const isRealMode = (): boolean => {
  const envMode = import.meta.env.VITE_MOSQUITO_AUTH_MODE
  // 当设置为 'real' 时才是真实模式，其他情况（包括 'auto'、'demo'、未配置）都视为非真实模式
  return envMode === 'real'
}

export type ActivityStatus = 'DRAFT' | 'PENDING' | 'IN_APPROVAL' | 'APPROVED' | 'REJECTED' | 'WAITING_PUBLISH' | 'RUNNING' | 'PAUSED' | 'ENDED' | 'ARCHIVED' | 'DELETED'

export type ActivityConfig = {
  audience: string
  conversion: string
  reward: string
  budget: string
}

export type ActivityMetrics = {
  visits: number
  shares: number
  conversions: number
  budgetUsed: number
}

export type ActivityItem = {
  id: number
  name: string
  description: string
  status: ActivityStatus
  startTime: string
  endTime: string
  participants: number
  config: ActivityConfig
  metrics: ActivityMetrics
  createdAt: string
  updatedAt: string
}

const storageKey = 'mosquito-admin-activities-v1'

const safeRead = (): ActivityItem[] | null => {
  try {
    const raw = localStorage.getItem(storageKey)
    return raw ? (JSON.parse(raw) as ActivityItem[]) : null
  } catch {
    return null
  }
}

const safeWrite = (items: ActivityItem[]) => {
  try {
    localStorage.setItem(storageKey, JSON.stringify(items))
  } catch {
    // ignore storage errors in restricted contexts
  }
}

const seedActivities = (): ActivityItem[] => {
  const now = Date.now()
  const iso = (offsetDays: number) => new Date(now + offsetDays * 86400000).toISOString()
  return [
    {
      id: 1,
      name: '裂变增长计划',
      description: '邀请好友注册，获取双倍奖励。',
      status: 'RUNNING',
      startTime: iso(-7),
      endTime: iso(21),
      participants: 1280,
      config: {
        audience: '新注册用户与邀请达人',
        conversion: '完成注册并绑定手机号',
        reward: '每邀请 1 人奖励 20 积分',
        budget: '总预算 50,000 积分'
      },
      metrics: {
        visits: 48210,
        shares: 12800,
        conversions: 3840,
        budgetUsed: 32000
      },
      createdAt: iso(-10),
      updatedAt: iso(-1)
    },
    {
      id: 2,
      name: '新用户召回活动',
      description: '召回沉默用户，提升活跃度。',
      status: 'ENDED',
      startTime: iso(-21),
      endTime: iso(-2),
      participants: 640,
      config: {
        audience: '30 天未登录用户',
        conversion: '完成首次分享',
        reward: '每邀请 1 人奖励 10 积分',
        budget: '总预算 20,000 积分'
      },
      metrics: {
        visits: 18200,
        shares: 6200,
        conversions: 1200,
        budgetUsed: 15000
      },
      createdAt: iso(-25),
      updatedAt: iso(-2)
    }
  ]
}

export const useActivityStore = defineStore('activities', {
  state: () => ({
    items: safeRead() ?? seedActivities(),
    loading: false
  }),
  getters: {
    byId: (state) => (id: number) => state.items.find((item) => item.id === id) ?? null
  },
  actions: {
    persist() {
      safeWrite(this.items)
    },
    // 从后端加载活动列表
    async fetchFromBackend() {
      if (!isRealMode()) return
      this.loading = true
      try {
        const activities = await activityService.getActivities()
        if (activities && activities.length > 0) {
          this.items = activities as unknown as ActivityItem[]
        }
      } catch (error) {
        console.error('Failed to fetch activities from backend:', error)
      } finally {
        this.loading = false
      }
    },
    async create(item: Omit<ActivityItem, 'id' | 'createdAt' | 'updatedAt'>) {
      // 真实模式下调用后端API
      if (isRealMode()) {
        try {
          // 后端返回Activity对象
          const created = await activityService.createActivity({
            name: item.name,
            description: item.description,
            status: item.status,
            startTime: item.startTime,
            endTime: item.endTime
          })
          if (created && created.id) {
            this.items = [created as unknown as ActivityItem, ...this.items]
            return created as unknown as ActivityItem
          }
        } catch (error) {
          console.error('Failed to create activity on backend:', error)
          // 如果后端创建失败，降级到本地存储
        }
      }
      // 本地存储模式
      const now = new Date().toISOString()
      const nextId = this.items.length ? Math.max(...this.items.map((i) => i.id)) + 1 : 1
      const created: ActivityItem = {
        ...item,
        id: nextId,
        createdAt: now,
        updatedAt: now
      }
      this.items = [created, ...this.items]
      this.persist()
      return created
    },
    async update(id: number, updates: Partial<ActivityItem>) {
      // 真实模式下调用后端API
      if (isRealMode()) {
        try {
          await activityService.updateActivity(id, updates)
          const updated = await activityService.getActivityById(id)
          if (updated) {
            const index = this.items.findIndex((item) => item.id === id)
            if (index >= 0) {
              this.items[index] = updated as unknown as ActivityItem
            }
            return updated as unknown as ActivityItem
          }
        } catch (error) {
          console.error('Failed to update activity on backend:', error)
        }
      }
      // 本地存储模式
      const index = this.items.findIndex((item) => item.id === id)
      if (index < 0) return null
      const updated = {
        ...this.items[index],
        ...updates,
        updatedAt: new Date().toISOString()
      }
      this.items.splice(index, 1, updated)
      this.persist()
      return updated
    },
    async updateStatus(id: number, status: ActivityStatus) {
      // 真实模式下调用后端API
      if (isRealMode()) {
        try {
          switch (status) {
            case 'RUNNING':
              await activityService.publishActivity(id)
              break
            case 'PAUSED':
              await activityService.pauseActivity(id)
              break
            case 'ENDED':
              await activityService.endActivity(id)
              break
          }
          return this.update(id, { status })
        } catch (error) {
          console.error('Failed to update activity status on backend:', error)
        }
      }
      return this.update(id, { status })
    }
  }
})
