import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseGuards,
  HttpCode,
  HttpStatus,
  Query,
  BadRequestException,
  Logger,
} from '@nestjs/common';
import { ChildrenService } from './children.service';
import { CreateChildDto } from './dto/create-child.dto';
import { UpdateChildDto } from './dto/update-child.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { CurrentUser } from '../auth/decorators/current-user.decorator';

@Controller('api/v1/children')
@UseGuards(JwtAuthGuard)
export class ChildrenController {
  private readonly logger = new Logger(ChildrenController.name);

  constructor(private readonly childrenService: ChildrenService) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  async create(
    @CurrentUser() user: any,
    @Query('familyId') familyId: string,
    @Body() createChildDto: CreateChildDto,
  ) {
    if (!familyId) {
      throw new BadRequestException('familyId query parameter is required');
    }

    const child = await this.childrenService.create(
      user.userId,
      familyId,
      createChildDto,
    );

    return {
      success: true,
      data: {
        child: {
          id: child.id,
          familyId: child.familyId,
          name: child.name,
          birthDate: child.birthDate,
          gender: child.gender,
          photoUrl: child.photoUrl,
          photoAlt: child.photoAlt,
          displayColor: child.displayColor,
          sortOrder: child.sortOrder,
          nickname: child.nickname,
          medicalInfo: child.medicalInfo,
          createdAt: child.createdAt,
        },
      },
    };
  }

  @Get('family/:familyId/statistics')
  @HttpCode(HttpStatus.OK)
  async getFamilyStatistics(
    @CurrentUser() user: any,
    @Param('familyId') familyId: string,
  ) {
    const stats = await this.childrenService.getFamilyStatistics(
      user.userId,
      familyId,
    );

    return {
      success: true,
      data: stats,
    };
  }

  @Get()
  @HttpCode(HttpStatus.OK)
  async findAll(@CurrentUser() user: any, @Query('familyId') familyId: string) {
    this.logger.log(`[findAll] user.userId: ${user.userId}, familyId: ${familyId || 'undefined'}`);

    let children;

    if (familyId) {
      // Get children for specific family
      this.logger.log(`[findAll] Calling findAll with familyId: ${familyId}`);
      children = await this.childrenService.findAll(user.userId, familyId);
    } else {
      // Get all children across all families
      this.logger.log(`[findAll] Calling findAllForUser (no familyId provided)`);
      children = await this.childrenService.findAllForUser(user.userId);
    }

    this.logger.log(`[findAll] Returning ${children.length} children: ${children.map(c => `${c.name}(${c.id.substring(0, 8)})`).join(', ')}`);

    return {
      success: true,
      data: {
        children: children.map((child) => ({
          id: child.id,
          familyId: child.familyId,
          name: child.name,
          birthDate: child.birthDate,
          gender: child.gender,
          photoUrl: child.photoUrl,
          photoAlt: child.photoAlt,
          displayColor: child.displayColor,
          sortOrder: child.sortOrder,
          nickname: child.nickname,
          medicalInfo: child.medicalInfo,
          createdAt: child.createdAt,
        })),
      },
    };
  }

  @Get(':id')
  @HttpCode(HttpStatus.OK)
  async findOne(@CurrentUser() user: any, @Param('id') id: string) {
    const child = await this.childrenService.findOne(user.userId, id);

    return {
      success: true,
      data: {
        child: {
          id: child.id,
          familyId: child.familyId,
          name: child.name,
          birthDate: child.birthDate,
          gender: child.gender,
          photoUrl: child.photoUrl,
          photoAlt: child.photoAlt,
          displayColor: child.displayColor,
          sortOrder: child.sortOrder,
          nickname: child.nickname,
          medicalInfo: child.medicalInfo,
          createdAt: child.createdAt,
        },
      },
    };
  }

  @Get(':id/age')
  @HttpCode(HttpStatus.OK)
  async getChildAge(@Param('id') id: string) {
    const ageInMonths = await this.childrenService.getChildAgeInMonths(id);

    return {
      success: true,
      data: {
        ageInMonths,
        ageInYears: Math.floor(ageInMonths / 12),
        remainingMonths: ageInMonths % 12,
      },
    };
  }

  @Patch(':id')
  @HttpCode(HttpStatus.OK)
  async update(
    @CurrentUser() user: any,
    @Param('id') id: string,
    @Body() updateChildDto: UpdateChildDto,
  ) {
    const child = await this.childrenService.update(
      user.userId,
      id,
      updateChildDto,
    );

    return {
      success: true,
      data: {
        child: {
          id: child.id,
          familyId: child.familyId,
          name: child.name,
          birthDate: child.birthDate,
          gender: child.gender,
          photoUrl: child.photoUrl,
          photoAlt: child.photoAlt,
          displayColor: child.displayColor,
          sortOrder: child.sortOrder,
          nickname: child.nickname,
          medicalInfo: child.medicalInfo,
          createdAt: child.createdAt,
        },
      },
    };
  }

  @Delete(':id')
  @HttpCode(HttpStatus.OK)
  async remove(@CurrentUser() user: any, @Param('id') id: string) {
    await this.childrenService.remove(user.userId, id);

    return {
      success: true,
      message: 'Child deleted successfully',
    };
  }
}
