import douyinLogo from "../assets/media-logos/douyin.svg";
import wechatLogo from "../assets/media-logos/wechat.svg";
import wechatChannelsLogo from "../assets/media-logos/wechat-channels.svg";
import xiaohongshuLogo from "../assets/media-logos/xiaohongshu.svg";
import websiteLogo from "../assets/media-logos/website.svg";
import customLogo from "../assets/media-logos/custom.svg";

export type MediaAccount = {
  id?: number | string;
  name?: string;
  platform?: string;
  platform_logo_url?: string;
  platformLogoUrl?: string;
  url?: string;
  qr_code_url?: string;
  qrCodeUrl?: string;
  status?: string;
  sort_order?: number;
  sortOrder?: number;
};

export type NormalizedMediaAccount = MediaAccount & {
  platformKey: string;
  platformTitle: string;
  logoSrc: string;
  displayUrl: string;
  qrCodeUrl: string;
  sortOrder: number;
};

export const MEDIA_PLATFORM_ORDER = ["wechat", "miniprogram", "video", "douyin", "xiaohongshu", "website", "custom"];

const PLATFORM_META: Record<string, { title: string; logo: string }> = {
  wechat: { title: "微信公众号", logo: wechatLogo },
  miniprogram: { title: "微信小程序", logo: wechatLogo },
  video: { title: "视频号", logo: wechatChannelsLogo },
  douyin: { title: "抖音号", logo: douyinLogo },
  xiaohongshu: { title: "小红书", logo: xiaohongshuLogo },
  website: { title: "官网/站点", logo: websiteLogo },
  custom: { title: "其他平台", logo: customLogo }
};

const PLATFORM_ALIASES: Record<string, string> = {
  wechat: "wechat",
  wx: "wechat",
  weixin: "wechat",
  mp: "wechat",
  gzh: "wechat",
  official_account: "wechat",
  wechat_official: "wechat",
  miniprogram: "miniprogram",
  mini_program: "miniprogram",
  miniapp: "miniprogram",
  wxapp: "miniprogram",
  xiaochengxu: "miniprogram",
  video: "video",
  channels: "video",
  wechat_channels: "video",
  shipinhao: "video",
  wx_channels: "video",
  douyin: "douyin",
  tiktok: "douyin",
  xiaohongshu: "xiaohongshu",
  xhs: "xiaohongshu",
  red: "xiaohongshu",
  redbook: "xiaohongshu",
  website: "website",
  site: "website",
  web: "website",
  official_site: "website",
  custom: "custom",
  other: "custom"
};

function clean(value: unknown) {
  return String(value ?? "").trim();
}

export function normalizeMediaPlatform(platform?: string) {
  const key = clean(platform).toLowerCase().replace(/[\s-]+/g, "_");
  return PLATFORM_ALIASES[key] || key || "custom";
}

export function normalizeMediaAccount(account: MediaAccount): NormalizedMediaAccount | null {
  const status = clean(account.status || "enabled").toLowerCase();
  const name = clean(account.name);
  const displayUrl = clean(account.url);
  const qrCodeUrl = clean(account.qrCodeUrl || account.qr_code_url);
  if (status !== "enabled" || !name || (!displayUrl && !qrCodeUrl)) return null;
  const platformKey = normalizeMediaPlatform(account.platform);
  const meta = PLATFORM_META[platformKey] || PLATFORM_META.custom;
  const logoSrc = clean(account.platformLogoUrl || account.platform_logo_url) || meta.logo;
  return {
    ...account,
    name,
    platformKey,
    platformTitle: meta.title,
    logoSrc,
    displayUrl,
    qrCodeUrl,
    sortOrder: Number(account.sortOrder ?? account.sort_order ?? 0) || 0
  };
}

export function normalizeMediaAccounts(accounts?: MediaAccount[]) {
  return (accounts || [])
    .map(normalizeMediaAccount)
    .filter(Boolean)
    .sort((a, b) => {
      const ai = MEDIA_PLATFORM_ORDER.indexOf(a!.platformKey);
      const bi = MEDIA_PLATFORM_ORDER.indexOf(b!.platformKey);
      const ao = ai < 0 ? MEDIA_PLATFORM_ORDER.length : ai;
      const bo = bi < 0 ? MEDIA_PLATFORM_ORDER.length : bi;
      return ao - bo || a!.sortOrder - b!.sortOrder || String(a!.id || "").localeCompare(String(b!.id || ""));
    }) as NormalizedMediaAccount[];
}

export function groupMediaAccounts(accounts: NormalizedMediaAccount[]) {
  const map = new Map<string, NormalizedMediaAccount[]>();
  accounts.forEach((account) => {
    const list = map.get(account.platformKey) || [];
    list.push(account);
    map.set(account.platformKey, list);
  });
  const keys = [
    ...MEDIA_PLATFORM_ORDER.filter((key) => map.has(key)),
    ...[...map.keys()].filter((key) => !MEDIA_PLATFORM_ORDER.includes(key))
  ];
  return keys.map((key) => ({
    key,
    title: PLATFORM_META[key]?.title || key,
    rows: map.get(key) || []
  }));
}
