import { useState, useRef, useEffect } from "react";
import { useClickAway } from "@uidotdev/usehooks";
import ModalWrapper from "../ModalWrapper";
import Button from "../ui/Button";
import ChevronDownIcon from "../icons/ChevronDownIcon";
import RestartIcon from "../icons/RestartIcon";

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

function SoundCheckModal({
  selectedSpeaker,
  speakers,
  onSelectSpeaker,
  onClose,
}: SoundCheckModalProps) {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const audioContextRef = useRef<AudioContext | null>(null);
  const dropdownRef = useClickAway<HTMLDivElement>(() =>
    setIsDropdownOpen(false)
  );

  // Очистка 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";

    // Плавное затухание
    gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(
      0.01,
      audioContext.currentTime + 1
    );

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

  return (
    <ModalWrapper title="" className="max-w-[21.111vw]">
      <div className="flex flex-col 2xl:gap-[1.667vw] gap-6">
        <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>

        <div className="flex flex-col items-center 2xl:gap-[0.278vw] gap-1">
          <p className="caption-xs text-[#7D7D7D]">Динамик</p>
          <div ref={dropdownRef} className="relative w-full">
            <button
              onClick={() => setIsDropdownOpen(!isDropdownOpen)}
              className="w-full bg-[#F3F3F3] 2xl:py-[0.972vw] py-3.5 2xl:px-[1.111vw] px-4 2xl:rounded-[1.111vw] rounded-2xl flex items-center justify-between"
            >
              <span className="button-m">{selectedSpeaker}</span>
              <div
                className={`2xl:size-[1.111vw] size-4 text-[#7D7D7D] transition-transform ${
                  isDropdownOpen ? "rotate-180" : ""
                }`}
              >
                <ChevronDownIcon />
              </div>
            </button>
            {isDropdownOpen && (
              <div className="absolute top-full left-0 w-full bg-[#F3F3F3] 2xl:rounded-b-[1.111vw] rounded-b-2xl overflow-hidden z-10">
                {speakers.map((speaker) => (
                  <button
                    key={speaker.deviceId}
                    onClick={() => {
                      onSelectSpeaker(speaker.label);
                      setIsDropdownOpen(false);
                    }}
                    className="w-full text-left 2xl:py-[0.972vw] py-3.5 2xl:px-[1.111vw] px-4 button-m hover:bg-[#f0f0f0] transition-colors"
                  >
                    {speaker.label}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Sound Wave Visualization */}
        <div className="flex flex-col items-center 2xl:gap-[0.833vw] gap-3">
          <div className="flex items-end justify-center 2xl:gap-[0.278vw] gap-1 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}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>

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

export default SoundCheckModal;
