import type { MemberFilterState, MemberTierEditorForm } from '../../types';

import type {
  MemberDetailDto,
  MemberListFilterQuery,
  MemberListQuery,
  MemberTierDetailDto,
  SaveMemberTierPayload,
} from '#/api/member';

import {
  DEFAULT_MEMBER_TIER_BENEFITS,
  DEFAULT_MEMBER_TIER_RULE,
} from './constants';

export function buildFilterPayload(
  storeId: string,
  filters: MemberFilterState,
): MemberListFilterQuery {
  return {
    storeId,
    keyword: filters.keyword.trim() || undefined,
    tierId: filters.tierId || undefined,
  };
}

export function buildQueryPayload(
  storeId: string,
  filters: MemberFilterState,
  page: number,
  pageSize: number,
): MemberListQuery {
  return {
    ...buildFilterPayload(storeId, filters),
    page,
    pageSize,
  };
}

export function formatCurrency(value: number) {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(Number.isFinite(value) ? value : 0);
}

export function formatInteger(value: number) {
  return new Intl.NumberFormat('zh-CN', {
    maximumFractionDigits: 0,
  }).format(Number.isFinite(value) ? value : 0);
}

export function decodeBase64ToBlob(base64: string) {
  const binary = atob(base64);
  const bytes = new Uint8Array(binary.length);
  for (let index = 0; index < binary.length; index += 1) {
    bytes[index] = binary.codePointAt(index) ?? 0;
  }
  return new Blob([bytes], { type: 'text/csv;charset=utf-8;' });
}

export function downloadBase64File(
  fileName: string,
  fileContentBase64: string,
) {
  const blob = decodeBase64ToBlob(fileContentBase64);
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = fileName;
  anchor.click();
  URL.revokeObjectURL(url);
}

function normalizeHexColor(color: string) {
  const source = (color || '#999999').trim();
  if (!source.startsWith('#')) {
    return `#${source}`;
  }
  return source;
}

function hexToRgb(hex: string) {
  const normalized = normalizeHexColor(hex).replace('#', '');
  if (normalized.length !== 6) {
    return { r: 153, g: 153, b: 153 };
  }

  return {
    r: Number.parseInt(normalized.slice(0, 2), 16),
    g: Number.parseInt(normalized.slice(2, 4), 16),
    b: Number.parseInt(normalized.slice(4, 6), 16),
  };
}

export function resolveTierTagStyle(colorHex: string) {
  const rgb = hexToRgb(colorHex);
  return {
    color: normalizeHexColor(colorHex),
    backgroundColor: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.12)`,
    borderColor: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.35)`,
  };
}

export function resolveTierIcon(iconKey: string) {
  const normalized = (iconKey || 'user').trim().toLowerCase();
  if (normalized === 'award') return 'lucide:award';
  if (normalized === 'trophy') return 'lucide:trophy';
  if (normalized === 'gem') return 'lucide:gem';
  if (normalized === 'crown') return 'lucide:crown';
  if (normalized === 'star') return 'lucide:star';
  return 'lucide:user';
}

export function createTierEditorForm(
  source: MemberTierDetailDto,
): MemberTierEditorForm {
  return {
    tierId: source.tierId,
    sortOrder: source.sortOrder,
    name: source.name,
    iconKey: source.iconKey,
    colorHex: source.colorHex,
    isDefault: source.isDefault,
    rule: {
      upgradeRuleType: source.rule.upgradeRuleType,
      upgradeAmountThreshold: source.rule.upgradeAmountThreshold,
      upgradeOrderCountThreshold: source.rule.upgradeOrderCountThreshold,
      downgradeWindowDays: source.rule.downgradeWindowDays,
    },
    benefits: {
      discount: {
        enabled: source.benefits.discount.enabled,
        discountRate: source.benefits.discount.discountRate,
      },
      pointMultiplier: {
        enabled: source.benefits.pointMultiplier.enabled,
        multiplier: source.benefits.pointMultiplier.multiplier,
      },
      birthday: {
        enabled: source.benefits.birthday.enabled,
        doublePointsEnabled: source.benefits.birthday.doublePointsEnabled,
        couponTemplateIds: [...source.benefits.birthday.couponTemplateIds],
      },
      monthlyCoupon: {
        enabled: source.benefits.monthlyCoupon.enabled,
        grantDay: source.benefits.monthlyCoupon.grantDay,
        couponTemplateIds: [...source.benefits.monthlyCoupon.couponTemplateIds],
      },
      freeDelivery: {
        enabled: source.benefits.freeDelivery.enabled,
        monthlyFreeTimes: source.benefits.freeDelivery.monthlyFreeTimes,
      },
      priorityDeliveryEnabled: source.benefits.priorityDeliveryEnabled,
      exclusiveServiceEnabled: source.benefits.exclusiveServiceEnabled,
    },
  };
}

