import { Controller, Get, Post, Body, Query, UseGuards } from "@nestjs/common"
import {
  ApiBearerAuth,
  ApiTags,
  ApiQuery,
  ApiOperation,
  ApiResponse,
  ApiBody,
} from "@nestjs/swagger"
import { AuthGuardMiddleware } from "src/middleware/auth-guard.middleware"
import { TeamMemberService } from "./team-member.service"
import { SendMessageDto } from "../../chat/dto/send-message.dto"
import {
  ChatMessageResponseDto,
  ChatHistoryResponseDto,
  MarkMessagesReadResponseDto,
} from "../../chat/dto/chat-message-response.dto"
import { ChatContactsResponseDto } from "../dto/chat-contacts-response.dto"

@ApiTags("Dispatcher")
@UseGuards(AuthGuardMiddleware)
@ApiBearerAuth("access-token")
@Controller("dispatcher")
export class DispatcherController {
  constructor(private readonly dispatcherService: TeamMemberService) {}

  @ApiQuery({ name: "dispatcher_id", type: Number })
  @Get("get-dispatcher-profile-details")
  async getDispatcherProfileDetails(
    @Query("dispatcher_id") dispatcherId: number,
  ) {
    return await this.dispatcherService.getDispatcherProfileDetails(
      dispatcherId,
    )
  }

  @ApiQuery({ name: "dispatcher_id", type: Number })
  @Get("home-page-counts")
  async getHomePageCounts(@Query("dispatcher_id") dispatcherId: number) {
    return await this.dispatcherService.getHomePageCounts(dispatcherId)
  }

  @ApiQuery({ name: "dispatcher_id", type: Number })
  @ApiQuery({
    name: "type",
    required: false,
    enum: ["ongoing", "upcoming", "requested", "past", "active"],
    enumName: "TripType",
  })
  @ApiQuery({ name: "limit", required: false, type: Number })
  @ApiQuery({ name: "skip", required: false, type: Number })
  @ApiQuery({
    name: "past_type",
    required: false,
    enum: ["completed", "cancelled", "all"],
    enumName: "PastTripType",
  })
  @ApiQuery({
    name: "sortkey",
    required: false,
    type: String,
    description: "Column to sort by (default: pickup_datetime)",
    example: "pickup_datetime",
  })
  @ApiQuery({
    name: "sortorder",
    required: false,
    type: String,
    enum: ["ASC", "DESC"],
    description: "Sort order (default: DESC)",
    example: "DESC",
  })
  @Get("trips")
  async getDispatcherTrips(
    @Query("dispatcher_id") dispatcherId: number,
    @Query("type")
    tripType?: "ongoing" | "upcoming" | "requested" | "past" | "active",
    @Query("limit") limit?: number,
    @Query("skip") skip?: number,
    @Query("past_type") pastTripType?: "completed" | "cancelled" | "all",
    @Query("sortkey") sortKey?: string,
    @Query("sortorder") sortOrder?: "ASC" | "DESC",
  ) {
    return await this.dispatcherService.getDispatcherTrips(
      dispatcherId,
      tripType,
      limit || 10,
      skip || 0,
      pastTripType,
      sortKey,
      sortOrder,
    )
  }

  @ApiQuery({ name: "dispatcher_id", type: Number })
  @Get("drivers")
  async getDispatcherDrivers(@Query("dispatcher_id") dispatcherId: number) {
    return await this.dispatcherService.getDispatchersWiseDrivers({
      dispatcher_id: dispatcherId,
    } as any)
  }

  @ApiOperation({
    summary: "Send message to driver",
    description: "Allows dispatcher to send chat messages to assigned drivers",
  })
  @ApiQuery({ name: "dispatcher_id", type: Number })
  @ApiBody({ type: SendMessageDto })
  @ApiResponse({
    status: 200,
    description: "Message sent successfully",
    type: ChatMessageResponseDto,
  })
  @ApiResponse({
    status: 400,
    description: "Bad request - validation error",
  })
  @ApiResponse({
    status: 404,
    description: "Driver not found or not assigned to dispatcher",
  })
  @Post("send-message")
  async sendMessageToDriver(
    @Query("dispatcher_id") dispatcherId: number,
    @Body() sendMessageDto: SendMessageDto,
  ) {
    return await this.dispatcherService.sendMessageToDriver(
      dispatcherId,
      sendMessageDto,
    )
  }

  @ApiOperation({
    summary: "Get chat history",
    description: "Retrieve chat message history for a specific chat room",
  })
  @ApiBody({
    schema: {
      type: "object",
      properties: {
        current_user_id: { type: "number" },
        current_user_type: { type: "string" },
        target_user_id: { type: "number" },
        target_user_type: { type: "string" },
        trip_id: { type: "number", nullable: true },
      },
      required: [
        "current_user_id",
        "current_user_type",
        "target_user_id",
        "target_user_type",
      ],
    },
  })
  @ApiResponse({
    status: 200,
    description: "Chat history retrieved successfully",
    type: ChatHistoryResponseDto,
  })
  @ApiResponse({
    status: 400,
    description: "Bad request - validation error",
  })
  @Post("chat-history")
  async getChatHistory(
    @Body()
    chatHistoryDto: {
      current_user_id: number
      current_user_type: string
      target_user_id: number
      target_user_type: string
      trip_id?: number
    },
  ) {
    return await this.dispatcherService.getChatRoom(chatHistoryDto)
  }

  @ApiOperation({
    summary: "Mark messages as read",
    description: "Mark chat messages as read for a specific chat room",
  })
  @ApiBody({
    schema: {
      type: "object",
      properties: {
        driver_id: { type: "number", example: 123 },
        chat_room_id: { type: "number", example: 456 },
      },
      required: ["driver_id", "chat_room_id"],
    },
  })
  @ApiResponse({
    status: 200,
    description: "Messages marked as read successfully",
    type: MarkMessagesReadResponseDto,
  })
  @ApiResponse({
    status: 400,
    description: "Bad request - validation error",
  })
  @Post("mark-messages-read")
  async markMessagesAsRead(
    @Body() data: { driver_id: number; chat_room_id: number },
  ) {
    return await this.dispatcherService.markMessagesAsRead(
      data.driver_id,
      data.chat_room_id,
    )
  }

  @ApiOperation({
    summary: "Get dispatcher chat contacts",
    description:
      "Get list of drivers or customers that the dispatcher has chatted with",
  })
  @ApiQuery({ name: "dispatcher_id", type: Number, required: true })
  @ApiQuery({
    name: "type",
    enum: ["driver", "customer"],
    required: true,
    description: "Type of contacts to retrieve",
  })
  @ApiResponse({
    status: 200,
    description: "Chat contacts retrieved successfully",
    type: ChatContactsResponseDto,
  })
  @ApiResponse({
    status: 400,
    description: "Bad request - validation error",
  })
  @Get("chat-contacts")
  async getDispatcherChatContacts(
    @Query("dispatcher_id") dispatcherId: number,
    @Query("type") type: "driver" | "customer",
  ) {
    return await this.dispatcherService.getDispatcherChatContacts(
      dispatcherId,
      type,
    )
  }
}
