import dayjs from 'dayjs';
import { getPersonalItemStatusTagType } from '@/constants/status-tag';

export const personalItemStatusOptions = [
  { label: '待处理', value: 'pending' as const },
  { label: '进行中', value: 'active' as const },
  { label: '已完成', value: 'completed' as const }
];

const personalItemStatusLabelMap: Record<Api.PersonalItem.PersonalItemStatusCode, string> = {
  pending: '待开始',
  active: '进行中',
  paused: '已暂停',
  completed: '已完成',
  cancelled: '已取消'
};

export function getPersonalItemStatusLabel(statusCode: Api.PersonalItem.PersonalItemStatusCode | null | undefined) {
  if (!statusCode) {
    return '--';
  }

  return personalItemStatusLabelMap[statusCode] || '--';
}

export function resolvePersonalItemStatusTagType(
  statusCode: Api.PersonalItem.PersonalItemStatusCode | null | undefined
) {
  return getPersonalItemStatusTagType(statusCode);
}

export function formatPersonalItemDate(value: string | null | undefined) {
  if (!value) {
    return '--';
  }

  const target = dayjs(value);

  if (!target.isValid()) {
    return '--';
  }

  return target.format('YYYY-MM-DD');
}

export function formatPersonalItemDateTime(value: string | null | undefined) {
  if (!value) {
    return '--';
  }

  const target = dayjs(value);

  if (!target.isValid()) {
    return '--';
  }

  return target.format('YYYY-MM-DD HH:mm:ss');
}

export function formatPersonalItemProgress(value: number | null | undefined) {
  if (typeof value !== 'number' || !Number.isFinite(value)) {
    return '0%';
  }

  const normalized = Math.round(Math.min(100, Math.max(0, value)) * 100) / 100;
  return `${normalized}%`;
}

export function formatPersonalItemName(value: string | null | undefined) {
  return value?.trim() || '--';
}

export function formatPersonalItemOwnerName(
  item: Pick<Api.PersonalItem.PersonalItem, 'ownerNickname' | 'ownerName' | 'ownerId'>
) {
  return item.ownerNickname?.trim() || item.ownerName?.trim() || item.ownerId || '--';
}

export function formatPersonalItemDateRange(start: string | null | undefined, end: string | null | undefined) {
  const startText = formatPersonalItemDate(start);
  const endText = formatPersonalItemDate(end);

  if (startText === '--' && endText === '--') {
    return '--';
  }

  return `${startText} ~ ${endText}`;
}

export function isEmptyRichText(html: string | null | undefined) {
  if (!html) {
    return true;
  }

  const text = html
    .replace(/<[^>]+>/g, '')
    .replace(/&nbsp;/g, '')
    .trim();

  if (text) {
    return false;
  }

  return !/<img\b/i.test(html);
}