export function createEmptyTierEditorForm(): MemberTierEditorForm {
  return {
    tierId: undefined,
    sortOrder: 1,
    name: '',
    iconKey: 'user',
    colorHex: '#999999',
    isDefault: false,
    rule: {
      ...DEFAULT_MEMBER_TIER_RULE,
    },
    benefits: {
      discount: { ...DEFAULT_MEMBER_TIER_BENEFITS.discount },
      pointMultiplier: { ...DEFAULT_MEMBER_TIER_BENEFITS.pointMultiplier },
      birthday: {
        ...DEFAULT_MEMBER_TIER_BENEFITS.birthday,
        couponTemplateIds: [],
      },
      monthlyCoupon: {
        ...DEFAULT_MEMBER_TIER_BENEFITS.monthlyCoupon,
        couponTemplateIds: [],
      },
      freeDelivery: { ...DEFAULT_MEMBER_TIER_BENEFITS.freeDelivery },
      priorityDeliveryEnabled:
        DEFAULT_MEMBER_TIER_BENEFITS.priorityDeliveryEnabled,
      exclusiveServiceEnabled:
        DEFAULT_MEMBER_TIER_BENEFITS.exclusiveServiceEnabled,
    },
  };
}

export function buildTierSavePayload(
  form: MemberTierEditorForm,
): SaveMemberTierPayload {
  return {
    tierId: form.tierId,
    sortOrder: Number(form.sortOrder || 1),
    name: form.name.trim(),
    iconKey: form.iconKey,
    colorHex: normalizeHexColor(form.colorHex),
    isDefault: !!form.isDefault,
    rule: {
      upgradeRuleType: form.rule.upgradeRuleType,
      upgradeAmountThreshold:
        form.rule.upgradeAmountThreshold === undefined
          ? undefined
          : Number(form.rule.upgradeAmountThreshold),
      upgradeOrderCountThreshold:
        form.rule.upgradeOrderCountThreshold === undefined
          ? undefined
          : Number(form.rule.upgradeOrderCountThreshold),
      downgradeWindowDays: Number(form.rule.downgradeWindowDays || 90),
    },
    benefits: {
      discount: {
        enabled: !!form.benefits.discount.enabled,
        discountRate:
          form.benefits.discount.discountRate === undefined
            ? undefined
            : Number(form.benefits.discount.discountRate),
      },
      pointMultiplier: {
        enabled: !!form.benefits.pointMultiplier.enabled,
        multiplier:
          form.benefits.pointMultiplier.multiplier === undefined
            ? undefined
            : Number(form.benefits.pointMultiplier.multiplier),
      },
      birthday: {
        enabled: !!form.benefits.birthday.enabled,
        doublePointsEnabled: !!form.benefits.birthday.doublePointsEnabled,
        couponTemplateIds: [
          ...new Set(form.benefits.birthday.couponTemplateIds),
        ],
      },
      monthlyCoupon: {
        enabled: !!form.benefits.monthlyCoupon.enabled,
        grantDay: Number(form.benefits.monthlyCoupon.grantDay || 1),
        couponTemplateIds: [
          ...new Set(form.benefits.monthlyCoupon.couponTemplateIds),
        ],
      },
      freeDelivery: {
        enabled: !!form.benefits.freeDelivery.enabled,
        monthlyFreeTimes: Number(
          form.benefits.freeDelivery.monthlyFreeTimes || 0,
        ),
      },
      priorityDeliveryEnabled: !!form.benefits.priorityDeliveryEnabled,
      exclusiveServiceEnabled: !!form.benefits.exclusiveServiceEnabled,
    },
  };
}

export function resolveMemberName(detail: MemberDetailDto | null) {
  return detail?.name || '会员';
}
