import SwiftUI

struct AddCustomModelCardView: View {
    @ObservedObject var customModelManager: CustomCloudModelManager
    var onModelAdded: () -> Void
    var editingModel: CustomCloudModel? = nil
    
    @State private var isExpanded = false
    @State private var displayName = ""
    @State private var apiEndpoint = ""
    @State private var apiKey = ""
    @State private var modelName = ""
    @State private var isMultilingual = true
    
    @State private var validationErrors: [String] = []
    @State private var showingAlert = false
    @State private var isSaving = false
    
    var body: some View {
        VStack(spacing: 0) {
            // Simple Add Model Button
            if !isExpanded {
                Button(action: {
                    withAnimation(.interpolatingSpring(stiffness: 170, damping: 20)) {
                        isExpanded = true
                        // Pre-fill values - either from editing model or defaults
                        if let editing = editingModel {
                            displayName = editing.displayName
                            apiEndpoint = editing.apiEndpoint
                            apiKey = editing.apiKey
                            modelName = editing.modelName
                            isMultilingual = editing.isMultilingualModel
                        } else {
                            // Pre-fill some default values when adding new
                            if apiEndpoint.isEmpty {
                                apiEndpoint = "https://api.example.com/v1/audio/transcriptions"
                            }
                            if modelName.isEmpty {
                                modelName = "large-v3-turbo"
                            }
                        }
                    }
                }) {
                    HStack(spacing: ProatSpacing.xs) {
                        Image(systemName: "plus")
                            .font(.system(size: 14, weight: .medium))
                        Text(editingModel != nil ? "Model bewerken" : "Model toevoegen")
                            .font(.system(size: 14, weight: .semibold))
                    }
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, ProatSpacing.s)
                    .background(LinearGradient.proatTeal)
                    .clipShape(RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous))
                }
                .buttonStyle(.plain)
                .proatShadowKaart()
            }
            
            // Expandable Form Section
            if isExpanded {
                VStack(alignment: .leading, spacing: ProatSpacing.l - 4) {
                    // Header
                    HStack {
                        Text(editingModel != nil ? "Eigen model bewerken" : "Eigen model toevoegen")
                            .font(ProatFont.sectie)
                            .foregroundColor(.proatText1)

                        Spacer()

                        Button(action: {
                            withAnimation(.interpolatingSpring(stiffness: 170, damping: 20)) {
                                isExpanded = false
                                clearForm()
                            }
                        }) {
                            Image(systemName: "xmark")
                                .font(.system(size: 12, weight: .medium))
                                .foregroundColor(.proatText2)
                        }
                        .buttonStyle(.plain)
                    }

                    // Disclaimer
                    HStack(spacing: ProatSpacing.xs) {
                        Image(systemName: "exclamationmark.triangle.fill")
                            .foregroundColor(.proatWarn)
                            .font(ProatFont.klein)
                        Text("Alleen OpenAI-compatibele transcriptie-API's worden ondersteund")
                            .font(ProatFont.klein)
                            .foregroundColor(.proatText2)
                    }
                    .padding(.horizontal, ProatSpacing.s)
                    .padding(.vertical, ProatSpacing.xs)
                    .background(Color.proatWarn.opacity(0.1))
                    .clipShape(RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous))

                    // Form fields
                    VStack(alignment: .leading, spacing: ProatSpacing.m) {
                        FormField(title: "Weergavenaam", text: $displayName, placeholder: "Mijn eigen model")
                        FormField(title: "API-endpoint", text: $apiEndpoint, placeholder: "https://api.example.com/v1/audio/transcriptions")
                        FormField(title: "API-sleutel", text: $apiKey, placeholder: "jouw-api-sleutel", isSecure: true)
                        FormField(title: "Modelnaam", text: $modelName, placeholder: "whisper-1")

                        Toggle("Meertalig model", isOn: $isMultilingual)
                    }
                    
                    // Action buttons
                    HStack(spacing: ProatSpacing.s) {
                        Button(action: {
                            withAnimation(.interpolatingSpring(stiffness: 170, damping: 20)) {
                                isExpanded = false
                                clearForm()
                            }
                        }) {
                            Text("Annuleren")
                                .font(.system(size: 13, weight: .medium))
                                .foregroundColor(.proatText2)
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, ProatSpacing.xs + 2)
                                .background(Color.proatBgSunken)
                                .clipShape(RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous))
                        }
                        .buttonStyle(.plain)

