/**
 * 用户反馈 API 服务
 * 模块: platform_feedback
 */
import apiClient, { PaginatedData, ApiClientError } from '@/lib/api-client';

// ==================== 类型定义 ====================

/**
 * 反馈类型
 */
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'               // 紧急
}

/**
 * 用户简要信息
 */
export interface UserBrief {
  id: string;
  displayName: string;
  email?: string;
  department?: {
    id: string;
    name: string;
  };
}

/**
 * 用户端反馈 (简化版)
 */
export interface UserFeedback {
  id: string;
  type: FeedbackType;
  title: string;
  content: string;
  attachments: string[];
  status: FeedbackStatus;
  priority: FeedbackPriority | null;
  adminReply: string | null;
  createdAt: string;
  updatedAt: string;
}

/**
 * 管理端反馈 (完整版)
 */
export interface AdminFeedback extends UserFeedback {
  pageUrl: string | null;
  userAgent: string | null;
  adminNote: string | null;
  assignee: UserBrief | null;
  resolvedAt: string | null;
  user: UserBrief;
  region: string;
}

/**
 * 反馈统计
 */
export interface FeedbackStats {
  total: number;
  byStatus: Record<FeedbackStatus, number>;
  byType: Record<FeedbackType, number>;
  byPriority: Record<string, number>;
  byRegion?: Record<string, number>;
  avgResolutionTime: number;
  todayNew: number;
  thisWeekNew: number;
  thisMonthNew: number;
}

// ==================== 请求参数类型 ====================

/**
 * 创建反馈参数
 */
export interface CreateFeedbackDto {
  type: FeedbackType;
  title: string;
  content: string;
  attachments?: string[];
  pageUrl?: string;
  userAgent?: string;
}

/**
 * 更新反馈状态参数
 */
export interface UpdateStatusDto {
  status: FeedbackStatus;
}

/**
 * 更新反馈信息参数
 */
export interface UpdateFeedbackDto {
  priority?: FeedbackPriority;
  adminNote?: string;
  adminReply?: string;
  assigneeId?: string;
}

/**
 * 批量更新状态参数
 */
export interface BatchUpdateStatusDto {
  ids: string[];
  status: FeedbackStatus;
}

/**
 * 用户端查询参数
 */
