import { useRef, useEffect } from "react";
import ModalWrapper from "../ModalWrapper";
import Button from "../ui/Button";
import RestartIcon from "../icons/RestartIcon";
import SettingsModal from "./SettingsModal";
import useModalStore from "../../store/modalStore";
import Select from "../ui/Select";

interface SoundCheckModalProps {
  selectedSpeaker: string;
  speakers: { deviceId: string; label: string }[];
  speakerVolume: number;
  onSelectSpeaker: (label: string) => void;
}

function SoundCheckModal({
  selectedSpeaker,
  speakers,
  speakerVolume,
  onSelectSpeaker,
}: SoundCheckModalProps) {
  const { setModal } = useModalStore();
  const audioContextRef = useRef<AudioContext | null>(null);

  // Очистка AudioContext при размонтировании
  useEffect(() => {
    return () => {
      if (audioContextRef.current) {
        audioContextRef.current.close();
        audioContextRef.current = null;
      }
    };
  }, []);

  const playTestSound = () => {
    // Создаём AudioContext если его нет
    if (!audioContextRef.current) {
      audioContextRef.current = new AudioContext();
    }

    const audioContext = audioContextRef.current;
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();

    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);

    // Настраиваем звук (440 Hz - нота A)
    oscillator.frequency.value = 440;
    oscillator.type = "sine";

    // Применяем громкость из настроек и плавное затухание
    const baseVolume = speakerVolume / 100;
    gainNode.gain.setValueAtTime(baseVolume * 0.3, audioContext.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(
      0.01,
      audioContext.currentTime + 1
    );

    // Играем звук 1 секунду
    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + 1);
  };

  return (
    <ModalWrapper className="2xl:max-w-[21.111vw] max-w-[304px]">
      <div className="flex flex-col 2xl:gap-[1.667vw] gap-6 2xl:py-[1.667vw] py-6">
        <div className="flex flex-col items-center 2xl:gap-[0.278vw] gap-1">
          <p className="caption-xs text-[#7D7D7D] font-medium">Динамик</p>
          <Select
            options={speakers.map((s) => s.label)}
            defaultOption={selectedSpeaker}
            onSelect={onSelectSpeaker}
          />
        </div>

        <div className="flex flex-col items-center 2xl:gap-[0.833vw] gap-3">
          <div className="flex items-center justify-center 2xl:gap-[0.208vw] gap-[3px] 2xl:h-[4.167vw] h-[60px]">
            {[3, 12, 16, 20, 44, 28, 34, 60, 8, 40, 18, 36, 24, 13, 10, 6].map(
              (height, index) => (
                <div
                  key={index}
                  className="2xl:w-[0.208vw] w-[3px] bg-[#D6D6D6] 2xl:rounded-[0.556vw] rounded-lg"
                  style={{ height: `${(height / 1440) * innerWidth}px` }}
                />
              )
            )}
          </div>

          <button
            onClick={playTestSound}
            className="2xl:size-[2.778vw] size-10 rounded-full bg-[#7B60F3] hover:bg-[#9184F6] active:bg-[#B3AAF9] flex items-center justify-center text-white transition-colors"
          >
            <div className="2xl:size-[1.111vw] size-4">
              <RestartIcon />
            </div>
          </button>
        </div>

        <div className="flex flex-col items-center 2xl:gap-[0.556vw] gap-2 text-center">
          <h2 className="title-l font-medium">Вы слышите звук?</h2>
          <p className="text-s text-[#7D7D7D]">
            Если нет, проверьте громкость и&nbsp;подключение динамиков
          </p>
        </div>

        <Button
          variant="primary"
          size="large"
          onClick={() => setModal(<SettingsModal />)}
        >
          Завершить
        </Button>
      </div>
    </ModalWrapper>
  );
}

export default SoundCheckModal;