                        Button(action: {
                            addModel()
                        }) {
                            HStack(spacing: ProatSpacing.xs - 2) {
                                if isSaving {
                                    ProgressView()
                                        .scaleEffect(0.8)
                                        .frame(width: 14, height: 14)
                                } else {
                                    Image(systemName: editingModel != nil ? "checkmark.circle.fill" : "plus.circle.fill")
                                        .font(.system(size: 14))
                                }
                                Text(editingModel != nil ? "Model bijwerken" : "Model toevoegen")
                                    .font(.system(size: 13, weight: .semibold))
                            }
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, ProatSpacing.xs + 2)
                            .background(
                                RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                                    .fill(isFormValid
                                          ? AnyShapeStyle(LinearGradient.proatTeal)
                                          : AnyShapeStyle(Color.proatText3))
                            )
                            .proatShadowRust()
                        }
                        .buttonStyle(.plain)
                        .disabled(!isFormValid || isSaving)
                    }
                }
                .padding(ProatSpacing.m)
                .background(
                    RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous)
                        .fill(Color.proatBgRaised)
                        .overlay(
                            RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous)
                                .stroke(Color.proatBorder, lineWidth: 1)
                        )
                )
            }
        }
        .alert("Validatiefouten", isPresented: $showingAlert) {
            Button("OK") { }
        } message: {
            Text(validationErrors.joined(separator: "\n"))
        }
        .onChange(of: editingModel) { oldValue, newValue in
            if newValue != nil {
                withAnimation(.interpolatingSpring(stiffness: 170, damping: 20)) {
                    isExpanded = true
                    // Pre-fill values from editing model
                    if let editing = newValue {
                        displayName = editing.displayName
                        apiEndpoint = editing.apiEndpoint
                        apiKey = editing.apiKey
                        modelName = editing.modelName
                        isMultilingual = editing.isMultilingualModel
                    }
                }
            }
        }
    }
    
    private var isFormValid: Bool {
        !displayName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&
        !apiEndpoint.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&
        !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&
        !modelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }
    
    private func clearForm() {
        displayName = ""
        apiEndpoint = ""
        apiKey = ""
        modelName = ""
        isMultilingual = true
    }
    
    private func addModel() {
        let trimmedDisplayName = displayName.trimmingCharacters(in: .whitespacesAndNewlines)
        let trimmedApiEndpoint = apiEndpoint.trimmingCharacters(in: .whitespacesAndNewlines)
        let trimmedApiKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
        let trimmedModelName = modelName.trimmingCharacters(in: .whitespacesAndNewlines)
        
        // Generate a name from display name (lowercase, no spaces)
        let generatedName = trimmedDisplayName.lowercased().replacingOccurrences(of: " ", with: "-")
        
        validationErrors = customModelManager.validateModel(
            name: generatedName,
            displayName: trimmedDisplayName,
            apiEndpoint: trimmedApiEndpoint,
            apiKey: trimmedApiKey,
            modelName: trimmedModelName,
            excludingId: editingModel?.id
        )
        
        if !validationErrors.isEmpty {
            showingAlert = true
            return
        }
        
        isSaving = true

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            if let editing = editingModel {
                let updatedModel = CustomCloudModel(
                    id: editing.id,
                    name: generatedName,
                    displayName: trimmedDisplayName,
                    description: "Eigen transcriptiemodel",
                    apiEndpoint: trimmedApiEndpoint,
                    modelName: trimmedModelName,
                    isMultilingual: isMultilingual
                )
                
                if APIKeyManager.shared.saveCustomModelAPIKey(trimmedApiKey, forModelId: editing.id) {
                    customModelManager.updateCustomModel(updatedModel)
                } else {
                    validationErrors = ["Kon de API-sleutel niet veilig in de Keychain opslaan. Controleer je systeeminstellingen of probeer het opnieuw."]
                    showingAlert = true
                    isSaving = false
                    return
                }
            } else {
                let customModel = CustomCloudModel(
                    name: generatedName,
                    displayName: trimmedDisplayName,
                    description: "Eigen transcriptiemodel",
                    apiEndpoint: trimmedApiEndpoint,
                    modelName: trimmedModelName,
                    isMultilingual: isMultilingual
                )
                
                if APIKeyManager.shared.saveCustomModelAPIKey(trimmedApiKey, forModelId: customModel.id) {
                    customModelManager.addCustomModel(customModel)
                } else {
                    validationErrors = ["Kon de API-sleutel niet veilig in de Keychain opslaan. Controleer je systeeminstellingen of probeer het opnieuw."]
                    showingAlert = true
                    isSaving = false
                    return
                }
            }

            onModelAdded()

            withAnimation(.interpolatingSpring(stiffness: 170, damping: 20)) {
                isExpanded = false
                clearForm()
                isSaving = false
            }
        }
    }
}

struct FormField: View {
    let title: String
    @Binding var text: String
    let placeholder: String
    var isSecure: Bool = false
    
    var body: some View {
        VStack(alignment: .leading, spacing: ProatSpacing.xs - 2) {
            Text(title)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.proatText1)

            if isSecure {
                SecureField(placeholder, text: $text)
                    .textFieldStyle(.roundedBorder)
            } else {
                TextField(placeholder, text: $text)
                    .textFieldStyle(.roundedBorder)
            }
        }
    }
} 