import { Router } from 'express'
import { db } from '../config/database'
import { authenticateToken, AuthRequest } from '../middleware/auth'

const router = Router()

// Get workspace utilization analytics
router.get('/workspace-utilization', authenticateToken, (req: AuthRequest, res) => {
  if (!['admin', 'superuser'].includes(req.user!.role)) {
    return res.status(403).json({ error: 'Insufficient permissions' })
  }

  try {
    const { from_date, to_date, workspace_id, workspace_type } = req.query

    let query = `
      SELECT 
        wa.*,
        w.name as workspace_name,
        w.type as workspace_type,
        w.floor,
        w.building
      FROM workspace_analytics wa
      JOIN workspaces w ON wa.workspace_id = w.id
      WHERE 1=1
    `
    const params: any[] = []

    if (from_date) {
      query += ' AND wa.date >= ?'
      params.push(from_date)
    }

    if (to_date) {
      query += ' AND wa.date <= ?'
      params.push(to_date)
    }

    if (workspace_id) {
      query += ' AND wa.workspace_id = ?'
      params.push(workspace_id)
    }

    if (workspace_type) {
      query += ' AND w.type = ?'
      params.push(workspace_type)
    }

    query += ' ORDER BY wa.date DESC'

    const analytics = db.prepare(query).all(...params)

    res.json(analytics)
  } catch (error) {
    console.error('Error fetching analytics:', error)
    res.status(500).json({ error: 'Failed to fetch analytics' })
  }
})

// Get overall statistics
router.get('/overview', authenticateToken, (req: AuthRequest, res) => {
  if (!['admin', 'superuser'].includes(req.user!.role)) {
    return res.status(403).json({ error: 'Insufficient permissions' })
  }

  try {
    const { from_date = new Date().toISOString().split('T')[0], to_date } = req.query

    // Total workspaces by type
    const workspaceStats = db.prepare(`
      SELECT type, COUNT(*) as count 
      FROM workspaces 
      WHERE is_active = 1 
      GROUP BY type
    `).all()

    // Booking statistics
    const bookingStats = db.prepare(`
      SELECT 
        COUNT(*) as total_bookings,
        COUNT(DISTINCT user_id) as unique_users,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_bookings,
        SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_bookings,
        SUM(CASE WHEN status = 'no_show' THEN 1 ELSE 0 END) as no_shows
      FROM bookings
      WHERE start_time >= ?
      ${to_date ? 'AND end_time <= ?' : ''}
    `).get(from_date, ...(to_date ? [to_date] : []))

    // Average utilization by workspace type
    const utilizationByType = db.prepare(`
      SELECT 
        w.type,
        AVG(wa.utilization_rate) as avg_utilization,
        AVG(wa.total_hours_booked) as avg_hours_booked
      FROM workspace_analytics wa
      JOIN workspaces w ON wa.workspace_id = w.id
      WHERE wa.date >= ?
      ${to_date ? 'AND wa.date <= ?' : ''}
      GROUP BY w.type
    `).all(from_date, ...(to_date ? [to_date] : []))

    // Popular workspaces
    const popularWorkspaces = db.prepare(`
      SELECT 
        w.id,
        w.name,
        w.type,
        w.floor,
        COUNT(b.id) as booking_count,
        AVG(
          CAST((julianday(b.end_time) - julianday(b.start_time)) * 24 AS REAL)
        ) as avg_duration_hours
      FROM workspaces w
      JOIN bookings b ON w.id = b.workspace_id
      WHERE b.start_time >= ?
      ${to_date ? 'AND b.end_time <= ?' : ''}
      AND b.status != 'cancelled'
      GROUP BY w.id, w.name, w.type, w.floor
      ORDER BY booking_count DESC
      LIMIT 10
    `).all(from_date, ...(to_date ? [to_date] : []))

    // Peak hours analysis
    const peakHours = db.prepare(`
      SELECT 
        CAST(strftime('%H', start_time) AS INTEGER) as hour,
        COUNT(*) as booking_count
      FROM bookings
      WHERE start_time >= ?
      ${to_date ? 'AND end_time <= ?' : ''}
      AND status != 'cancelled'
      GROUP BY hour
      ORDER BY hour
    `).all(from_date, ...(to_date ? [to_date] : []))

    res.json({
      workspace_stats: workspaceStats,
      booking_stats: bookingStats,
      utilization_by_type: utilizationByType,
      popular_workspaces: popularWorkspaces,
      peak_hours: peakHours,
      date_range: {
        from: from_date,
        to: to_date || new Date().toISOString().split('T')[0]
      }
    })
  } catch (error) {
    console.error('Error fetching overview:', error)
    res.status(500).json({ error: 'Failed to fetch overview' })
  }
})

// Update analytics data (should be run by a scheduled job)
router.post('/update', authenticateToken, (req: AuthRequest, res) => {
  if (req.user!.role !== 'admin') {
    return res.status(403).json({ error: 'Admin access required' })
  }

  try {
    const date = req.body.date || new Date().toISOString().split('T')[0]

    // Calculate analytics for each workspace
    const workspaces = db.prepare('SELECT id FROM workspaces WHERE is_active = 1').all()

    for (const workspace of workspaces) {
      const dayStart = `${date}T00:00:00.000Z`
      const dayEnd = `${date}T23:59:59.999Z`

      // Get booking statistics for the day
      const stats = db.prepare(`
        SELECT 
          COUNT(*) as total_bookings,
          COUNT(DISTINCT user_id) as unique_users,
          SUM(
            CASE 
              WHEN status = 'no_show' OR (status = 'confirmed' AND check_in_time IS NULL AND end_time < ?)
              THEN 1 
              ELSE 0 
            END
          ) as no_show_count,
          SUM(
            CAST((julianday(end_time) - julianday(start_time)) * 24 AS REAL)
          ) as total_hours_booked
        FROM bookings
        WHERE workspace_id = ?
        AND start_time >= ? AND start_time <= ?
        AND status != 'cancelled'
      `).get(new Date().toISOString(), (workspace as any).id, dayStart, dayEnd)

      // Calculate peak hour
      const peakHour = db.prepare(`
        SELECT 
          CAST(strftime('%H', start_time) AS INTEGER) as hour,
          COUNT(*) as count
        FROM bookings
        WHERE workspace_id = ?
        AND start_time >= ? AND start_time <= ?
        AND status != 'cancelled'
        GROUP BY hour
        ORDER BY count DESC
        LIMIT 1
      `).get((workspace as any).id, dayStart, dayEnd)

      // Calculate utilization rate (assuming 10 hour work day)
      const workHoursPerDay = 10
      const utilizationRate = (stats as any).total_hours_booked / workHoursPerDay

      // Insert or update analytics record
      db.prepare(`
        INSERT OR REPLACE INTO workspace_analytics (
          id, workspace_id, date, total_bookings, total_hours_booked,
          utilization_rate, no_show_count, unique_users, peak_hour
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
      `).run(
        `${(workspace as any).id}-${date}`,
        (workspace as any).id,
        date,
        (stats as any).total_bookings || 0,
        (stats as any).total_hours_booked || 0,
        utilizationRate || 0,
        (stats as any).no_show_count || 0,
        (stats as any).unique_users || 0,
        (peakHour as any)?.hour || null
      )
    }

    res.json({ message: 'Analytics updated successfully' })
  } catch (error) {
    console.error('Error updating analytics:', error)
    res.status(500).json({ error: 'Failed to update analytics' })
  }
})

export default router