//
//  ItemEditorView.swift
//  Cable
//
//  Created by Stefan Lange-Hegermann on 16.09.25.
//

import SwiftUI
import UIKit

struct ItemEditorView: View {
    @Environment(\.dismiss) private var dismiss
    
    let title: String
    let nameFieldLabel: String
    let previewSubtitle: String
    let icons: [String]
    let additionalFields: () -> AnyView
    private let remoteIconURLStringBinding: Binding<String?>?
    
    @Binding var name: String
    @Binding var iconName: String
    @Binding var colorName: String
    
    @State private var tempName: String
    @State private var tempIconName: String
    @State private var tempColorName: String
    @State private var tempRemoteIconURLString: String?
    
    private let curatedColors: [(String, Color)] = [
        ("blue", .blue),
        ("green", .green),
        ("orange", .orange),
        ("red", .red),
        ("purple", .purple),
        ("yellow", .yellow),
        ("pink", .pink),
        ("teal", .teal),
        ("indigo", .indigo),
        ("mint", .mint),
        ("cyan", .cyan),
        ("brown", .brown),
        ("gray", .gray)
    ]
    
    init(
        title: String,
        nameFieldLabel: String,
        previewSubtitle: String,
        icons: [String],
        name: Binding<String>,
        iconName: Binding<String>,
        colorName: Binding<String>,
        remoteIconURLString: Binding<String?>? = nil,
        @ViewBuilder additionalFields: @escaping () -> AnyView = { AnyView(EmptyView()) }
    ) {
        self.title = title
        self.nameFieldLabel = nameFieldLabel
        self.previewSubtitle = previewSubtitle
        self.icons = icons
        self.additionalFields = additionalFields
        self.remoteIconURLStringBinding = remoteIconURLString
        self._name = name
        self._iconName = iconName
        self._colorName = colorName
        self._tempName = State(initialValue: name.wrappedValue)
        self._tempIconName = State(initialValue: iconName.wrappedValue)
        self._tempColorName = State(initialValue: colorName.wrappedValue)
        self._tempRemoteIconURLString = State(initialValue: remoteIconURLString?.wrappedValue)
    }
    
    var body: some View {
        NavigationStack {
            Form {
                Section("Preview") {
                    HStack {
                        LoadIconView(
                            remoteIconURLString: tempRemoteIconURLString,
                            fallbackSystemName: tempIconName,
                            fallbackColor: selectedColor,
                            size: 60
                        )
                        
                        VStack(alignment: .leading) {
                            Text(tempName.isEmpty ? nameFieldLabel : tempName)
                                .font(.headline)
                                .foregroundColor(.primary)
                            Text(previewSubtitle)
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                        
                        Spacer()
                    }
                    .padding(.vertical, 8)
                }
                
                Section("Details") {
                    AutoSelectTextField(
                        text: $tempName,
                        placeholder: nameFieldLabel,
                        autoFocus: true
                    )
                    
                    additionalFields()
                }
                
                Section("Icon") {
                    LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 5), spacing: 16) {
                        ForEach(icons, id: \.self) { icon in
                            Button(action: {
                                tempIconName = icon
                                tempRemoteIconURLString = nil
                            }) {
                                ZStack {
                                    RoundedRectangle(cornerRadius: 12)
                                        .fill(tempIconName == icon && tempRemoteIconURLString == nil ? selectedColor : Color(.systemGray5))
                                        .frame(width: 50, height: 50)
                                    
                                    Image(systemName: icon)
                                        .font(.title3)
                                        .foregroundColor(tempIconName == icon && tempRemoteIconURLString == nil ? .white : .primary)
                                }
                            }
                            .buttonStyle(.plain)
                        }
                    }
                    .padding(.vertical, 8)
                }
                
                Section("Color") {
                    LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 6), spacing: 16) {
                        ForEach(curatedColors, id: \.0) { colorName, color in
                            Button(action: {
                                tempColorName = colorName
                            }) {
                                ZStack {
                                    Circle()
                                        .fill(color)
                                        .frame(width: 40, height: 40)
                                    
                                    if tempColorName == colorName {
                                        Image(systemName: "checkmark")
                                            .font(.headline)
                                            .fontWeight(.bold)
                                            .foregroundColor(.white)
                                    }
                                }
                            }
                            .buttonStyle(.plain)
                        }
                    }
                    .padding(.vertical, 8)
                }
            }
            .navigationTitle(title)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel") {
                        dismiss()
                    }
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Save") {
                        saveChanges()
                        dismiss()
                    }
                    .fontWeight(.semibold)
                }
            }
        }
    }
    
    private var selectedColor: Color {
        curatedColors.first { $0.0 == tempColorName }?.1 ?? .blue
    }
    
    private func saveChanges() {
        name = tempName
        iconName = tempIconName
        colorName = tempColorName
        remoteIconURLStringBinding?.wrappedValue = tempRemoteIconURLString
    }
}

private struct AutoSelectTextField: UIViewRepresentable {
    @Binding var text: String
    let placeholder: String
    let autoFocus: Bool
    
    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField(frame: .zero)
        textField.delegate = context.coordinator
        textField.placeholder = placeholder
        textField.text = text
        textField.autocapitalizationType = .words
        textField.clearButtonMode = .whileEditing
        textField.returnKeyType = .done
        textField.addTarget(context.coordinator, action: #selector(Coordinator.textChanged(_:)), for: .editingChanged)
        return textField
    }
    
    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
        uiView.placeholder = placeholder
        uiView.autocapitalizationType = .words
        
        if autoFocus, !context.coordinator.didFocus {
            context.coordinator.didFocus = true
            DispatchQueue.main.async {
                uiView.becomeFirstResponder()
                uiView.selectAll(nil)
            }
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(text: $text)
    }
    
    final class Coordinator: NSObject, UITextFieldDelegate {
        @Binding var text: String
        var didFocus = false
        
        init(text: Binding<String>) {
            self._text = text
        }
        
        @objc func textChanged(_ sender: UITextField) {
            text = sender.text ?? ""
        }
        
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            return true
        }
    }
}
