import SwiftUI
import AVFoundation

struct RecordingSheet: View {
    @State private var recordingTime: TimeInterval = 0
    @State private var isRecording: Bool = false
    @State private var showPermissionAlert: Bool = false
    @State private var permissionDenied: Bool = false
    @State private var timer: Timer?
    @State private var waveformOffset: CGFloat = 0
    let onDismiss: () -> Void

    var body: some View {
        VStack(spacing: 0) {

            // Time display header
            Text(timeString(from: recordingTime))
                .font(Constants.Typography.mediumTitle)
                .foregroundColor(Constants.Colors.Foreground.primary)
                .frame(maxWidth: .infinity)
                .padding(.horizontal, 24)
                .padding(.top, 48)

            // Main content area
            VStack(spacing: 0) {
                // Waveform area
                GeometryReader { geometry in
                    ZStack {
                        Color.clear

                        // Waveform bars that scroll from center to left
                        HStack(spacing: 8) {
                            ForEach(0..<150, id: \.self) { index in
                                RoundedRectangle(cornerRadius: 100)
                                    .fill(Color(hex: "#D9D9D9"))
                                    .frame(width: 2, height: isRecording ? waveformHeight(for: index) : 2)
                            }
                        }
                        .offset(x: geometry.size.width / 2 + waveformOffset)
                        .animation(.linear(duration: 0.1), value: waveformOffset)
                    }
                    .clipped()
                }
                .frame(maxWidth: .infinity)
                .frame(maxHeight: .infinity)

                // Record button and footer
                VStack(spacing: 0) {
                    // Record/Stop button
                    Button(action: {
                        if isRecording {
                            stopRecording()
                        } else {
                            requestMicrophonePermission()
                        }
                    }) {
                        ZStack {
                            if isRecording {
                                // Stop button - rounded square
                                Circle()
                                    .fill(Constants.Colors.Background.Fog.thin)
                                    .frame(width: 100, height: 100)

                                RoundedRectangle(cornerRadius: 8)
                                    .fill(Constants.Colors.Accent.error)
                                    .frame(width: 32, height: 32)
                            } else {
                                // Record button - circle
                                Circle()
                                    .fill(Constants.Colors.Accent.error)
                                    .frame(width: 68, height: 68)

                                Circle()
                                    .fill(Constants.Colors.Background.Fog.thin)
                                    .frame(width: 100, height: 100)
                            }
                        }
                    }
                    .buttonStyle(PlainButtonStyle())

                    // Footer text
                    VStack(spacing: 0) {
                        HStack(spacing: 0) {
                            Text("1 min limit. ")
                                .font(Constants.Typography.xSmallRegular)
                                .foregroundColor(Constants.Colors.Foreground.inactive)

                            Button(action: {
                                print("Upgrade tapped")
                            }) {
                                Text("Upgrade")
                                    .font(Constants.Typography.xSmallRegular)
                                    .foregroundColor(Constants.Colors.Foreground.inactive)
                                    .underline()
                            }

                            Text(" to use longer audio (8 min)")
                                .font(Constants.Typography.xSmallRegular)
                                .foregroundColor(Constants.Colors.Foreground.inactive)
                        }
                        .padding(.horizontal, 24)
                        .padding(.vertical, 24)
                        .frame(height: 60)
                    }
                }
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Constants.Colors.Background.secondary)
        .onDisappear {
            // Clean up timer when view disappears
            timer?.invalidate()
            timer = nil
        }
        .alert("Microphone Access Required", isPresented: $showPermissionAlert) {
            Button("OK", role: .cancel) {
                showPermissionAlert = false
            }
            Button("Settings") {
                if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
                    UIApplication.shared.open(settingsURL)
                }
            }
        } message: {
            Text("Please enable microphone access in Settings to record audio.")
        }
    }

    private func timeString(from timeInterval: TimeInterval) -> String {
        let minutes = Int(timeInterval) / 60
        let seconds = Int(timeInterval) % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }

    private func requestMicrophonePermission() {
        AVAudioSession.sharedInstance().requestRecordPermission { granted in
            DispatchQueue.main.async {
                if granted {
                    // Permission granted, start recording
                    startRecording()
                } else {
                    // Permission denied
                    permissionDenied = true
                    showPermissionAlert = true
                }
            }
        }
    }

    private func startRecording() {
        isRecording = true
        recordingTime = 0
        waveformOffset = 0

        // Start timer for elapsed time and waveform animation
        timer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { _ in
            recordingTime += 0.05

            // Animate waveform scrolling from center to left
            waveformOffset -= 5

            // Stop at 60 seconds (1 minute limit)
            if recordingTime >= 60 {
                stopRecording()
            }
        }

        // TODO: Implement actual audio recording logic
        print("Recording started")
    }

    private func stopRecording() {
        isRecording = false
        timer?.invalidate()
        timer = nil
        waveformOffset = 0

        // TODO: Save and process the recording
        print("Recording stopped at \(timeString(from: recordingTime))")
    }

    private func waveformHeight(for index: Int) -> CGFloat {
        // Generate semi-random heights for waveform bars based on index and time
        let baseHeight: CGFloat = 5
        let maxHeight: CGFloat = 80

        // Calculate position relative to center
        let relativePosition = CGFloat(index) * 10 + waveformOffset

        // Only show height for bars that have been "captured" (past center)
        if relativePosition > 0 {
            return 2 // Not yet captured, show as dots
        }

        // Create varied heights using sine wave pattern for captured audio
        let phase = CGFloat(index) / 5 + recordingTime
        let amplitude = sin(phase) * cos(phase / 2) * sin(phase / 3)
        let height = amplitude * (maxHeight - baseHeight) / 2 + (maxHeight + baseHeight) / 2

        return abs(height)
    }
}

#Preview {
    RecordingSheet(onDismiss: {})
        .preferredColorScheme(.dark)
}
