import { api } from './common'

export interface NotificationLog {
  name: string
  subject: string
  document_type?: string
  document_name?: string
  link?: string
  from_user: string
  read: number
  creation: string
}

export interface Event {
  name: string
  subject: string
  starts_on: string
  ends_on: string
  all_day: number
  color: string
  location?: string
  participants?: string[]
}

export interface ChangelogFeedItem {
  title: string
  link: string
  app_title: string
  posting_timestamp: string
}

// Get notification logs
export const getNotificationLogs = async (limit: number = 20): Promise<{ 
  success: boolean
  data?: {
    notification_logs: NotificationLog[]
    user_info?: any
  }
  message?: string 
}> => {
  try {
    const result = await api.call(
      'jingrow.desk.pagetype.notification_log.notification_log.get_notification_logs',
      { limit }
    )
    return {
      success: true,
      data: result.message
    }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || 'Failed to fetch notifications'
    }
  }
}

// Mark notification as read
export const markNotificationAsRead = async (docname: string): Promise<{
  success: boolean
  message?: string
}> => {
  try {
    await api.call(
      'jingrow.desk.pagetype.notification_log.notification_log.mark_as_read',
      { docname }
    )
    return { success: true }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || 'Failed to mark as read'
    }
  }
}

// Mark all notifications as read
export const markAllNotificationsAsRead = async (): Promise<{
  success: boolean
  message?: string
}> => {
  try {
    await api.call(
      'jingrow.desk.pagetype.notification_log.notification_log.mark_all_as_read'
    )
    return { success: true }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || 'Failed to mark all as read'
    }
  }
}

// Get today's events
export const getTodaysEvents = async (): Promise<{
  success: boolean
  data?: Event[]
  message?: string
}> => {
  try {
    // Get today's date in YYYY-MM-DD format
    const today = new Date().toISOString().split('T')[0]
    
    const result = await api.call(
      'jingrow.desk.pagetype.event.event.get_events',
      {
        start: today,
        end: today
      }
    )
    return {
      success: true,
      data: result.message || result || []
    }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || 'Failed to fetch events'
    }
  }
}

// Trigger indicator hide
export const triggerIndicatorHide = async (): Promise<{
  success: boolean
  message?: string
}> => {
  try {
    await api.call(
      'jingrow.desk.pagetype.notification_log.notification_log.trigger_indicator_hide'
    )
    return { success: true }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || 'Failed to trigger indicator hide'
    }
  }
}

// Set seen value
export const setNotificationSeenValue = async (value: number, user: string): Promise<{
  success: boolean
  message?: string
}> => {
  try {
    await api.call(
      'jingrow.desk.pagetype.notification_settings.notification_settings.set_seen_value',
      { value, user }
    )
    return { success: true }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || 'Failed to set seen value'
    }
  }
}

// Get notification settings for current user
export const getNotificationSettings = async (user: string): Promise<{
  success: boolean
  data?: any
  message?: string
}> => {
  try {
    const result = await api.call(
      'jingrow.client.get_value',
      {
        pagetype: 'Notification Settings',
        filters: { name: user },
        fieldname: ['enabled', 'seen']
      }
    )
    return {
      success: true,
      data: result.message || { enabled: 1, seen: 0 }
    }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || 'Failed to get notification settings'
    }
  }
}

// Get changelog feed items
export const getChangelogFeed = async (): Promise<{
  success: boolean
  data?: ChangelogFeedItem[]
  message?: string
}> => {
  try {
    // Use jingrow.client.get_list which is always whitelisted
    const result = await api.call(
      'jingrow.client.get_list',
      {
        pagetype: 'Changelog Feed',
        fields: ['title', 'app_name', 'link', 'posting_timestamp'],
        order_by: 'posting_timestamp desc',
        limit_page_length: 20
      }
    )
    
    const feed = result.message || []
    // Add app_title for each item
    feed.forEach((f: any) => {
      f.app_title = f.app_name
    })
    
    return {
      success: true,
      data: feed
    }
  } catch (error: any) {
    return {
      success: false,
      data: [],
      message: error.message || 'Failed to get changelog feed'
    }
  }
}
