import { Controller, Get, Put, Body } from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
} from '@nestjs/swagger';
import { DashboardService } from './dashboard.service';
import { UpdateLayoutDto } from './dto/dashboard-layout.dto';
import { CurrentUser } from '../../auth/decorators/current-user.decorator';
import { JwtPayload } from '../../auth/interfaces/jwt-payload.interface';
import { RequirePermissions } from '../../auth/permissions/permissions.decorator';
import { Permission } from '../../auth/permissions/permissions.enum';

@ApiTags('dashboard')
@ApiBearerAuth('JWT-auth')
@Controller('dashboard')
export class DashboardController {
  constructor(private readonly dashboardService: DashboardService) {}

  @Get('stats')
  @RequirePermissions(Permission.DASHBOARD_VIEW)
  @ApiOperation({ summary: 'Get dashboard statistics (role-filtered)' })
  @ApiResponse({
    status: 200,
    description: 'Dashboard statistics retrieved successfully (filtered by role)',
    schema: {
      type: 'object',
      properties: {
        users: {
          type: 'object',
          description: 'Only visible for admin/manager',
          properties: {
            total: { type: 'number', example: 150 },
            active: { type: 'number', example: 142 },
            newThisMonth: { type: 'number', example: 5 },
          },
        },
        departments: {
          type: 'object',
          properties: {
            total: { type: 'number', example: 12 },
            active: { type: 'number', example: 10 },
          },
        },
        employees: {
          type: 'object',
          description: 'Only visible for admin/manager',
          properties: {
            total: { type: 'number', example: 120 },
            active: { type: 'number', example: 115 },
          },
        },
        absences: {
          type: 'object',
          description: 'Scoped by role - admin/manager see all, dept head sees department',
          properties: {
            pending: { type: 'number', example: 8 },
            approved: { type: 'number', example: 45 },
            total: { type: 'number', example: 53 },
          },
        },
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  getStats(@CurrentUser() user: JwtPayload) {
    return this.dashboardService.getStats(user.sub, user.roles || []);
  }

  @Get('widgets')
  @RequirePermissions(Permission.DASHBOARD_VIEW)
  @ApiOperation({ summary: 'Get available widget types' })
  @ApiResponse({
    status: 200,
    description: 'List of available widget types',
    schema: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          id: { type: 'string', example: 'statistics' },
          name: { type: 'string', example: 'Statistics Overview' },
          description: { type: 'string', example: 'Display key metrics' },
          minWidth: { type: 'number', example: 2 },
          minHeight: { type: 'number', example: 1 },
          maxWidth: { type: 'number', example: 4 },
          maxHeight: { type: 'number', example: 2 },
          category: { type: 'string', example: 'overview' },
          requiredPermissions: {
            type: 'array',
            items: { type: 'string' },
            example: ['audit:view'],
          },
        },
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  getWidgets() {
    return this.dashboardService.getWidgetTypes();
  }

  @Get('layout')
  @RequirePermissions(Permission.DASHBOARD_VIEW)
  @ApiOperation({ summary: "Get user's dashboard layout" })
  @ApiResponse({
    status: 200,
    description: 'Dashboard layout retrieved successfully',
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  getLayout(@CurrentUser() user: JwtPayload) {
    return this.dashboardService.getLayout(user.sub);
  }

  @Put('layout')
  @RequirePermissions(Permission.DASHBOARD_CUSTOMIZE)
  @ApiOperation({ summary: "Save user's dashboard layout" })
  @ApiResponse({
    status: 200,
    description: 'Dashboard layout saved successfully',
  })
  @ApiResponse({ status: 400, description: 'Bad request' })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  saveLayout(
    @CurrentUser() user: JwtPayload,
    @Body() updateDto: UpdateLayoutDto,
  ) {
    return this.dashboardService.saveLayout(user.sub, updateDto.layout);
  }

  @Get('activity')
  @RequirePermissions(Permission.DASHBOARD_VIEW)
  @ApiOperation({ summary: 'Get recent activity for dashboard (role-filtered)' })
  @ApiResponse({
    status: 200,
    description: 'Recent activity retrieved successfully (admins see all, others see own)',
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  getActivity(@CurrentUser() user: JwtPayload) {
    return this.dashboardService.getRecentActivity(user.sub, user.roles || []);
  }

  @Get('absences/upcoming')
  @RequirePermissions(Permission.ABSENCES_VIEW)
  @ApiOperation({ summary: 'Get upcoming absences for dashboard (role-filtered)' })
  @ApiResponse({
    status: 200,
    description: 'Upcoming absences retrieved successfully (scoped by role)',
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  getUpcomingAbsences(@CurrentUser() user: JwtPayload) {
    return this.dashboardService.getUpcomingAbsences(user.sub, user.roles || []);
  }

  @Get('approvals/pending/count')
  @RequirePermissions(Permission.ABSENCES_APPROVE)
  @ApiOperation({ summary: 'Get pending approvals count' })
  @ApiResponse({
    status: 200,
    description: 'Pending approvals count',
    schema: {
      type: 'object',
      properties: {
        count: { type: 'number', example: 5 },
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  async getPendingApprovalsCount() {
    const count = await this.dashboardService.getPendingApprovalsCount();
    return { count };
  }
}
