import {
  IsString,
  IsEnum,
  IsOptional,
  IsArray,
  IsUUID,
  MaxLength,
  MinLength,
  IsUrl,
  IsDateString,
  IsInt,
  Min,
  Max,
} from 'class-validator';
import { Type, Transform } from 'class-transformer';
import { ApiProperty, ApiPropertyOptional, PartialType } from '@nestjs/swagger';

// ============================================================================
// Enums
// ============================================================================

export enum FeedbackType {
  BUG = 'BUG',
  FEATURE = 'FEATURE',
  IMPROVEMENT = 'IMPROVEMENT',
  OTHER = 'OTHER',
}

export enum FeedbackStatus {
  PENDING = 'PENDING',
  IN_PROGRESS = 'IN_PROGRESS',
  RESOLVED = 'RESOLVED',
  CLOSED = 'CLOSED',
}

export enum FeedbackPriority {
  LOW = 'LOW',
  MEDIUM = 'MEDIUM',
  HIGH = 'HIGH',
  URGENT = 'URGENT',
}

// ============================================================================
// Create Feedback DTO
// ============================================================================

export class CreateFeedbackDto {
  @ApiProperty({
    description: '反馈类型',
    enum: FeedbackType,
    example: FeedbackType.BUG,
  })
  @IsEnum(FeedbackType)
  type: FeedbackType;

  @ApiProperty({
    description: '反馈标题',
    minLength: 1,
    maxLength: 200,
    example: '登录页面无法加载',
  })
  @IsString()
  @MinLength(1)
  @MaxLength(200)
  title: string;

  @ApiProperty({
    description: '反馈详细内容',
    minLength: 1,
    maxLength: 5000,
    example: '点击登录按钮后，页面一直显示加载中...',
  })
  @IsString()
  @MinLength(1)
  @MaxLength(5000)
  content: string;

  @ApiPropertyOptional({
    description: '附件 URL 数组（最多5个）',
    type: [String],
    example: ['https://storage.example.com/feedbacks/screenshot1.png'],
  })
  @IsOptional()
  @IsArray()
  @IsUrl({}, { each: true })
  attachments?: string[];

  @ApiPropertyOptional({
    description: '提交时的页面 URL',
    maxLength: 500,
    example: '/login',
  })
  @IsOptional()
  @IsString()
  @MaxLength(500)
  pageUrl?: string;

  @ApiPropertyOptional({
    description: '浏览器 User-Agent',
    maxLength: 500,
    example: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...',
  })
  @IsOptional()
  @IsString()
  @MaxLength(500)
  userAgent?: string;
}

// ============================================================================
// Update Feedback DTO (Admin)
// ============================================================================

export class UpdateFeedbackDto {
  @ApiPropertyOptional({
    description: '优先级',
    enum: FeedbackPriority,
    example: FeedbackPriority.HIGH,
  })
  @IsOptional()
  @IsEnum(FeedbackPriority)
  priority?: FeedbackPriority;

  @ApiPropertyOptional({
    description: '管理员内部备注（用户不可见）',
    maxLength: 5000,
    example: '需要后端配合排查，疑似 API 超时问题',
  })
  @IsOptional()
  @IsString()
  @MaxLength(5000)
  adminNote?: string;

  @ApiPropertyOptional({
    description: '管理员回复（用户可见）',
    maxLength: 5000,
    example: '我们已经定位到问题，正在修复中。',
  })
  @IsOptional()
  @IsString()
  @MaxLength(5000)
  adminReply?: string;

  @ApiPropertyOptional({
    description: '指派处理人 ID',
    example: 'uuid',
  })
  @IsOptional()
  @IsUUID()
  assigneeId?: string;
}

// ============================================================================
// Update Status DTO
// ============================================================================

export class UpdateStatusDto {
  @ApiProperty({
    description: '新状态',
    enum: FeedbackStatus,
    example: FeedbackStatus.IN_PROGRESS,
  })
  @IsEnum(FeedbackStatus)
  status: FeedbackStatus;
}

// ============================================================================
// Batch Update Status DTO
// ============================================================================

export class BatchUpdateStatusDto {
  @ApiProperty({
    description: '反馈 ID 数组（最多 100 个）',
    type: [String],
    example: ['uuid1', 'uuid2', 'uuid3'],
  })
  @IsArray()
  @IsUUID('all', { each: true })
  ids: string[];

  @ApiProperty({
    description: '目标状态',
    enum: FeedbackStatus,
    example: FeedbackStatus.CLOSED,
  })
  @IsEnum(FeedbackStatus)
  status: FeedbackStatus;
}

// ============================================================================
// Query DTOs
// ============================================================================

export class FeedbackQueryDto {
  @ApiPropertyOptional({
    description: '页码，从 1 开始',
    default: 1,
    minimum: 1,
  })
  @IsOptional()
  @Type(() => Number)
  @IsInt()
  @Min(1)
  page?: number = 1;

  @ApiPropertyOptional({
    description: '每页数量',
    default: 20,
    minimum: 1,
    maximum: 100,
  })
  @IsOptional()
  @Type(() => Number)
  @IsInt()
  @Min(1)
  @Max(100)
  pageSize?: number = 20;

