// 姓名验证
export const validateName = (name: string): { valid: boolean; message: string } => {
  if (!name || name.trim().length === 0) {
    return { valid: false, message: '请输入姓名' };
  }
  
  if (name.length < 2 || name.length > 20) {
    return { valid: false, message: '姓名长度必须在2-20个字符之间' };
  }
  
  // 支持中英文
  const nameRegex = /^[\u4e00-\u9fa5a-zA-Z\s]+$/;
  if (!nameRegex.test(name)) {
    return { valid: false, message: '姓名只能包含中文、英文和空格' };
  }
  
  return { valid: true, message: '' };
};

// 手机号验证
export const validatePhone = (phone: string): { valid: boolean; message: string } => {
  if (!phone || phone.trim().length === 0) {
    return { valid: false, message: '请输入手机号' };
  }
  
  // 中国手机号验证：11位数字，1开头，第二位为3-9
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(phone)) {
    return { valid: false, message: '请输入正确的中国手机号' };
  }
  
  return { valid: true, message: '' };
};

// 表单验证
export const validateUserForm = (name: string, phone: string): { 
  valid: boolean; 
  nameError: string; 
  phoneError: string; 
} => {
  const nameValidation = validateName(name);
  const phoneValidation = validatePhone(phone);
  
  return {
    valid: nameValidation.valid && phoneValidation.valid,
    nameError: nameValidation.message,
    phoneError: phoneValidation.message
  };
};

// 生成唯一ID
export const generateId = (): string => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 格式化时间
const hasExplicitTimeZone = (value: string) => {
  // ISO with Z or numeric offset, e.g. 2025-01-01T00:00:00Z / 2025-01-01T00:00:00+08:00
  return /([zZ]|[+-]\d{2}:?\d{2})$/.test(value.trim());
};

const normalizeUtcStringToIso = (value: string) => {
  const v = value.trim();

  // Already ISO with timezone
  if (hasExplicitTimeZone(v)) return v;

  // SQLite CURRENT_TIMESTAMP: "YYYY-MM-DD HH:mm:ss" (UTC)
  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?$/.test(v)) {
    const iso = v.replace(' ', 'T');
    return iso.length === 16 ? `${iso}:00Z` : `${iso}Z`;
  }

  // ISO without timezone: treat as UTC
  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?$/.test(v)) {
    return `${v}Z`;
  }

  // Date only: treat as UTC midnight
  if (/^\d{4}-\d{2}-\d{2}$/.test(v)) {
    return `${v}T00:00:00Z`;
  }

  return v;
};

export const parseUtcDateTime = (value: string | null | undefined): Date | null => {
  if (!value) return null;
  const normalized = normalizeUtcStringToIso(String(value));
  const date = new Date(normalized);
  if (Number.isNaN(date.getTime())) return null;
  return date;
};

export const formatDateTime = (
  dateString: string,
  options?: { includeSeconds?: boolean; dateOnly?: boolean },
): string => {
  const date = parseUtcDateTime(dateString);
  if (!date) return dateString;

  if (options?.dateOnly) {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    });
  }

  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    ...(options?.includeSeconds ? { second: '2-digit' as const } : null),
  });
};

export const formatDate = (dateString: string): string => {
  return formatDateTime(dateString, { dateOnly: true });
};

// 计算正确率
export const calculateCorrectRate = (correct: number, total: number): string => {
  if (total === 0) return '0%';
  return ((correct / total) * 100).toFixed(1) + '%';
};

// 题型映射
export const questionTypeMap = {
  single: '单选题',
  multiple: '多选题',
  judgment: '判断题',
  text: '文字描述题'
};

// 题型颜色
export const questionTypeColors = {
  single: 'blue',
  multiple: 'green',
  judgment: 'orange',
  text: 'purple'
};