//
//  ClockSettingsView.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/7/25.
//

import SwiftUI

/// Settings interface for clock customization
struct ClockSettingsView: View {
    
    // MARK: - Properties
    @State private var style: ClockStyle
    let onCommit: (ClockStyle) -> Void
    
    @State private var digitColor: Color = .white
    @State private var backgroundColor: Color = .black
    
    // MARK: - Init
    init(style: ClockStyle, onCommit: @escaping (ClockStyle) -> Void) {
        self._style = State(initialValue: style)
        self.onCommit = onCommit
    }
    
    // MARK: - Body
    var body: some View {
        NavigationView {
            Form {
                TimeFormatSection(style: $style)
                FontSection(style: $style)
                AppearanceSection(
                    style: $style,
                    digitColor: $digitColor,
                    backgroundColor: $backgroundColor,
                    onCommit: onCommit
                )
                DisplaySection(style: $style)
                OverlaySection(style: $style)
            }
            .navigationTitle("Clock Settings")
            .navigationBarTitleDisplayMode(.inline)
            .onAppear {
                digitColor = Color(hex: style.digitColorHex) ?? .white
                backgroundColor = Color(hex: style.backgroundHex) ?? .black
            }
            .onDisappear {
                onCommit(style)
            }
        }
    }
}

// MARK: - Supporting Views
private struct FontSection: View {
    @Binding var style: ClockStyle
    
    private let fontFamilies = ["System", "Arial", "Courier", "Georgia", "Helvetica", "Monaco", "Times New Roman", "Verdana"]
    private let fontWeights = ["Ultra Light", "Thin", "Light", "Regular", "Medium", "Semibold", "Bold", "Heavy", "Black"]
    private let fontDesigns = ["Default", "Serif", "Rounded", "Monospaced"]
    
    var body: some View {
        Section(header: Text("Font")) {
            // Font Family
            Picker("Family", selection: $style.fontFamily) {
                ForEach(fontFamilies, id: \.self) { family in
                    Text(family).tag(family)
                }
            }
            .pickerStyle(.menu)
            
            // Font Weight
            Picker("Weight", selection: $style.fontWeight) {
                ForEach(fontWeights, id: \.self) { weight in
                    Text(weight).tag(weight)
                }
            }
            .pickerStyle(.menu)
            
            // Font Design
            Picker("Design", selection: $style.fontDesign) {
                ForEach(fontDesigns, id: \.self) { design in
                    Text(design).tag(design)
                }
            }
            .pickerStyle(.menu)
            
            // Font Preview
            HStack {
                Text("Preview:")
                    .foregroundColor(.secondary)
                Spacer()
                Text("12:34")
                    .font(FontUtils.customFont(
                        size: 24,
                        family: style.fontFamily,
                        weight: style.fontWeight,
                        design: style.fontDesign
                    ))
                    .foregroundColor(.primary)
            }
        }
    }
}

private struct TimeFormatSection: View {
    @Binding var style: ClockStyle
    
    var body: some View {
        Section(header: Text("Time")) {
            Toggle("24‑Hour", isOn: $style.use24Hour)
            Toggle("Show Seconds", isOn: $style.showSeconds)
        }
    }
}

private struct AppearanceSection: View {
    @Binding var style: ClockStyle
    @Binding var digitColor: Color
    @Binding var backgroundColor: Color
    let onCommit: (ClockStyle) -> Void
    
    var body: some View {
        Section(header: Text("Appearance")) {
            ColorPicker("Background Color", selection: $backgroundColor, supportsOpacity: true)
            ColorPicker("Digit Color", selection: $digitColor, supportsOpacity: false)
            Toggle("Randomize Color (every minute)", isOn: $style.randomizeColor)
            
            Toggle("Stretched (auto-fit)", isOn: $style.stretched)
            
            if !style.stretched {
                HStack {
                    Text("Size")
                    Slider(value: $style.digitScale, in: 0.0...1.0)
                    Text("\(Int((min(max(style.digitScale, 0.0), 1.0)) * 100))%")
                        .frame(width: 50, alignment: .trailing)
                }
            }
            
            HStack {
                Text("Glow")
                Slider(value: $style.glowIntensity, in: 0...1)
                Text("\(Int(style.glowIntensity * 100))%")
                    .frame(width: 50, alignment: .trailing)
            }
            
            HStack {
                Text("Clock Opacity")
                Slider(value: $style.clockOpacity, in: 0.0...1.0)
                Text("\(Int(style.clockOpacity * 100))%")
                    .frame(width: 50, alignment: .trailing)
            }
        }
        .onChange(of: backgroundColor) { _, newValue in
            style.backgroundHex = newValue.toHex() ?? AppConstants.Defaults.backgroundColorHex
            style.clearColorCache()
        }
        .onChange(of: digitColor) { _, newValue in
            style.digitColorHex = newValue.toHex() ?? AppConstants.Defaults.digitColorHex
            style.clearColorCache()
        }
    }
}

private struct OverlaySection: View {
    @Binding var style: ClockStyle
    
    private let dateFormats = Date.availableDateFormats()
    
    var body: some View {
        Section(header: Text("Overlays")) {
            HStack {
                Text("Overlay Opacity")
                Slider(value: $style.overlayOpacity, in: 0.0...1.0)
                Text("\(Int(style.overlayOpacity * 100))%")
                    .frame(width: 50, alignment: .trailing)
            }
            
            Toggle("Battery Level", isOn: $style.showBattery)
            Toggle("Date", isOn: $style.showDate)
            
            if style.showDate {
                Picker("Date Format", selection: $style.dateFormat) {
                    ForEach(dateFormats, id: \.1) { format in
                        Text(format.0).tag(format.1)
                    }
                }
                .pickerStyle(.menu)
            }
        }
    }
}

private struct DisplaySection: View {
    @Binding var style: ClockStyle
    
    var body: some View {
        Section(header: Text("Display"), footer: Text("Keep the screen awake when in full-screen display mode. This prevents the device from sleeping while viewing the clock.")) {
            Toggle("Keep Awake in Display Mode", isOn: $style.keepAwake)
        }
        
        Section(header: Text("Focus Modes"), footer: Text("Control how the app behaves when Focus modes (Do Not Disturb) are active. When enabled, audio may be paused during Focus mode.")) {
            Toggle("Respect Focus Modes", isOn: $style.respectFocusModes)
        }
    }
}

// MARK: - Preview
#Preview {
    ClockSettingsView(
        style: ClockStyle(),
        onCommit: { _ in }
    )
}