  @ApiPropertyOptional({
    description: '搜索关键词（匹配标题、内容）',
  })
  @IsOptional()
  @IsString()
  keyword?: string;

  @ApiPropertyOptional({
    description: '状态筛选',
    enum: FeedbackStatus,
  })
  @IsOptional()
  @IsEnum(FeedbackStatus)
  status?: FeedbackStatus;

  @ApiPropertyOptional({
    description: '类型筛选',
    enum: FeedbackType,
  })
  @IsOptional()
  @IsEnum(FeedbackType)
  type?: FeedbackType;

  @ApiPropertyOptional({
    description: '排序字段',
    default: 'createdAt',
    example: 'createdAt',
  })
  @IsOptional()
  @IsString()
  sortBy?: string = 'createdAt';

  @ApiPropertyOptional({
    description: '排序方向',
    enum: ['asc', 'desc'],
    default: 'desc',
  })
  @IsOptional()
  @IsString()
  sortOrder?: 'asc' | 'desc' = 'desc';
}

export class AdminFeedbackQueryDto extends FeedbackQueryDto {
  @ApiPropertyOptional({
    description: '优先级筛选',
    enum: FeedbackPriority,
  })
  @IsOptional()
  @IsEnum(FeedbackPriority)
  priority?: FeedbackPriority;

  @ApiPropertyOptional({
    description: '区域筛选（全局管理员可用）',
    example: 'CN',
  })
  @IsOptional()
  @IsString()
  region?: string;

  @ApiPropertyOptional({
    description: '提交用户 ID 筛选',
  })
  @IsOptional()
  @IsUUID()
  userId?: string;

  @ApiPropertyOptional({
    description: '处理人 ID 筛选',
  })
  @IsOptional()
  @IsUUID()
  assigneeId?: string;

  @ApiPropertyOptional({
    description: '开始日期（ISO 8601）',
    example: '2025-12-01T00:00:00.000Z',
  })
  @IsOptional()
  @IsDateString()
  startDate?: string;

  @ApiPropertyOptional({
    description: '结束日期（ISO 8601）',
    example: '2025-12-31T23:59:59.999Z',
  })
  @IsOptional()
  @IsDateString()
  endDate?: string;
}

// ============================================================================
// Stats Query DTO
// ============================================================================

export class FeedbackStatsQueryDto {
  @ApiPropertyOptional({
    description: '区域筛选（全局管理员可用）',
    example: 'CN',
  })
  @IsOptional()
  @IsString()
  region?: string;

  @ApiPropertyOptional({
    description: '开始日期',
  })
  @IsOptional()
  @IsDateString()
  startDate?: string;

  @ApiPropertyOptional({
    description: '结束日期',
  })
  @IsOptional()
  @IsDateString()
  endDate?: string;
}

// ============================================================================
// Response Types (for Swagger documentation)
// ============================================================================

export class UserBriefDto {
  @ApiProperty()
  id: string;

  @ApiProperty()
  displayName: string;

  @ApiPropertyOptional()
  email?: string;
}

export class FeedbackResponseDto {
  @ApiProperty()
  id: string;

  @ApiProperty({ enum: FeedbackType })
  type: FeedbackType;

  @ApiProperty()
  title: string;

  @ApiProperty()
  content: string;

  @ApiPropertyOptional({ type: [String] })
  attachments?: string[];

  @ApiPropertyOptional()
  pageUrl?: string;

  @ApiPropertyOptional()
  userAgent?: string;

  @ApiProperty({ enum: FeedbackStatus })
  status: FeedbackStatus;

  @ApiPropertyOptional({ enum: FeedbackPriority })
  priority?: FeedbackPriority;

  @ApiPropertyOptional()
  adminNote?: string;

  @ApiPropertyOptional()
  adminReply?: string;

  @ApiPropertyOptional({ type: UserBriefDto })
  assignee?: UserBriefDto;

  @ApiPropertyOptional()
  resolvedAt?: Date;

  @ApiProperty({ type: UserBriefDto })
  user: UserBriefDto;

  @ApiProperty()
  region: string;

  @ApiProperty()
  createdAt: Date;

  @ApiProperty()
  updatedAt: Date;
}

export class FeedbackStatsDto {
  @ApiProperty()
  total: number;

  @ApiProperty()
  byStatus: Record<FeedbackStatus, number>;

  @ApiProperty()
  byType: Record<FeedbackType, number>;

  @ApiProperty()
  byPriority: Record<string, number>;

  @ApiPropertyOptional()
  byRegion?: Record<string, number>;

  @ApiProperty({ description: '平均解决时间（小时）' })
  avgResolutionTime: number;

  @ApiProperty()
  todayNew: number;

  @ApiProperty()
  thisWeekNew: number;

  @ApiProperty()
  thisMonthNew: number;
}

export class BatchUpdateResultDto {
  @ApiProperty()
  total: number;

  @ApiProperty()
  updated: number;

  @ApiProperty()
  failed: number;

  @ApiProperty({ type: [Object] })
  failures: Array<{ id: string; reason: string }>;
}
