import SwiftUI
import AVFoundation

struct FlashlightView: View {
    @Environment(\.presentationMode) var presentationMode
    
    enum LightState: String {
        case off, steady, slowFlash, fastFlash, sos
    }
    
    @State private var currentState: LightState = .off
    @State private var isLightOn = false
    @State private var flashTimer: Timer?
    @State private var sosWorkItem: DispatchWorkItem? // SOS task item
    
    var body: some View {
        VStack {
         
            HStack{
                Button(action: {
                           presentationMode.wrappedValue.dismiss()
                       }) {
                           Image("nav_back")
                               .foregroundColor(.black)
                       }
                Spacer()
                Text(L("Survival light"))
                    .font(.system(size: 16, weight: .bold))
                    .foregroundColor(.black)
                
                Spacer()
                
            }
            .padding(.horizontal,15.0)
            
            Spacer()
            
            Image(isLightOn ? "light_on" : "light_off")
                .frame(width: 200.0, height: 200.0)
            
            Spacer()
            
            HStack(spacing: 30.0) {
                stateButton(title: "Off", state: .off)
            }
            .padding(.bottom)
            
            HStack(spacing: 30.0) {
                stateButton(title: "Always", state: .steady)
                stateButton(title: "Slow flash", state: .slowFlash)
            }
            .padding(.bottom)
            
            HStack(spacing: 30.0) {
                stateButton(title: "Twinkle", state: .fastFlash)
                stateButton(title: "SOS", state: .sos)
            }
            
            Spacer()
        }
        .edgesIgnoringSafeArea(.bottom)
        .gradientBackground()
        .navigationBarBackButtonHidden(true)
        .onChange(of: currentState) { _ in
            handleLightStateChange()
        }
    }
    
    private func stateButton(title: String, state: LightState) -> some View {
        Button(action: {
            currentState = state
        }) {
            HStack{
                if title == "Off" {
                    Image("sw_off")
                }
                Text(L(title))
                    .foregroundColor(currentState == state ? .white : .black)
                    
            }.frame(width: 140, height: 60)
                .background(currentState == state ? Color.customdeepblue : Color.white)
                .cornerRadius(10)
        }
    }

    private func handleLightStateChange() {
        flashTimer?.invalidate()  // Stop any previous flash sequence
        sosWorkItem?.cancel()     // Cancel SOS signal if active
        sosWorkItem = nil
        isLightOn = false
        turnFlashlight(on: false) // Ensure flashlight is off during transition
        
        switch currentState {
        case .off:
            isLightOn = false
            turnFlashlight(on: false)
        case .steady:
            isLightOn = true
            turnFlashlight(on: true)
        case .slowFlash:
            startFlashing(interval: 1.0)
        case .fastFlash:
            startFlashing(interval: 0.3)
        case .sos:
            startSOSSignal()
        }
    }

    private func turnFlashlight(on: Bool) {
        guard let device = AVCaptureDevice.default(for: .video), device.hasTorch else { return }
        do {
            try device.lockForConfiguration()
            device.torchMode = on ? .on : .off
            isLightOn = on // Synchronize the circle color with the flashlight state
            device.unlockForConfiguration()
        } catch {
            print("Flashlight could not be used")
        }
    }

    private func startFlashing(interval: Double) {
        flashTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in
            isLightOn.toggle()
            turnFlashlight(on: isLightOn)
        }
    }

    private func startSOSSignal() {
        sosWorkItem = DispatchWorkItem {
            let dotDuration: useconds_t = 300000  // 0.3 seconds for short (dot)
            let dashDuration: useconds_t = 900000 // 0.9 seconds for long (dash)
            let pauseDuration: useconds_t = 300000 // 0.3 seconds between flashes
            
            while self.currentState == .sos {
                // 3 short flashes (dot)
                for _ in 0..<3 {
                    guard self.currentState == .sos else { return } // Exit if SOS is deactivated
                    self.turnFlashlight(on: true)
                    usleep(dotDuration)
                    self.turnFlashlight(on: false)
                    usleep(pauseDuration)
                }
                
                usleep(dotDuration) // Slightly longer pause between letters
                
                // 3 long flashes (dash)
                for _ in 0..<3 {
                    guard self.currentState == .sos else { return } // Exit if SOS is deactivated
                    self.turnFlashlight(on: true)
                    usleep(dashDuration)
                    self.turnFlashlight(on: false)
                    usleep(pauseDuration)
                }
                
                usleep(dotDuration) // Slightly longer pause between letters
                
                // 3 short flashes (dot)
                for _ in 0..<3 {
                    guard self.currentState == .sos else { return } // Exit if SOS is deactivated
                    self.turnFlashlight(on: true)
                    usleep(dotDuration)
                    self.turnFlashlight(on: false)
                    usleep(pauseDuration)
                }
                
                // Longer pause before repeating SOS signal
                usleep(3000000) // 3-second pause before restarting the SOS signal
            }
        }
        // Execute SOS signal task in a background thread
        if let sosWorkItem = sosWorkItem {
            DispatchQueue.global().async(execute: sosWorkItem)
        }
    }
}

struct FlashlightView_Previews: PreviewProvider {
    static var previews: some View {
        FlashlightView()
    }
}
