'use client';

import React, { useState, useEffect, useRef } from 'react';
import { Volume2, VolumeX, AlertTriangle, X, ShieldAlert } from 'lucide-react';

interface SirenModalProps {
  isOpen: boolean;
  onClose: () => void;
  onTriggerSOS: () => void;
}

export default function SirenModal({ isOpen, onClose, onTriggerSOS }: SirenModalProps) {
  const [isPlaying, setIsPlaying] = useState(false);
  const audioContextRef = useRef<AudioContext | null>(null);
  const oscillatorRef = useRef<OscillatorNode | null>(null);
  const gainNodeRef = useRef<GainNode | null>(null);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  const startSiren = () => {
    try {
      const AudioContextClass = window.AudioContext || (window as any).webkitAudioContext;
      const ctx = new AudioContextClass();
      audioContextRef.current = ctx;

      const osc = ctx.createOscillator();
      const gain = ctx.createGain();

      osc.type = 'sawtooth';
      osc.frequency.setValueAtTime(400, ctx.currentTime);

      // Oscillate frequency for siren wail
      let goingUp = true;
      const interval = setInterval(() => {
        if (!audioContextRef.current) return;
        const currentFreq = osc.frequency.value;
        if (goingUp) {
          if (currentFreq < 900) {
            osc.frequency.setValueAtTime(currentFreq + 50, ctx.currentTime);
          } else {
            goingUp = false;
          }
        } else {
          if (currentFreq > 400) {
            osc.frequency.setValueAtTime(currentFreq - 50, ctx.currentTime);
          } else {
            goingUp = true;
          }
        }
      }, 150);

      intervalRef.current = interval;

      gain.gain.setValueAtTime(0.3, ctx.currentTime);

      osc.connect(gain);
      gain.connect(ctx.destination);

      osc.start();
      oscillatorRef.current = osc;
      gainNodeRef.current = gain;
      setIsPlaying(true);
    } catch (e) {
      console.error('AudioContext error:', e);
    }
  };

  const stopSiren = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    if (oscillatorRef.current) {
      try {
        oscillatorRef.current.stop();
        oscillatorRef.current.disconnect();
      } catch (e) {}
      oscillatorRef.current = null;
    }
    if (audioContextRef.current) {
      try {
        audioContextRef.current.close();
      } catch (e) {}
      audioContextRef.current = null;
    }
    setIsPlaying(false);
  };

  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (isOpen) {
      timer = setTimeout(() => {
        startSiren();
      }, 50);
    }
    return () => {
      if (timer) clearTimeout(timer);
      stopSiren();
    };
  }, [isOpen]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-md animate-fadeIn">
      <div className="relative w-full max-w-lg p-8 mx-4 bg-red-950/90 border-4 border-red-600 rounded-3xl shadow-2xl text-white text-center animate-pulse">
        <button
          onClick={() => {
            stopSiren();
            onClose();
          }}
          className="absolute top-4 right-4 p-2 text-red-200 hover:text-white bg-red-900/60 rounded-full transition"
        >
          <X className="w-6 h-6" />
        </button>

        <div className="flex justify-center mb-6">
          <div className="p-4 bg-red-600 text-white rounded-full shadow-lg shadow-red-600/50 animate-bounce">
            <ShieldAlert className="w-16 h-16" />
          </div>
        </div>

        <h2 className="text-3xl font-black tracking-wider uppercase mb-2 text-red-100">
          SIRENE DARURAT AKTIF
        </h2>
        <p className="text-red-200 text-sm mb-6">
          Peringatan bahaya darurat di wilayah Kecamatan Pulokulon, Kabupaten Grobogan sedang berbunyi. Segera ambil tindakan pengamanan atau evakuasi!
        </p>

        <div className="flex flex-col gap-4">
          <button
            onClick={() => {
              if (isPlaying) {
                stopSiren();
              } else {
                startSiren();
              }
            }}
            className={`flex items-center justify-center gap-3 py-4 px-6 rounded-xl font-bold text-lg shadow-lg transition ${
              isPlaying
                ? 'bg-amber-600 hover:bg-amber-500 text-white'
                : 'bg-red-600 hover:bg-red-500 text-white'
            }`}
          >
            {isPlaying ? <VolumeX className="w-6 h-6" /> : <Volume2 className="w-6 h-6" />}
            {isPlaying ? 'Matikan Suara Sirene' : 'Nyalakan Kembali Sirene'}
          </button>

          <button
            onClick={() => {
              stopSiren();
              onTriggerSOS();
              onClose();
            }}
            className="flex items-center justify-center gap-2 py-4 px-6 bg-white hover:bg-red-100 text-red-950 font-black text-lg rounded-xl shadow-xl transition"
          >
            <AlertTriangle className="w-6 h-6 text-red-600" />
            KIRIM SINYAL SOS & LOKASI DARURAT
          </button>
        </div>

        <p className="text-xs text-red-300/80 mt-6">
          Sistem Siaga Pulokulon - Terhubung langsung ke Posko Darurat Kecamatan.
        </p>
      </div>
    </div>
  );
}
