import SwiftUI
import SwiftData

// Edit existing word replacement entry
struct EditReplacementSheet: View {
    let replacement: WordReplacement
    let modelContext: ModelContext

    @Environment(\.dismiss) private var dismiss

    @State private var originalWord: String
    @State private var replacementWord: String
    @State private var showAlert = false
    @State private var alertMessage = ""

    // MARK: – Initialiser
    init(replacement: WordReplacement, modelContext: ModelContext) {
        self.replacement = replacement
        self.modelContext = modelContext
        _originalWord = State(initialValue: replacement.originalText)
        _replacementWord = State(initialValue: replacement.replacementText)
    }

    var body: some View {
        VStack(spacing: 0) {
            header
                .overlay(Divider().overlay(Color.proatBorder), alignment: .bottom)
            formContent
        }
        .frame(width: 460, height: 560)
        .alert("Vervanging", isPresented: $showAlert) {
            Button("OK", role: .cancel) {}
        } message: {
            Text(alertMessage)
        }
    }

    // MARK: – Subviews
    private var header: some View {
        HStack {
            Button("Annuleren", role: .cancel) { dismiss() }
                .buttonStyle(.borderless)
                .keyboardShortcut(.escape, modifiers: [])

            Spacer()

            Text("Vervanging bewerken")
                .font(ProatFont.sectie)
                .foregroundColor(.proatText1)

            Spacer()

            Button("Opslaan") { saveChanges() }
                .buttonStyle(.borderedProminent)
                .tint(.proatTeal)
                .controlSize(.small)
                .disabled(originalWord.isEmpty || replacementWord.isEmpty)
                .keyboardShortcut(.return, modifiers: [])
        }
        .padding(.horizontal, ProatSpacing.m)
        .padding(.vertical, ProatSpacing.s)
        .background(Color.proatBgRaised)
    }

    private var formContent: some View {
        ScrollView {
            VStack(spacing: 20) {
                descriptionSection
                inputSection
            }
            .padding(.vertical)
        }
    }

    private var descriptionSection: some View {
        Text("Wijzig het woord of de zin die automatisch vervangen moet worden.")
            .font(ProatFont.body)
            .foregroundColor(.proatText2)
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.horizontal, ProatSpacing.m)
            .padding(.top, ProatSpacing.xs)
    }

    private var inputSection: some View {
        VStack(spacing: ProatSpacing.m) {
            // Original Text Field
            VStack(alignment: .leading, spacing: 6) {
                HStack {
                    Text("Originele tekst")
                        .font(ProatFont.sectie)
                        .foregroundColor(.proatText1)
                    Text("Verplicht")
                        .font(ProatFont.klein)
                        .foregroundColor(.proatText3)
                }
                TextField("Voer woord of zin in om te vervangen (gebruik komma's voor meerdere)", text: $originalWord)
                    .textFieldStyle(.roundedBorder)
                    .font(ProatFont.mono)

            }
            .padding(.horizontal, ProatSpacing.m)

            // Replacement Text Field
            VStack(alignment: .leading, spacing: 6) {
                HStack {
                    Text("Vervangende tekst")
                        .font(ProatFont.sectie)
                        .foregroundColor(.proatText1)
                    Text("Verplicht")
                        .font(ProatFont.klein)
                        .foregroundColor(.proatText3)
                }
                TextEditor(text: $replacementWord)
                    .font(ProatFont.mono)
                    .frame(height: 100)
                    .padding(ProatSpacing.xs)
                    .background(Color.proatBgSunken)
                    .clipShape(RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous))
                    .overlay(
                        RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                            .stroke(Color.proatBorder, lineWidth: 1)
                    )
            }
            .padding(.horizontal, ProatSpacing.m)
        }
    }

    // MARK: – Actions
    private func saveChanges() {
        let newOriginal = originalWord.trimmingCharacters(in: .whitespacesAndNewlines)
        let newReplacement = replacementWord
        let tokens = newOriginal
            .split(separator: ",")
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { !$0.isEmpty }
        guard !tokens.isEmpty, !newReplacement.isEmpty else { return }

        // Check for duplicates (excluding current replacement)
        let newTokensPairs = tokens.map { (original: $0, lowercased: $0.lowercased()) }

        let descriptor = FetchDescriptor<WordReplacement>()
        if let allReplacements = try? modelContext.fetch(descriptor) {
            for existingReplacement in allReplacements {
                // Skip checking against itself
                if existingReplacement.id == replacement.id {
                    continue
                }

                let existingTokens = existingReplacement.originalText
                    .split(separator: ",")
                    .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
                    .filter { !$0.isEmpty }

                for tokenPair in newTokensPairs {
                    if existingTokens.contains(tokenPair.lowercased) {
                        alertMessage = "'\(tokenPair.original)' bestaat al in de vervangingen"
                        showAlert = true
                        return
                    }
                }
            }
        }

        // Update the replacement
        replacement.originalText = newOriginal
        replacement.replacementText = newReplacement

        do {
            try modelContext.save()
            dismiss()
        } catch {
            alertMessage = "Kon wijzigingen niet opslaan: \(error.localizedDescription)"
            showAlert = true
        }
    }
}