import SwiftUI
import CoreData

struct CreateCodeView: View {
    @Environment(\.dismiss) private var dismiss
    @EnvironmentObject var coreDataManager: CoreDataManager
    
    // 从类型选择界面传入的参数
    let selectedDataType: DataType
    let selectedBarcodeType: BarcodeType
    let selectedQRCodeType: QRCodeType
    @State private var content = ""
    @State private var showingAlert = false
    @State private var alertMessage = ""
    
    // 条形码验证相关状态
    @State private var validationResult: BarcodeValidator.ValidationResult?
    
    // 输入焦点，确保进入页面自动弹出键盘
    @FocusState private var isContentFieldFocused: Bool
    
    var body: some View {
        Form {
            // 内容输入和预览组件
            CodeContentInputView(
                selectedDataType: selectedDataType,
                selectedBarcodeType: selectedBarcodeType,
                selectedQRCodeType: selectedQRCodeType,
                content: $content,
                validationResult: $validationResult,
                isContentFieldFocused: $isContentFieldFocused
            )
        }
        .navigationTitle(String(format: "create_data_type".localized, selectedDataType.displayName))
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button("create".localized) { createCode() }
                    .disabled(content.isEmpty)
            }
        }
        .alert("tip".localized, isPresented: $showingAlert) {
Button("confirm".localized) { }
        } message: { Text(alertMessage) }
        .onAppear {
            // 稍延迟以确保进入页面时自动聚焦
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                isContentFieldFocused = true
            }
        }
        .onTapGesture {
            // 点击外部关闭键盘
            isContentFieldFocused = false
        }
    }
    
    private func createCode() {
        guard !content.isEmpty else { return }
        // 如果是条形码，验证格式
        if selectedDataType == .barcode {
            let validation = BarcodeValidator.validateBarcode(content, type: selectedBarcodeType)
            if !validation.isValid {
                alertMessage = validation.errorMessage ?? "barcode_format_incorrect".localized
                showingAlert = true
                return
            }
        }
        let context = coreDataManager.container.viewContext
        let historyItem = HistoryItem(context: context)
        historyItem.id = UUID()
        historyItem.content = content
        historyItem.dataType = selectedDataType.rawValue
        historyItem.dataSource = DataSource.created.rawValue
        historyItem.createdAt = Date()
        historyItem.isFavorite = false
        if selectedDataType == .barcode {
            historyItem.barcodeType = selectedBarcodeType.rawValue
        } else {
            historyItem.qrCodeType = selectedQRCodeType.rawValue
        }
        coreDataManager.addHistoryItem(historyItem)
        alertMessage = String(format: "data_type_created_successfully".localized, selectedDataType.displayName)
        showingAlert = true
        // 创建成功后返回主页
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { 
            dismiss() // 关闭创建界面，返回到类型选择界面
        }
    }
}

#Preview {
    CreateCodeView(
        selectedDataType: .barcode,
        selectedBarcodeType: .ean13,
        selectedQRCodeType: .text
    )
} 
