import SwiftUI

struct SerialView: View {
    @Environment(\.presentationMode) private var presentationMode
    
    @State var selectedDevice: Device = .MacBookAir
    @State var selectedModel: Model? = nil
    @State var generatedSerial = ""
    @State var isSerialTapped = false
    @State var showModelNumber = false
    @State var showModelIdentifier = true
    @State private var clipboardConfirmationShown = false
    @State private var seadmed = Seadmed()
    @State private var isEditing = false
    @EnvironmentObject var serialHistory: SerialHistory
    @State private var selectedSerialForQR: String?
    @State private var isQRSheetPresented = false

    @State private var numberOfSerials: Double = 1

    
    func copyToClipboard(_ text: String) {
        let pasteboard = NSPasteboard.general
        pasteboard.clearContents()
        pasteboard.setString(text, forType: .string)
        clipboardConfirmationShown = true
        
        // Clear generated serials after copying
        generatedSerial = ""
        
        // Dismiss the confirmation after a delay
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            clipboardConfirmationShown = false
        }
    }

    // Function to determine the label for the copy button
    private func copyButtonLabel() -> String {
        let serialCount = generatedSerial.components(separatedBy: "\n").filter { !$0.isEmpty }.count
        return serialCount > 1 ? "Kopeeri seerianumbrid" : "Kopeeri seerianumber"
    }

    
    
    var body: some View {
        Form {
            Section(header:
                        VStack(alignment:.leading) {
                Text("Intel seerianumbrite genereerimine")
                Text("Seerianumbrid on unikaalsed identifikaatorid, mida kasutatakse seadme autentimiseks ja jälgimiseks. Seerianumbrite generaator loob macOS seadmetele päris seerianumbrid, mis vastavad Apple standarditele.")
                    .font(.callout)
                    .foregroundStyle(.secondary)
            }){
                Picker("Seade:", selection: $selectedDevice) {
                    ForEach(Seadmed.allDevices, id: \.self) { device in
                        Text(device.rawValue)
                            .foregroundColor(selectedDevice == device ? .primary : .secondary)

                    }
                }
                .pickerStyle(.segmented)
                Toggle(isOn: $showModelNumber) {
                    Label("Näita mudeli numbrit", systemImage: "text.badge.checkmark")
                        .symbolRenderingMode(.multicolor)
                }
                Toggle(isOn: $showModelIdentifier) {
                    Label("Näita mudeli identifikaatorit", systemImage: "barcode.viewfinder")
                        .symbolRenderingMode(.multicolor)
                }
            }
            
            Section("Mudeli valik") {
                List(Seadmed.saadavadMudelid(for: selectedDevice), id: \.self, selection: $selectedModel) { model in
                    ModelItemView(model: model, showModelNumber: showModelNumber, showModelIdentifier: showModelIdentifier)
                    
                }
            }
            
            Section("Genereeritud seerianumber") {
                LabeledContent("Seerianumber:") {
                    if clipboardConfirmationShown {
                        Label("Seerianumber kopeeritud lõikelauale!", systemImage: "checkmark.circle")
                            .foregroundColor(.green)
                    } else {
                        Text(generatedSerial)
                    }
                }
                HStack {
                    Button("Genereeri seerianumber") {
                        generateSerialNumber()
                    }
                    .controlSize(.large)
                    .disabled(selectedModel == nil)
                    .buttonStyle(.borderedProminent)
                    
                    Button(copyButtonLabel()) {
                        if !generatedSerial.isEmpty {
                            copyToClipboard(generatedSerial)
                        }
                    }

                    .controlSize(.large)
                    .buttonStyle(.bordered)
                    .disabled(generatedSerial.isEmpty)
                    
                }
            }
            Text("Palun veendu, et need genereeritud seerianumbrid ei oleks pilve- ega MDM lukus [siin](https://backend.replace.tech/CheckMend).")
                .font(.callout)
                .foregroundStyle(.secondary)
        }
        .sheet(isPresented: $isQRSheetPresented) {
            if let selectedSerial = selectedSerialForQR {
                QRCodeSheet(serial: selectedSerial)
            }
        }
        .formStyle(.grouped)
        .navigationTitle("Seerianumbrite generaator")
        .navigationSubtitle("Genereeri Intel seadmete seerianumbreid")
        .navigationBarBackButtonHidden(false)
    }
    
    
    private func generateSerialNumber() {
        guard let modelIdentifier = selectedModel?.identifier else {
            generatedSerial = "Palun vali mudel"
            isSerialTapped = false
            return
        }

        if let serialsString = SendCommand(modelIdentifier: modelIdentifier, numberOfSerials: Int(numberOfSerials)) {
            let serialsArray = serialsString.components(separatedBy: .newlines).filter { !$0.isEmpty }
            generatedSerial = serialsArray.joined(separator: "\n")
            isSerialTapped = true

            // Show the QR code sheet only if a single serial is generated
            if serialsArray.count == 1 {
                selectedSerialForQR = serialsArray.first
                isQRSheetPresented = true
            }

            for serial in serialsArray {
                serialHistory.addRecord(serial: serial, model: selectedModel!)
            }
        } else {
            generatedSerial = "Viga seerianumbrite genereerimisel"
            isSerialTapped = false
        }
    }
}