import { NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { queryJobPanelDb, initializeJobPanelDatabase } from '@/lib/job-panel-db'
import { getAllJobs, getJobEmployeeCount } from '@/lib/services/job-adapter'
import { logJobPanel } from '@/lib/services/admin-logging'
import { v4 as uuidv4 } from 'uuid'
import type { RowDataPacket } from 'mysql2'

// Feature definitions
export const PANEL_FEATURES = [
  { key: 'criminal_records', label: 'Criminal Records / Files', icon: 'file-text', description: 'Create and manage criminal records' },
  { key: 'employee_management', label: 'Employee Management', icon: 'users', description: 'Manage faction employees' },
  { key: 'rank_management', label: 'Rank Management', icon: 'award', description: 'Configure rank permissions' },
  { key: 'vehicle_management', label: 'Vehicle Management', icon: 'car', description: 'Track faction vehicles' },
  { key: 'inventory_access', label: 'Inventory Access', icon: 'package', description: 'View player inventories' },
  { key: 'dispatch_logs', label: 'Dispatch / Activity Logs', icon: 'radio', description: 'Track faction activities' },
  { key: 'billing_invoices', label: 'Billing / Invoices', icon: 'file-invoice', description: 'Create and manage invoices' },
  { key: 'storage_management', label: 'Storage Management', icon: 'warehouse', description: 'Manage faction storage' },
  { key: 'notes_system', label: 'Custom Notes System', icon: 'sticky-note', description: 'Create internal notes' },
  { key: 'duty_tracking', label: 'Duty Tracking', icon: 'clock', description: 'Track employee duty time' },
  { key: 'live_overview', label: 'Live Activity Overview', icon: 'activity', description: 'Real-time faction status' },
] as const

// GET - List all job panels or available jobs
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const action = searchParams.get('action')

    // Features endpoint doesn't need auth - return early
    if (action === 'features') {
      return NextResponse.json({ features: PANEL_FEATURES })
    }

    const session = await getSession()
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Initialize database if needed
    await initializeJobPanelDatabase()

    if (action === 'available-jobs') {
      // Get all jobs from game database
      const jobs = await getAllJobs()
      
      // Get existing panels
      const panels = await queryJobPanelDb<RowDataPacket[]>(
        'SELECT job_name FROM job_panels'
      )
      const existingJobNames = new Set(panels.map(p => p.job_name))

      // Get employee counts
      const jobsWithData = await Promise.all(
        jobs.map(async (job) => ({
          ...job,
          employeeCount: await getJobEmployeeCount(job.name),
          hasPanel: existingJobNames.has(job.name),
        }))
      )

      return NextResponse.json({ jobs: jobsWithData })
    }

    // Get all panels
    const panels = await queryJobPanelDb<RowDataPacket[]>(`
      SELECT 
        jp.*,
        (SELECT COUNT(*) FROM job_panel_features WHERE panel_id = jp.id AND is_enabled = TRUE) as enabled_features,
        (SELECT COUNT(*) FROM job_panel_members WHERE panel_id = jp.id) as member_count
      FROM job_panels jp
      ORDER BY jp.created_at DESC
    `)

    // Get employee counts for each panel
    const panelsWithData = await Promise.all(
      panels.map(async (panel) => ({
        id: panel.id,
        jobName: panel.job_name,
        jobLabel: panel.job_label,
        panelName: panel.panel_name,
        description: panel.description,
        icon: panel.icon,
        isActive: panel.is_active === 1,
        enabledFeatures: panel.enabled_features,
        memberCount: panel.member_count,
        employeeCount: await getJobEmployeeCount(panel.job_name),
        createdAt: panel.created_at,
      }))
    )

    return NextResponse.json({ panels: panelsWithData })
  } catch (error) {
    console.error('[JobPanels] GET error:', error)
    return NextResponse.json({ error: 'Failed to fetch job panels' }, { status: 500 })
  }
}

// POST - Create a new job panel
export async function POST(request: NextRequest) {
  try {
    const session = await getSession()
    if (!session || session.role !== 'SUPERADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await request.json()
    const { jobName, jobLabel, panelName, description, icon, features } = body

    if (!jobName || !panelName) {
      return NextResponse.json({ error: 'Job name and panel name are required' }, { status: 400 })
    }

    // Initialize database
    const initResult = await initializeJobPanelDatabase()
    if (!initResult.success) {
      console.error('[JobPanels] Database init failed:', initResult.error)
      return NextResponse.json({ 
        error: `Database initialization failed: ${initResult.error}. Please configure the game database first.` 
      }, { status: 500 })
    }

    // Check if panel already exists
    const existing = await queryJobPanelDb<RowDataPacket[]>(
      'SELECT id FROM job_panels WHERE job_name = ?',
      [jobName]
    )

    if (existing.length > 0) {
      return NextResponse.json({ error: 'A panel for this job already exists' }, { status: 400 })
    }

    // Create panel
    const panelId = uuidv4()
    await queryJobPanelDb(
      `INSERT INTO job_panels (id, job_name, job_label, panel_name, description, icon, created_by, created_by_name)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [panelId, jobName, jobLabel || jobName, panelName, description || null, icon || 'briefcase', session.userId, session.username]
    )

    // Create webhook settings entry
    await queryJobPanelDb(
      'INSERT INTO job_panel_webhooks (id, panel_id) VALUES (?, ?)',
      [uuidv4(), panelId]
    )

    // Create feature entries
    if (features && Array.isArray(features)) {
      for (const feature of PANEL_FEATURES) {
        const isEnabled = features.includes(feature.key)
        await queryJobPanelDb(
          'INSERT INTO job_panel_features (id, panel_id, feature_key, is_enabled) VALUES (?, ?, ?, ?)',
          [uuidv4(), panelId, feature.key, isEnabled]
        )
      }
    } else {
      // Create all features as disabled by default
      for (const feature of PANEL_FEATURES) {
        await queryJobPanelDb(
          'INSERT INTO job_panel_features (id, panel_id, feature_key, is_enabled) VALUES (?, ?, ?, ?)',
          [uuidv4(), panelId, feature.key, false]
        )
      }
    }

    // Log the panel creation (fire-and-forget, don't await)
    logJobPanel('PANEL_CREATED', {
      panelId,
      panelName,
      jobName,
      features: features || [],
    })

    return NextResponse.json({ 
      success: true, 
      panelId,
      message: 'Job panel created successfully' 
    })
  } catch (error) {
    console.error('[JobPanels] POST error:', error)
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    return NextResponse.json({ 
      error: `Failed to create job panel: ${errorMessage}` 
    }, { status: 500 })
  }
}