export interface MyFeedbacksQueryParams {
  page?: number;
  pageSize?: number;
  status?: FeedbackStatus;
  type?: FeedbackType;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

/**
 * 管理端查询参数
 */
export interface AdminFeedbacksQueryParams extends MyFeedbacksQueryParams {
  keyword?: string;
  priority?: FeedbackPriority;
  region?: string;
  userId?: string;
  assigneeId?: string;
  startDate?: string;
  endDate?: string;
}

/**
 * 统计查询参数
 */
export interface StatsQueryParams {
  region?: string;
  startDate?: string;
  endDate?: string;
}

// ==================== 响应类型 ====================

/**
 * 批量操作结果
 */
export interface BatchUpdateResult {
  total: number;
  updated: number;
  failed: number;
  failures: Array<{
    id: string;
    reason: string;
  }>;
}

// ==================== API 函数 ====================

const API_PREFIX = '/feedbacks';

// -------------------- 用户端接口 --------------------

/**
 * 提交反馈
 * POST /feedbacks
 */
export async function createFeedback(data: CreateFeedbackDto): Promise<UserFeedback> {
  return apiClient.post(API_PREFIX, {
    ...data,
    pageUrl: data.pageUrl || (typeof window !== 'undefined' ? window.location.pathname : undefined),
    userAgent: data.userAgent || (typeof window !== 'undefined' ? navigator.userAgent : undefined),
  });
}

/**
 * 获取我的反馈列表
 * GET /feedbacks/my
 */
export async function getMyFeedbacks(
  params?: MyFeedbacksQueryParams
): Promise<PaginatedData<UserFeedback>> {
  return apiClient.get(`${API_PREFIX}/my`, { params });
}

/**
 * 获取我的反馈详情
 * GET /feedbacks/my/:id
 */
export async function getMyFeedbackDetail(id: string): Promise<UserFeedback> {
  return apiClient.get(`${API_PREFIX}/my/${id}`);
}

// -------------------- 管理端接口 --------------------

/**
 * 获取所有反馈列表（管理员）
 * GET /feedbacks
 */
export async function getFeedbacks(
  params?: AdminFeedbacksQueryParams
): Promise<PaginatedData<AdminFeedback>> {
  return apiClient.get(API_PREFIX, { params });
}

/**
 * 获取反馈详情（管理员）
 * GET /feedbacks/:id
 */
export async function getFeedbackDetail(id: string): Promise<AdminFeedback> {
  return apiClient.get(`${API_PREFIX}/${id}`);
}

/**
 * 更新反馈状态
 * PATCH /feedbacks/:id/status
 */
export async function updateFeedbackStatus(
  id: string,
  data: UpdateStatusDto
): Promise<{ id: string; status: FeedbackStatus; updatedAt: string }> {
  return apiClient.patch(`${API_PREFIX}/${id}/status`, data);
}

/**
 * 更新反馈信息
 * PATCH /feedbacks/:id
 */
export async function updateFeedback(
  id: string,
  data: UpdateFeedbackDto
): Promise<AdminFeedback> {
  return apiClient.patch(`${API_PREFIX}/${id}`, data);
}

/**
 * 删除反馈（软删除）
 * DELETE /feedbacks/:id
 */
export async function deleteFeedback(id: string): Promise<null> {
  return apiClient.delete(`${API_PREFIX}/${id}`);
}

/**
 * 批量更新状态
 * POST /feedbacks/batch-status
 */
export async function batchUpdateStatus(
  data: BatchUpdateStatusDto
): Promise<BatchUpdateResult> {
  return apiClient.post(`${API_PREFIX}/batch-status`, data);
}

// -------------------- 统计接口 --------------------

/**
 * 获取反馈统计
 * GET /feedbacks/stats
 */
export async function getFeedbackStats(
  params?: StatsQueryParams
): Promise<FeedbackStats> {
  return apiClient.get(`${API_PREFIX}/stats`, { params });
}

// ==================== 辅助函数 ====================

/**
 * 获取反馈类型的显示文本
 */
export function getFeedbackTypeLabel(type: FeedbackType, t?: any): string {
  const labels = {
    [FeedbackType.BUG]: t?.feedback?.typeBug || '问题反馈',
    [FeedbackType.FEATURE]: t?.feedback?.typeFeature || '功能建议',
    [FeedbackType.IMPROVEMENT]: t?.feedback?.typeImprovement || '改进建议',
    [FeedbackType.OTHER]: t?.feedback?.typeOther || '其他',
  };
  return labels[type] || type;
}

/**
 * 获取反馈状态的显示文本
 */
export function getFeedbackStatusLabel(status: FeedbackStatus, t?: any): string {
  const labels = {
    [FeedbackStatus.PENDING]: t?.feedback?.statusPending || '待处理',
    [FeedbackStatus.IN_PROGRESS]: t?.feedback?.statusInProgress || '处理中',
    [FeedbackStatus.RESOLVED]: t?.feedback?.statusResolved || '已解决',
    [FeedbackStatus.CLOSED]: t?.feedback?.statusClosed || '已关闭',
  };
  return labels[status] || status;
}

/**
 * 获取反馈优先级的显示文本
 */
export function getFeedbackPriorityLabel(priority: FeedbackPriority | null, t?: any): string {
  if (!priority) return t?.feedback?.priorityUnset || '未设置';
  const labels = {
    [FeedbackPriority.LOW]: t?.feedback?.priorityLow || '低',
    [FeedbackPriority.MEDIUM]: t?.feedback?.priorityMedium || '中',
    [FeedbackPriority.HIGH]: t?.feedback?.priorityHigh || '高',
    [FeedbackPriority.URGENT]: t?.feedback?.priorityUrgent || '紧急',
  };
  return labels[priority] || priority;
}

/**
 * 获取反馈状态的颜色配置
 */
export function getFeedbackStatusColor(status: FeedbackStatus): {
  bg: string;
  text: string;
  border?: string;
} {
  const colors = {
    [FeedbackStatus.PENDING]: { bg: 'bg-yellow-50', text: 'text-yellow-700', border: 'border-yellow-200' },
    [FeedbackStatus.IN_PROGRESS]: { bg: 'bg-blue-50', text: 'text-blue-700', border: 'border-blue-200' },
    [FeedbackStatus.RESOLVED]: { bg: 'bg-green-50', text: 'text-green-700', border: 'border-green-200' },
    [FeedbackStatus.CLOSED]: { bg: 'bg-gray-50', text: 'text-gray-700', border: 'border-gray-200' },
  };
  return colors[status] || colors[FeedbackStatus.PENDING];
}

/**
 * 获取反馈优先级的颜色配置
 */
export function getFeedbackPriorityColor(priority: FeedbackPriority | null): {
  bg: string;
  text: string;
} {
  if (!priority) return { bg: 'bg-gray-50', text: 'text-gray-500' };
  const colors = {
    [FeedbackPriority.LOW]: { bg: 'bg-gray-50', text: 'text-gray-600' },
    [FeedbackPriority.MEDIUM]: { bg: 'bg-blue-50', text: 'text-blue-600' },
    [FeedbackPriority.HIGH]: { bg: 'bg-orange-50', text: 'text-orange-600' },
    [FeedbackPriority.URGENT]: { bg: 'bg-red-50', text: 'text-red-600' },
  };
  return colors[priority] || colors[FeedbackPriority.LOW];
}

/**
 * 获取反馈类型的颜色配置
 */
export function getFeedbackTypeColor(type: FeedbackType): {
  bg: string;
  text: string;
} {
  const colors = {
    [FeedbackType.BUG]: { bg: 'bg-red-50', text: 'text-red-600' },
    [FeedbackType.FEATURE]: { bg: 'bg-purple-50', text: 'text-purple-600' },
    [FeedbackType.IMPROVEMENT]: { bg: 'bg-blue-50', text: 'text-blue-600' },
    [FeedbackType.OTHER]: { bg: 'bg-gray-50', text: 'text-gray-600' },
  };
  return colors[type] || colors[FeedbackType.OTHER];
}

// 导出错误类型便于使用
export { ApiClientError };
