//
//  TimerView.swift
//  EzTimer
//
//  Created by Jared Evans on 12/17/25.
//

import SwiftUI

struct TimerView: View {
    @ObservedObject var viewModel: TimerViewModel
    @State private var selectedPresets: Set<Int> = []
    @State private var selectedLabelIndex: Int?
    
    // For handling renaming (local state moved from ContentView)
    @State private var isRenaming = false
    @State private var renamingIndex: Int?
    @State private var renamingText = ""
    
    let presetTimes = [1, 2, 5, 10, 15, 20, 25, 30, 40, 45, 50, 60]
    
    var body: some View {
        VStack(spacing: 20) {
            timerControls
            messageInput
            presetsGrid
            colorSelectionRow
            customMessagesGrid
            Spacer()
        }
        .padding(.horizontal, 12)
        .padding(.vertical)
        .padding(.top, 8)
        .onAppear {
            selectedPresets.removeAll()
            selectedLabelIndex = nil
        }
        .alert("Rename Button", isPresented: $isRenaming) {
            TextField("Button Label", text: $renamingText)
            Button("Save") {
                if let index = renamingIndex {
                    viewModel.updateCustomLabel(at: index, with: renamingText)
                }
            }
            Button("Cancel", role: .cancel) { }
        }
    }
    
    // MARK: - Subviews
    
    private var timerControls: some View {
        GlassCard {
            VStack(spacing: 16) {
                HStack(spacing: 20) {
                    // Minutes Adjustment
                    VStack(spacing: 8) {
                        AdjustmentButton(icon: "chevron.up") { viewModel.adjustTime(bySeconds: 60) }
                        AdjustmentButton(icon: "chevron.down") { viewModel.adjustTime(bySeconds: -60) }
                    }
                    
                    // Time Display (Compact)
                    Text(viewModel.timeString())
                        .font(.system(size: 96, weight: .regular, design: .rounded))
                        .foregroundStyle(.primary)
                        .contentTransition(.numericText(value: Double(Int(ceil(viewModel.timeRemaining)))))
                        .minimumScaleFactor(0.5)
                        .lineLimit(1)
                        .shadow(color: .black.opacity(0.1), radius: 2, x: 0, y: 1)
                    
                    // Seconds Adjustment
                    VStack(spacing: 8) {
                        AdjustmentButton(icon: "chevron.up") { viewModel.adjustTime(bySeconds: 1) }
                        AdjustmentButton(icon: "chevron.down") { viewModel.adjustTime(bySeconds: -1) }
                    }
                }
                
                // Controls Row
                HStack(spacing: 16) {
                    ModernButton(title: "Reset", icon: "arrow.counterclockwise", action: {
                        withAnimation { viewModel.resetTimer() }
                        selectedPresets.removeAll() // Clear selection on reset
                        selectedLabelIndex = nil // Clear custom message selection
                        viewModel.notificationMessage = "" // Clear message text
                    }, backgroundColor: .neonOrange)
                    
                    ModernButton(title: "Start", icon: viewModel.isActive ? "pause.fill" : "play.fill", action: {
                        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                        withAnimation { viewModel.startCountdown() }
                    }, backgroundColor: viewModel.isActive ? .gray : .neonBlue)
                    .disabled(viewModel.isActive)
                }
            }
        }
        .glow(color: viewModel.isActive ? .neonBlue : .clear, isActive: viewModel.isActive)
    }
    
    private var messageInput: some View {
        HStack {
                Image(systemName: "pencil.and.scribble")
                    .foregroundColor(.secondary)
                
                TextField("Timer message (optional)", text: $viewModel.notificationMessage)
                    .font(.subheadline)
                
                if !viewModel.notificationMessage.isEmpty {
                    Button(action: {
                        viewModel.notificationMessage = ""
                        selectedLabelIndex = nil
                    }) {
                        Image(systemName: "xmark.circle.fill")
                        .foregroundColor(.secondary)
                    }
                }
                
                Divider()
                    .frame(height: 20)
                
                Button(action: {
                    withAnimation {
                        viewModel.isFlashEnabled.toggle()
                    }
                }) {
                    Image(systemName: viewModel.isFlashEnabled ? "lightbulb.fill" : "lightbulb")
                        .font(.title3)
                        .foregroundColor(viewModel.isFlashEnabled ? .yellow : .secondary)
                        .padding(8)
                        .background(viewModel.isFlashEnabled ? Color.yellow.opacity(0.2) : Color.clear)
                        .clipShape(Circle())
                }
            }
            .padding(.horizontal, 8)
            .padding(.vertical, 0)
        .padding(.horizontal, 12)
        .padding(.vertical, 6)
        .liquidGlass(cornerRadius: 24)
    }
    
    private var presetsGrid: some View {
        GlassCard {
            LazyVGrid(columns: [GridItem(.adaptive(minimum: 70))], spacing: 12) {
                ForEach(presetTimes, id: \.self) { minutes in
                    presetButtonLabel(minutes: minutes)
                        .onTapGesture {
                            selectedPresets = [minutes]
                            withAnimation { viewModel.setTime(minutes: minutes) }
                        }
                        .onLongPressGesture(minimumDuration: 0.5) {
                            let generator = UIImpactFeedbackGenerator(style: .medium)
                            generator.impactOccurred()
                            selectedPresets.insert(minutes)
                            withAnimation { viewModel.addTime(minutes: minutes) }
                        }
                }
            }
        }
        .disabled(viewModel.isActive)
        .opacity(viewModel.isActive ? 0.1 : 1.0)
    }
    
