import { Router, Request, Response } from 'express'
import { db } from '../config/database'
import { authenticateToken, AuthRequest } from '../middleware/auth'
import { v4 as uuidv4 } from 'uuid'
import { Workspace, WorkspaceFilter } from '@skillmate/shared'

const router = Router()

// Get all workspaces with optional filters
router.get('/', authenticateToken, (req: AuthRequest, res: Response) => {
  try {
    const filters: WorkspaceFilter = req.query
    let query = 'SELECT * FROM workspaces WHERE is_active = 1'
    const params: any[] = []

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

    if (filters.floor) {
      query += ' AND floor = ?'
      params.push(filters.floor)
    }

    if (filters.building) {
      query += ' AND building = ?'
      params.push(filters.building)
    }

    if (filters.min_capacity) {
      query += ' AND capacity >= ?'
      params.push(filters.min_capacity)
    }

    query += ' ORDER BY floor, name'

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

    // Parse equipment JSON
    const parsedWorkspaces = workspaces.map((ws: any) => ({
      ...ws,
      equipment: ws.equipment ? JSON.parse(ws.equipment) : [],
      is_active: Boolean(ws.is_active)
    }))

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

// Get available workspaces for a time range
router.post('/availability', authenticateToken, (req: AuthRequest, res: Response) => {
  try {
    const { start_time, end_time, type, capacity } = req.body

    if (!start_time || !end_time) {
      return res.status(400).json({ error: 'Start and end time required' })
    }

    let query = `
      SELECT w.* FROM workspaces w
      WHERE w.is_active = 1
      AND w.id NOT IN (
        SELECT DISTINCT workspace_id FROM bookings
        WHERE status = 'confirmed'
        AND (
          (start_time <= ? AND end_time > ?)
          OR (start_time < ? AND end_time >= ?)
          OR (start_time >= ? AND end_time <= ?)
        )
      )
    `
    const params = [start_time, start_time, end_time, end_time, start_time, end_time]

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

    if (capacity) {
      query += ' AND w.capacity >= ?'
      params.push(capacity)
    }

    query += ' ORDER BY w.floor, w.name'

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

    // Parse equipment JSON
    const parsedWorkspaces = availableWorkspaces.map((ws: any) => ({
      ...ws,
      equipment: ws.equipment ? JSON.parse(ws.equipment) : [],
      is_active: Boolean(ws.is_active)
    }))

    res.json(parsedWorkspaces)
  } catch (error) {
    console.error('Error checking availability:', error)
    res.status(500).json({ error: 'Failed to check availability' })
  }
})

// Get workspace by ID
router.get('/:id', authenticateToken, (req: AuthRequest, res: Response) => {
  try {
    const workspace = db.prepare('SELECT * FROM workspaces WHERE id = ?').get(req.params.id)
    
    if (!workspace) {
      return res.status(404).json({ error: 'Workspace not found' })
    }

    // Parse equipment JSON
    const parsedWorkspace = {
      ...(workspace as any),
      equipment: (workspace as any).equipment ? JSON.parse((workspace as any).equipment) : [],
      is_active: Boolean((workspace as any).is_active)
    }

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

// Create new workspace (admin only)
router.post('/', authenticateToken, (req: AuthRequest, res: Response) => {
  if (req.user?.role !== 'admin') {
    return res.status(403).json({ error: 'Admin access required' })
  }

  try {
    const {
      name,
      type,
      floor,
      building,
      capacity = 1,
      equipment = [],
      position_x,
      position_y
    } = req.body

    if (!name || !type || !floor) {
      return res.status(400).json({ error: 'Name, type, and floor are required' })
    }

    const id = uuidv4()
    const now = new Date().toISOString()

    db.prepare(`
      INSERT INTO workspaces (
        id, name, type, floor, building, capacity, equipment,
        position_x, position_y, is_active, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `).run(
      id, name, type, floor, building, capacity,
      JSON.stringify(equipment), position_x, position_y,
      1, now, now
    )

    const newWorkspace = db.prepare('SELECT * FROM workspaces WHERE id = ?').get(id)
    
    res.status(201).json({
      ...(newWorkspace as any),
      equipment: JSON.parse((newWorkspace as any).equipment || '[]'),
      is_active: Boolean((newWorkspace as any).is_active)
    })
  } catch (error) {
    console.error('Error creating workspace:', error)
    res.status(500).json({ error: 'Failed to create workspace' })
  }
})

// Update workspace (admin only)
router.put('/:id', authenticateToken, (req: AuthRequest, res: Response) => {
  if (req.user?.role !== 'admin') {
    return res.status(403).json({ error: 'Admin access required' })
  }

  try {
    const {
      name,
      type,
      floor,
      building,
      capacity,
      equipment,
      position_x,
      position_y,
      is_active
    } = req.body

    const existing = db.prepare('SELECT * FROM workspaces WHERE id = ?').get(req.params.id)
    if (!existing) {
      return res.status(404).json({ error: 'Workspace not found' })
    }

    const updates = []
    const params = []

    if (name !== undefined) {
      updates.push('name = ?')
      params.push(name)
    }
    if (type !== undefined) {
      updates.push('type = ?')
      params.push(type)
    }
    if (floor !== undefined) {
      updates.push('floor = ?')
      params.push(floor)
    }
    if (building !== undefined) {
      updates.push('building = ?')
      params.push(building)
    }
    if (capacity !== undefined) {
      updates.push('capacity = ?')
      params.push(capacity)
    }
    if (equipment !== undefined) {
      updates.push('equipment = ?')
      params.push(JSON.stringify(equipment))
    }
    if (position_x !== undefined) {
      updates.push('position_x = ?')
      params.push(position_x)
    }
    if (position_y !== undefined) {
      updates.push('position_y = ?')
      params.push(position_y)
    }
    if (is_active !== undefined) {
      updates.push('is_active = ?')
      params.push(is_active ? 1 : 0)
    }

    updates.push('updated_at = ?')
    params.push(new Date().toISOString())

    params.push(req.params.id)

    db.prepare(`
      UPDATE workspaces
      SET ${updates.join(', ')}
      WHERE id = ?
    `).run(...params)

    const updated = db.prepare('SELECT * FROM workspaces WHERE id = ?').get(req.params.id)
    
    res.json({
      ...(updated as any),
      equipment: JSON.parse((updated as any).equipment || '[]'),
      is_active: Boolean((updated as any).is_active)
    })
  } catch (error) {
    console.error('Error updating workspace:', error)
    res.status(500).json({ error: 'Failed to update workspace' })
  }
})

// Delete workspace (admin only)
router.delete('/:id', authenticateToken, (req: AuthRequest, res: Response) => {
  if (req.user?.role !== 'admin') {
    return res.status(403).json({ error: 'Admin access required' })
  }

  try {
    // Check if workspace has active bookings
    const activeBookings = db.prepare(`
      SELECT COUNT(*) as count FROM bookings
      WHERE workspace_id = ? AND status = 'confirmed'
      AND end_time > ?
    `).get(req.params.id, new Date().toISOString())

    if ((activeBookings as any).count > 0) {
      return res.status(400).json({ 
        error: 'Cannot delete workspace with active bookings' 
      })
    }

    // Soft delete by setting is_active = 0
    db.prepare(`
      UPDATE workspaces SET is_active = 0, updated_at = ?
      WHERE id = ?
    `).run(new Date().toISOString(), req.params.id)

    res.json({ message: 'Workspace deleted successfully' })
  } catch (error) {
    console.error('Error deleting workspace:', error)
    res.status(500).json({ error: 'Failed to delete workspace' })
  }
})

export default router