import SwiftUI
import SwiftData

enum VocabularySortMode: String {
    case wordAsc = "wordAsc"
    case wordDesc = "wordDesc"
}

struct VocabularyView: View {
    @Query private var vocabularyWords: [VocabularyWord]
    @Environment(\.modelContext) private var modelContext
    @ObservedObject var whisperPrompt: WhisperPrompt
    @State private var newWord = ""
    @State private var showAlert = false
    @State private var alertMessage = ""
    @State private var sortMode: VocabularySortMode = .wordAsc

    init(whisperPrompt: WhisperPrompt) {
        self.whisperPrompt = whisperPrompt

        if let savedSort = UserDefaults.standard.string(forKey: "vocabularySortMode"),
           let mode = VocabularySortMode(rawValue: savedSort) {
            _sortMode = State(initialValue: mode)
        }
    }

    private var sortedItems: [VocabularyWord] {
        switch sortMode {
        case .wordAsc:
            return vocabularyWords.sorted { $0.word.localizedCaseInsensitiveCompare($1.word) == .orderedAscending }
        case .wordDesc:
            return vocabularyWords.sorted { $0.word.localizedCaseInsensitiveCompare($1.word) == .orderedDescending }
        }
    }

    private func toggleSort() {
        sortMode = (sortMode == .wordAsc) ? .wordDesc : .wordAsc
        UserDefaults.standard.set(sortMode.rawValue, forKey: "vocabularySortMode")
    }

    private var shouldShowAddButton: Bool {
        !newWord.isEmpty
    }

    var body: some View {
        VStack(alignment: .leading, spacing: ProatSpacing.l) {
            HStack(alignment: .top, spacing: ProatSpacing.s) {
                Image(systemName: "info.circle.fill")
                    .foregroundColor(.proatTeal)
                    .font(.system(size: 14))
                Text("Voeg woorden toe zodat Proat ze goed herkent. (Vereist AI-verfijning)")
                    .font(ProatFont.klein)
                    .foregroundColor(.proatText2)
                    .fixedSize(horizontal: false, vertical: true)
                Spacer(minLength: 0)
            }
            .proatCard(padding: ProatSpacing.s)

            HStack(spacing: ProatSpacing.xs) {
                TextField("Woord aan woordenboek toevoegen", text: $newWord)
                    .textFieldStyle(.roundedBorder)
                    .font(ProatFont.body)
                    .onSubmit { addWords() }

                if shouldShowAddButton {
                    Button(action: addWords) {
                        Image(systemName: "plus.circle.fill")
                            .symbolRenderingMode(.hierarchical)
                            .foregroundStyle(Color.proatTeal)
                            .font(.system(size: 16, weight: .semibold))
                    }
                    .buttonStyle(.borderless)
                    .disabled(newWord.isEmpty)
                    .help("Woord toevoegen")
                }
            }
            .animation(.easeInOut(duration: 0.2), value: shouldShowAddButton)

            if !vocabularyWords.isEmpty {
                VStack(alignment: .leading, spacing: ProatSpacing.s) {
                    Button(action: toggleSort) {
                        HStack(spacing: 4) {
                            Text("Woorden in woordenboek (\(vocabularyWords.count))")
                                .font(.system(size: 12, weight: .medium))
                                .foregroundColor(.proatText2)

                            Image(systemName: sortMode == .wordAsc ? "chevron.up" : "chevron.down")
                                .font(ProatFont.klein)
                                .foregroundColor(.proatTeal)
                        }
                    }
                    .buttonStyle(.plain)
                    .help("Alfabetisch sorteren")

                    ScrollView {
                        FlowLayout(spacing: ProatSpacing.xs) {
                            ForEach(sortedItems) { item in
                                VocabularyWordView(item: item) {
                                    removeWord(item)
                                }
                            }
                        }
                        .padding(.vertical, 4)
                    }
                    .frame(maxHeight: 200)
                }
                .padding(.top, 4)
            }
        }
        .padding()
        .alert("Woordenboek", isPresented: $showAlert) {
            Button("OK", role: .cancel) {}
        } message: {
            Text(alertMessage)
        }
    }
    
    private func addWords() {
        let input = newWord.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !input.isEmpty else { return }
        if let error = DictionaryService.addVocabularyWords(input, existing: Array(vocabularyWords), context: modelContext) {
            alertMessage = error
            showAlert = true
            return
        }
        newWord = ""
    }

    private func removeWord(_ word: VocabularyWord) {
        modelContext.delete(word)

        do {
            try modelContext.save()
        } catch {
            // Rollback the delete to restore UI consistency
            modelContext.rollback()
            alertMessage = "Kon woord niet verwijderen: \(error.localizedDescription)"
            showAlert = true
        }
    }
}

struct VocabularyWordView: View {
    let item: VocabularyWord
    let onDelete: () -> Void
    @State private var isDeleteHovered = false
    @State private var isChipHovered = false

    var body: some View {
        HStack(spacing: 6) {
            Text(item.word)
                .font(ProatFont.mono)
                .lineLimit(1)
                .foregroundColor(.proatText1)

            Button(action: onDelete) {
                Image(systemName: "xmark.circle.fill")
                    .symbolRenderingMode(.hierarchical)
                    .foregroundStyle(isDeleteHovered ? Color.proatError : Color.proatText3)
                    .contentTransition(.symbolEffect(.replace))
            }
            .buttonStyle(.borderless)
            .help("Woord verwijderen")
            .opacity(isChipHovered || isDeleteHovered ? 1 : 0.55)
            .onHover { hover in
                withAnimation(.easeInOut(duration: 0.2)) {
                    isDeleteHovered = hover
                }
            }
        }
        .padding(.horizontal, ProatSpacing.xs)
        .padding(.vertical, 6)
        .background {
            RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                .fill(isChipHovered ? Color.proatTealTint : Color.proatBgSunken)
        }
        .overlay {
            RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                .stroke(isChipHovered ? Color.proatTeal.opacity(0.5) : Color.proatBorder, lineWidth: 1)
        }
        .proatShadowRust()
        .onHover { hover in
            withAnimation(.easeInOut(duration: 0.18)) {
                isChipHovered = hover
            }
        }
    }
}
