import type { MutableRefObject } from 'react';

export type ManualInterventionAlertSoundOption = {
  id: string;
  label: string;
  src: string;
  description?: string;
};

export const MANUAL_INTERVENTION_ALERT_SOUND_STORAGE_KEY = 'autoprocurement.search.manual-intervention-alert-sound';
export const DEFAULT_MANUAL_INTERVENTION_ALERT_SOUND_ID = 'system-01';

const SYSTEM_SOUND_SLOT_COUNT = 20;

function buildSystemSoundOptions(): ManualInterventionAlertSoundOption[] {
  return Array.from({ length: SYSTEM_SOUND_SLOT_COUNT }, (_, index) => {
    const slot = String(index + 1).padStart(2, '0');
    return {
      id: `system-${slot}`,
      label: `系统提示音 ${slot}`,
      src: `/sounds/manual-intervention-library/alert-${slot}.mp3`,
      description: `对应文件名 alert-${slot}.mp3`,
    };
  });
}

export const manualInterventionAlertSoundOptions: ManualInterventionAlertSoundOption[] = buildSystemSoundOptions();

export function normalizeManualInterventionAlertSoundId(soundId: string | null | undefined) {
  if (!soundId) {
    return DEFAULT_MANUAL_INTERVENTION_ALERT_SOUND_ID;
  }

  if (soundId === 'default') {
    return DEFAULT_MANUAL_INTERVENTION_ALERT_SOUND_ID;
  }

  const legacyCustomMatch = /^custom-(\d{2})$/.exec(soundId);
  if (legacyCustomMatch) {
    return `system-${legacyCustomMatch[1]}`;
  }

  const matched = manualInterventionAlertSoundOptions.find((option) => option.id === soundId);
  return matched?.id ?? DEFAULT_MANUAL_INTERVENTION_ALERT_SOUND_ID;
}

export function getManualInterventionAlertSoundOption(soundId: string | null | undefined) {
  const normalizedSoundId = normalizeManualInterventionAlertSoundId(soundId);
  return manualInterventionAlertSoundOptions.find((option) => option.id === normalizedSoundId)
    ?? manualInterventionAlertSoundOptions[0];
}

export async function playAlertSound(
  audioRef: MutableRefObject<HTMLAudioElement | null>,
  sound: ManualInterventionAlertSoundOption,
) {
  if (typeof window === 'undefined') {
    return;
  }

  if (!audioRef.current) {
    audioRef.current = new Audio(sound.src);
    audioRef.current.preload = 'auto';
  }

  const audio = audioRef.current;
  if (audio.src !== new URL(sound.src, window.location.origin).toString()) {
    audio.src = sound.src;
    audio.load();
  }
  audio.currentTime = 0;
  await audio.play().catch(() => {
    // 浏览器可能阻止自动播放，忽略并保留视觉提示。
  });
}