import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  Request,
  ParseIntPipe,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { PublicService } from './public.service';
import { UserWorksService } from './user-works.service';
import { CreationService } from './creation.service';
import { TagsService } from './tags.service';
import { GalleryService } from './gallery.service';
import { PublicRegisterDto, PublicLoginDto } from './dto/register.dto';
import { CreateChildDto, UpdateChildDto } from './dto/child.dto';
import { PublicRegisterActivityDto } from './dto/registration.dto';
import { Public } from '../auth/decorators/public.decorator';

@Controller('public')
export class PublicController {
  constructor(
    private readonly publicService: PublicService,
    private readonly userWorksService: UserWorksService,
    private readonly creationService: CreationService,
    private readonly tagsService: TagsService,
    private readonly galleryService: GalleryService,
  ) {}

  // ==================== 注册 & 登录（公开接口） ====================

  @Public()
  @Post('auth/register')
  async register(@Body() dto: PublicRegisterDto) {
    return this.publicService.register(dto);
  }

  @Public()
  @Post('auth/login')
  async login(@Body() dto: PublicLoginDto) {
    return this.publicService.login(dto);
  }

  // ==================== 个人信息（需要登录） ====================

  @UseGuards(AuthGuard('jwt'))
  @Get('mine/profile')
  async getProfile(@Request() req) {
    return this.publicService.getUserInfo(req.user.userId);
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('mine/profile')
  async updateProfile(
    @Request() req,
    @Body() data: { nickname?: string; city?: string; avatar?: string; gender?: string },
  ) {
    return this.publicService.updateProfile(req.user.userId, data);
  }

  // ==================== 子女管理（需要登录） ====================

  @UseGuards(AuthGuard('jwt'))
  @Get('mine/children')
  async getChildren(@Request() req) {
    return this.publicService.getChildren(req.user.userId);
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('mine/children')
  async createChild(@Request() req, @Body() dto: CreateChildDto) {
    return this.publicService.createChild(req.user.userId, dto);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('mine/children/:id')
  async getChild(@Request() req, @Param('id', ParseIntPipe) id: number) {
    return this.publicService.getChild(req.user.userId, id);
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('mine/children/:id')
  async updateChild(
    @Request() req,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: UpdateChildDto,
  ) {
    return this.publicService.updateChild(req.user.userId, id, dto);
  }

  @UseGuards(AuthGuard('jwt'))
  @Delete('mine/children/:id')
  async deleteChild(@Request() req, @Param('id', ParseIntPipe) id: number) {
    return this.publicService.deleteChild(req.user.userId, id);
  }

  // ==================== 子女独立账号管理（需要登录） ====================

  @UseGuards(AuthGuard('jwt'))
  @Post('children/create-account')
  async createChildAccount(@Request() req, @Body() dto: {
    username: string;
    password: string;
    nickname: string;
    gender?: string;
    birthday?: string;
    city?: string;
    avatar?: string;
    relationship?: string;
  }) {
    return this.publicService.createChildAccount(req.user.userId, dto);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('children/accounts')
  async getChildAccounts(@Request() req) {
    return this.publicService.getChildAccounts(req.user.userId);
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('auth/switch-child')
  async switchToChild(@Request() req, @Body() dto: { childUserId: number }) {
    return this.publicService.switchToChild(req.user.userId, dto.childUserId);
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('children/accounts/:id')
  async updateChildAccount(
    @Request() req,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: {
      nickname?: string;
      password?: string;
      gender?: string;
      birthday?: string;
      city?: string;
      avatar?: string;
      controlMode?: string;
    },
  ) {
    return this.publicService.updateChildAccount(req.user.userId, id, dto);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('mine/parent-info')
  async getParentInfo(@Request() req) {
    return this.publicService.getParentInfo(req.user.userId);
  }

  // ==================== 作品提交（需要登录） ====================

  @UseGuards(AuthGuard('jwt'))
  @Get('activities/:id/my-registration')
  async getMyRegistration(@Request() req, @Param('id', ParseIntPipe) id: number) {
    return this.publicService.getMyRegistration(req.user.userId, id);
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('activities/:id/submit-work')
  async submitWork(
    @Request() req,
    @Param('id', ParseIntPipe) id: number,
    @Body() data: { registrationId: number; title: string; description?: string; files?: string[]; previewUrl?: string; attachments?: any[] },
  ) {
    return this.publicService.submitWork(req.user.userId, data);
  }

  // ==================== 报名（需要登录） ====================

  @UseGuards(AuthGuard('jwt'))
  @Post('activities/:id/register')
  async registerActivity(
    @Request() req,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: PublicRegisterActivityDto,
  ) {
    dto.contestId = id;
    return this.publicService.registerActivity(req.user.userId, dto);
  }

  // ==================== 我的报名 & 作品（需要登录） ====================

  @UseGuards(AuthGuard('jwt'))
  @Get('mine/registrations')
  async getMyRegistrations(
    @Request() req,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    return this.publicService.getMyRegistrations(req.user.userId, {
      page: page ? parseInt(page, 10) : 1,
      pageSize: pageSize ? parseInt(pageSize, 10) : 10,
    });
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('mine/works')
  async getMyWorks(
    @Request() req,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    return this.publicService.getMyWorks(req.user.userId, {
      page: page ? parseInt(page, 10) : 1,
      pageSize: pageSize ? parseInt(pageSize, 10) : 10,
    });
  }

  // ==================== 公众用户管理（超管端使用） ====================

  @UseGuards(AuthGuard('jwt'))
  @Get('users')
  async getPublicUsers(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('keyword') keyword?: string,
  ) {
    return this.publicService.getPublicUsers({
      page: page ? parseInt(page, 10) : 1,
      pageSize: pageSize ? parseInt(pageSize, 10) : 10,
      keyword,
    });
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('users/:id')
  async getPublicUserDetail(@Param('id', ParseIntPipe) id: number) {
    return this.publicService.getPublicUserDetail(id);
  }

  // ==================== 活动浏览（公开接口） ====================

  @Public()
  @Get('activities')
  async getActivities(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('keyword') keyword?: string,
    @Query('contestType') contestType?: string,
    @Request() req?,
  ) {
    // 尝试从 JWT 获取用户 ID（未登录用户为 undefined）
    const userId = req?.user?.userId;
    return this.publicService.getPublicActivities(
      {
        page: page ? parseInt(page, 10) : 1,
        pageSize: pageSize ? parseInt(pageSize, 10) : 12,
        keyword,
        contestType,
      },
      userId,
    );
  }

  @Public()
  @Get('activities/:id')
  async getActivityDetail(@Param('id', ParseIntPipe) id: number) {
    return this.publicService.getActivityDetail(id);
  }

  // ==================== 用户作品库 ====================

  @UseGuards(AuthGuard('jwt'))
  @Post('works')
  async createUserWork(@Request() req, @Body() dto: any) {
    return this.userWorksService.create(req.user.userId, dto);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('works')
  async getUserWorksList(
    @Request() req,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('status') status?: string,
    @Query('keyword') keyword?: string,
  ) {
    return this.userWorksService.findMyWorks(req.user.userId, {
      page: page ? parseInt(page) : 1,
      pageSize: pageSize ? parseInt(pageSize) : 10,
      status,
      keyword,
    });
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('works/:id')
  async getUserWork(@Request() req, @Param('id', ParseIntPipe) id: number) {
    return this.userWorksService.findOne(id, req.user.userId);
  }

  @UseGuards(AuthGuard('jwt'))
  @Put('works/:id')
  async updateUserWork(
    @Request() req,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: any,
  ) {
    return this.userWorksService.update(id, req.user.userId, dto);
  }

  @UseGuards(AuthGuard('jwt'))
  @Delete('works/:id')
  async deleteUserWork(@Request() req, @Param('id', ParseIntPipe) id: number) {
    return this.userWorksService.remove(id, req.user.userId);
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('works/:id/publish')
  async publishUserWork(@Request() req, @Param('id', ParseIntPipe) id: number) {
    return this.userWorksService.publish(id, req.user.userId);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('works/:id/pages')
  async getUserWorkPages(@Param('id', ParseIntPipe) id: number) {
    return this.userWorksService.getPages(id);
  }

  @UseGuards(AuthGuard('jwt'))
  @Post('works/:id/pages')
  async saveUserWorkPages(
    @Request() req,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: { pages: Array<{ pageNo: number; imageUrl?: string; text?: string; audioUrl?: string }> },
  ) {
    return this.userWorksService.savePages(id, req.user.userId, dto.pages);
  }

  // ==================== AI 创作流程 ====================

  @UseGuards(AuthGuard('jwt'))
  @Post('creation/submit')
  async submitCreation(@Request() req, @Body() dto: {
    originalImageUrl: string;
    voiceInputUrl?: string;
    textInput?: string;
  }) {
    return this.creationService.submit(req.user.userId, dto);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('creation/:id/status')
  async getCreationStatus(@Request() req, @Param('id', ParseIntPipe) id: number) {
    return this.creationService.getStatus(id, req.user.userId);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('creation/:id/result')
  async getCreationResult(@Request() req, @Param('id', ParseIntPipe) id: number) {
    return this.creationService.getResult(id, req.user.userId);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('creation/history')
  async getCreationHistory(
    @Request() req,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    return this.creationService.getHistory(req.user.userId, {
      page: page ? parseInt(page) : 1,
      pageSize: pageSize ? parseInt(pageSize) : 10,
    });
  }

  // ==================== 标签（公众端） ====================

  @Public()
  @Get('tags')
  async getPublicTags() {
    return this.tagsService.getPublicTags();
  }

  @Public()
  @Get('tags/hot')
  async getHotTags() {
    return this.tagsService.getHotTags();
  }

  // ==================== 作品广场（公众端） ====================

  @Public()
  @Get('gallery')
  async getGalleryList(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('tagId') tagId?: string,
    @Query('category') category?: string,
    @Query('sortBy') sortBy?: string,
    @Query('keyword') keyword?: string,
  ) {
    return this.galleryService.getGalleryList({
      page: page ? parseInt(page) : 1,
      pageSize: pageSize ? parseInt(pageSize) : 12,
      tagId: tagId ? parseInt(tagId) : undefined,
      category,
      sortBy,
      keyword,
    });
  }

  @Public()
  @Get('gallery/:id')
  async getGalleryDetail(@Param('id', ParseIntPipe) id: number) {
    return this.galleryService.getGalleryDetail(id);
  }

  @Public()
  @Get('users/:id/works')
  async getUserPublicWorks(
    @Param('id', ParseIntPipe) id: number,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    return this.galleryService.getUserPublicWorks(id, {
      page: page ? parseInt(page) : 1,
      pageSize: pageSize ? parseInt(pageSize) : 12,
    });
  }
}