    private func presetButtonLabel(minutes: Int) -> some View {
        VStack(spacing: 0) {
            Text("\(minutes)")
                .font(.title3)
                .fontWeight(.bold)
            Text("min")
                .font(.caption2)
                .foregroundColor(.secondary)
        }
        .frame(maxWidth: .infinity)
        .frame(height: 50)
        .background(selectedPresets.contains(minutes) ? Color.blue.opacity(0.6) : Color.blue.opacity(0.1))
        .background(.ultraThinMaterial)
        .clipShape(Circle())
        .overlay(
            Circle()
                .stroke(selectedPresets.contains(minutes) ? Color.white.opacity(0.6) : Color.white.opacity(0.2), lineWidth: 1.5)
        )
        .shadow(color: selectedPresets.contains(minutes) ? Color.blue.opacity(0.5) : Color.clear, radius: 4)
    }
    
    // MARK: - Color Selection Row
    private var colorSelectionRow: some View {
        GlassCard {
            HStack(spacing: 12) {
                // Color circles
                HStack(spacing: 12) {
                    ForEach(TimerViewModel.TimerColor.allCases, id: \.self) { colorOption in
                        Circle()
                            .fill(colorOption.color)
                            .frame(width: 30, height: 30)
                            .overlay(
                                Circle()
                                    .stroke(Color.white, lineWidth: viewModel.selectedColor == colorOption ? 3 : 0)
                            )
                            .shadow(color: colorOption.color.opacity(0.6), radius: viewModel.selectedColor == colorOption ? 8 : 2)
                            .scaleEffect(viewModel.selectedColor == colorOption ? 1.1 : 1.0)
                            .onTapGesture {
                                withAnimation(.spring(response: 0.3, dampingFraction: 0.6)) {
                                    viewModel.selectedColor = colorOption
                                }
                            }
                    }
                }
                
                Divider()
                    .frame(height: 24)
                
                // Flash mode icons
                HStack(spacing: 8) {
                    // Soft fade icon
                    flashModeButton(mode: .soft)
                    
                    // Rapid strobe icon
                    flashModeButton(mode: .rapid)
                }
            }
            .padding(.vertical, 4)
            .frame(maxWidth: .infinity)
        }
        .disabled(viewModel.isActive)
        .opacity(viewModel.isActive ? 0.1 : 1.0)
    }
    
    private func flashModeButton(mode: TimerViewModel.FlashMode) -> some View {
        let isSelected = viewModel.selectedFlashMode == mode
        return Button(action: {
            viewModel.selectedFlashMode = mode
        }) {
            Image(systemName: mode.iconName)
                .font(.body)
                .foregroundColor(isSelected ? .white : .secondary)
                .frame(width: 32, height: 32)
                .background(isSelected ? Color.blue.opacity(0.6) : Color.clear)
                .clipShape(Circle())
                .overlay(
                    Circle()
                        .stroke(isSelected ? Color.white : Color.white.opacity(0.2), lineWidth: isSelected ? 2 : 1)
                )
                .shadow(color: isSelected ? Color.blue.opacity(0.5) : Color.clear, radius: 4)
                .contentTransition(.identity)
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    private var customMessagesGrid: some View {
        GlassCard {
            LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 2), spacing: 12) {
                ForEach(0..<4, id: \.self) { index in
                    let label = viewModel.customLabels[index]
                    customMessageButtonLabel(label: label, index: index)
                        .onTapGesture {
                            if label.isEmpty {
                                startRenaming(at: index)
                            } else {
                                selectedLabelIndex = index
                                viewModel.notificationMessage = label
                            }
                        }
                        .onLongPressGesture(minimumDuration: 0.5) {
                            startRenaming(at: index)
                        }
                }
            }
        }
        .disabled(viewModel.isActive)
        .opacity(viewModel.isActive ? 0.1 : 1.0)
    }
    
    private func customMessageButtonLabel(label: String, index: Int) -> some View {
        HStack {
            if label.isEmpty {
                Image(systemName: "plus")
            } else {
                Text(label)
                    .lineLimit(1)
            }
        }
        .font(.subheadline)
        .frame(maxWidth: .infinity)
        .padding(.vertical, 16)
        .background(selectedLabelIndex == index ? Color.indigo.opacity(0.6) : Color.indigo.opacity(0.2))
        .background(.ultraThinMaterial)
        .cornerRadius(16)
        .overlay(
            RoundedRectangle(cornerRadius: 16)
                .stroke(selectedLabelIndex == index ? Color.white.opacity(0.6) : Color.white.opacity(0.2), lineWidth: 1.5)
        )
        .shadow(color: selectedLabelIndex == index ? Color.indigo.opacity(0.5) : Color.clear, radius: 4)
    }
    
    private func startRenaming(at index: Int) {
        renamingIndex = index
        renamingText = viewModel.customLabels[index]
        isRenaming = true
    }
}

struct AdjustmentButton: View {
    let icon: String
    let action: () -> Void
    
    var body: some View {
        Button(action: {
            withAnimation { action() }
        }) {
            Image(systemName: icon)
                .font(.title3)
                .frame(width: 44, height: 44)
                .background(.ultraThinMaterial)
                .clipShape(Circle())
                .overlay(Circle().stroke(Color.white.opacity(0.2), lineWidth: 1))
        }
        .buttonStyle(PlainButtonStyle())
    }
}
