//
//  MeterSettingsTabView.swift
//  USB Meter
//

import SwiftUI

struct MeterSettingsTabView: View {
    @EnvironmentObject private var meter: Meter

    let isMacIPadApp: Bool
    let onBackToHome: () -> Void

    @State private var editingName = false
    @State private var editingScreenTimeout = false
    @State private var editingScreenBrightness = false

    var body: some View {
        VStack(spacing: 0) {
            if isMacIPadApp {
                settingsMacHeader
            }
            ScrollView {
                VStack(spacing: 14) {
                    settingsCard(title: "Name", tint: meter.color) {
                        HStack {
                            Spacer()
                            if !editingName {
                                Text(meter.name)
                                    .foregroundColor(.secondary)
                            }
                            ChevronView(rotate: $editingName)
                        }
                        if editingName {
                            MeterNameEditorView(editingName: $editingName, newName: meter.name)
                        }
                    }

                    if meter.operationalState == .dataIsAvailable && meter.supportsManualTemperatureUnitSelection {
                        settingsCard(title: "Meter Temperature Unit", tint: .orange) {
                            Text("TC66 temperature is shown as degrees without assuming Celsius or Fahrenheit. Keep this matched to the unit configured on the device so you can interpret the reading correctly.")
                                .font(.footnote)
                                .foregroundColor(.secondary)
                            Picker("", selection: $meter.tc66TemperatureUnitPreference) {
                                ForEach(TemperatureUnitPreference.allCases) { unit in
                                    Text(unit.title).tag(unit)
                                }
                            }
                            .pickerStyle(SegmentedPickerStyle())
                        }
                    }

                    if meter.operationalState == .dataIsAvailable && meter.model == .TC66C {
                        settingsCard(title: "Screen Reporting", tint: .orange) {
                            MeterInfoRowView(label: "Current Screen", value: "Not Reported")
                            Text("TC66 is the exception: it does not report the current screen in the payload, so the app keeps this note here instead of showing it on the home screen.")
                                .font(.footnote)
                                .foregroundColor(.secondary)
                        }
                    }

                    if meter.operationalState == .dataIsAvailable {
                        settingsCard(
                            title: meter.reportsCurrentScreenIndex ? "Screen Controls" : "Page Controls",
                            tint: .indigo
                        ) {
                            if meter.reportsCurrentScreenIndex {
                                Text("Use these controls when you want to change the screen shown on the device without crowding the main meter view.")
                                    .font(.footnote)
                                    .foregroundColor(.secondary)
                            } else {
                                Text("Use these controls when you want to switch device pages without crowding the main meter view.")
                                    .font(.footnote)
                                    .foregroundColor(.secondary)
                            }

                            MeterScreenControlsView(showsHeader: false)
                        }
                    }

                    if meter.operationalState == .dataIsAvailable && meter.supportsUMSettings {
                        settingsCard(title: "Screen Timeout", tint: .purple) {
                            HStack {
                                Spacer()
                                if !editingScreenTimeout {
                                    Text(meter.screenTimeout > 0 ? "\(meter.screenTimeout) Minutes" : "Off")
                                        .foregroundColor(.secondary)
                                }
                                ChevronView(rotate: $editingScreenTimeout)
                            }
                            if editingScreenTimeout {
                                ScreenTimeoutEditorView()
                            }
                        }

                        settingsCard(title: "Screen Brightness", tint: .yellow) {
                            HStack {
                                Spacer()
                                if !editingScreenBrightness {
                                    Text("\(meter.screenBrightness)")
                                        .foregroundColor(.secondary)
                                }
                                ChevronView(rotate: $editingScreenBrightness)
                            }
                            if editingScreenBrightness {
                                ScreenBrightnessEditorView()
                            }
                        }
                    }
                }
                .padding()
            }
            .background(
                LinearGradient(
                    colors: [meter.color.opacity(0.14), Color.clear],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
            )
        }
    }

    private var settingsMacHeader: some View {
        HStack(spacing: 12) {
            Button(action: onBackToHome) {
                HStack(spacing: 4) {
                    Image(systemName: "chevron.left")
                        .font(.body.weight(.semibold))
                    Text("Back")
                }
                .foregroundColor(.accentColor)
            }
            .buttonStyle(.plain)

            Text("Meter Settings")
                .font(.headline)
                .lineLimit(1)

            Spacer()

            if meter.operationalState > .notPresent {
                RSSIView(RSSI: meter.btSerial.averageRSSI)
                    .frame(width: 18, height: 18)
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 10)
        .background(
            Rectangle()
                .fill(.ultraThinMaterial)
                .ignoresSafeArea(edges: .top)
        )
        .overlay(alignment: .bottom) {
            Rectangle()
                .fill(Color.secondary.opacity(0.12))
                .frame(height: 1)
        }
    }

    private func settingsCard<Content: View>(
        title: String,
        tint: Color,
        @ViewBuilder content: () -> Content
    ) -> some View {
        VStack(alignment: .leading, spacing: 12) {
            Text(title)
                .font(.headline)
            content()
        }
        .padding(18)
        .meterCard(tint: tint, fillOpacity: 0.18, strokeOpacity: 0.24)
    }
}
