import SwiftUI
import SwiftData

extension View {
    func placeholder<Content: View>(
        when shouldShow: Bool,
        alignment: Alignment = .center,
        @ViewBuilder placeholder: () -> Content) -> some View {

        ZStack(alignment: alignment) {
            placeholder().opacity(shouldShow ? 1 : 0)
            self
        }
    }
}

enum ConfigurationMode: Hashable {
    case add
    case edit(PowerModeConfig)
    
    var isAdding: Bool {
        if case .add = self { return true }
        return false
    }
    
    var title: String {
        switch self {
        case .add: return "Power Mode toevoegen"
        case .edit: return "Power Mode bewerken"
        }
    }
    
    func hash(into hasher: inout Hasher) {
        switch self {
        case .add:
            hasher.combine(0)
        case .edit(let config):
            hasher.combine(1)
            hasher.combine(config.id)
        }
    }
    
    static func == (lhs: ConfigurationMode, rhs: ConfigurationMode) -> Bool {
        switch (lhs, rhs) {
        case (.add, .add):
            return true
        case (.edit(let lhsConfig), .edit(let rhsConfig)):
            return lhsConfig.id == rhsConfig.id
        default:
            return false
        }
    }
}

enum ConfigurationType {
    case application
    case website
}

let commonEmojis = ["🏢", "🏠", "💼", "🎮", "📱", "📺", "🎵", "📚", "✏️", "🎨", "🧠", "⚙️", "💻", "🌐", "📝", "📊", "🔍", "💬", "📈", "🔧"]

struct PowerModeView: View {
    @StateObject private var powerModeManager = PowerModeManager.shared
    @EnvironmentObject private var enhancementService: AIEnhancementService
    @EnvironmentObject private var aiService: AIService
    @State private var configurationMode: ConfigurationMode?
    @State private var isPanelOpen = false
    @State private var panelID = UUID()
    @State private var isReorderPanelOpen = false
    
    var body: some View {
            VStack(spacing: 0) {
                // Header Section
                VStack(spacing: ProatSpacing.s) {
                    HStack {
                        VStack(alignment: .leading, spacing: ProatSpacing.xs / 2) {
                            HStack(spacing: ProatSpacing.xs) {
                                Text("Power Modes")
                                    .font(ProatFont.display)
                                    .foregroundColor(.proatText1)

                                InfoTip(
                                    "Pas automatisch aangepaste configuraties toe op basis van de app/website die je gebruikt."
                                )
                            }

                            Text("Automatiseer je workflows met contextbewuste configuraties.")
                                .font(ProatFont.body)
                                .foregroundColor(.proatText2)
                        }

                        Spacer()

                        HStack(spacing: ProatSpacing.xs) {
                            Button(action: {
                                openPanel(mode: .add)
                            }) {
                                HStack(spacing: ProatSpacing.xs - 2) {
                                    Image(systemName: "plus")
                                        .font(.system(size: 12, weight: .semibold))
                                    Text("Power Mode toevoegen")
                                        .font(.system(size: 13, weight: .semibold))
                                }
                                .foregroundColor(.white)
                                .padding(.horizontal, ProatSpacing.s)
                                .padding(.vertical, ProatSpacing.xs - 2)
                                .background(LinearGradient.proatTeal)
                                .clipShape(Capsule())
                                .proatShadowRust()
                            }
                            .buttonStyle(PlainButtonStyle())

                            Button(action: { openReorderPanel() }) {
                                HStack(spacing: ProatSpacing.xs - 2) {
                                    Image(systemName: "arrow.up.arrow.down")
                                        .font(.system(size: 12, weight: .medium))
                                    Text("Herordenen")
                                        .font(.system(size: 13, weight: .medium))
                                }
                                .foregroundColor(.proatText1)
                                .padding(.horizontal, ProatSpacing.s)
                                .padding(.vertical, ProatSpacing.xs - 2)
                                .background(Color.proatBgRaised)
                                .clipShape(Capsule())
                                .overlay(
                                    Capsule()
                                        .stroke(Color.proatBorder, lineWidth: 1)
                                )
                            }
                            .buttonStyle(PlainButtonStyle())
                        }
                    }
                }
                .padding(.horizontal, ProatSpacing.l)
                .padding(.top, ProatSpacing.l - 4)
                .padding(.bottom, ProatSpacing.m)
                .frame(maxWidth: .infinity)
                .background(Color.proatBgRaised)
                
                // Content Section
                Group {
                        GeometryReader { geometry in
                            ScrollView {
                                VStack(spacing: 0) {
                                    if powerModeManager.configurations.isEmpty {
                                        VStack(spacing: 24) {
                                            Spacer()
                                                .frame(height: geometry.size.height * 0.2)
                                            
                                            VStack(spacing: ProatSpacing.m) {
                                                Image(systemName: "square.grid.2x2.fill")
                                                    .font(.system(size: 48, weight: .regular))
                                                    .foregroundColor(.proatText3)

                                                VStack(spacing: ProatSpacing.xs) {
                                                    Text("Nog geen Power Modes")
                                                        .font(ProatFont.titel)
                                                        .foregroundColor(.proatText1)

                                                    Text("Maak je eerste Power Mode om je Proat-workflow te automatiseren op basis van de apps/websites die je gebruikt")
                                                        .font(ProatFont.body)
                                                        .foregroundColor(.proatText2)
                                                        .multilineTextAlignment(.center)
                                                        .lineSpacing(2)
                                                }
                                            }
                                            
                                            Spacer()
                                        }
                                        .frame(maxWidth: .infinity)
                                        .frame(minHeight: geometry.size.height)
                                    } else {
                                        VStack(spacing: 0) {
                                            PowerModeConfigurationsGrid(
                                                powerModeManager: powerModeManager,
                                                onEditConfig: { config in
                                                    openPanel(mode: .edit(config))
                                                }
                                            )
                                            .padding(.horizontal, 24)
                                            .padding(.vertical, 20)
                                            
                                            Spacer()
                                                .frame(height: 40)
                                        }
                                    }
                                }
                            }
                        }
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.proatBgBase)
            }
            .background(Color.proatBgBase)
            .slidingPanel(isPresented: .init(
                get: { isPanelOpen },
                set: { if !$0 { closePanel() } }
            ), width: 400) {
                if let mode = configurationMode {
                    ConfigurationView(mode: mode, powerModeManager: powerModeManager, onDismiss: closePanel)
                        .id(panelID)
                }
            }
            .slidingPanel(isPresented: .init(
                get: { isReorderPanelOpen },
                set: { if !$0 { closeReorderPanel() } }
            ), width: 400) {
                ReorderPanelView(powerModeManager: powerModeManager, onDismiss: closeReorderPanel)
            }
    }

    private func openPanel(mode: ConfigurationMode) {
        configurationMode = mode
        panelID = UUID()
        withAnimation(.smooth(duration: 0.3)) {
            isPanelOpen = true
        }
    }

    private func closePanel() {
        withAnimation(.smooth(duration: 0.3)) {
            isPanelOpen = false
            configurationMode = nil
        }
    }

    private func openReorderPanel() {
        withAnimation(.smooth(duration: 0.3)) {
            isReorderPanelOpen = true
        }
    }

    private func closeReorderPanel() {
        withAnimation(.smooth(duration: 0.3)) {
            isReorderPanelOpen = false
        }
    }
}

struct ReorderPanelView: View {
    @ObservedObject var powerModeManager: PowerModeManager
    let onDismiss: () -> Void

    var body: some View {
        VStack(spacing: 0) {
            // Header
            HStack(spacing: ProatSpacing.s) {
                Text("Power Modes herordenen")
                    .font(ProatFont.sectie)
                    .foregroundColor(.proatText1)
                Spacer()
                Button(action: onDismiss) {
                    Image(systemName: "xmark")
                        .font(.system(size: 14, weight: .medium))
                        .foregroundColor(.proatText2)
                        .padding(ProatSpacing.xs - 2)
                        .background(Color.proatBgSunken)
                        .clipShape(Circle())
                }
                .buttonStyle(.plain)
                .help("Sluiten")
            }
            .padding(.horizontal, ProatSpacing.l - 4)
            .padding(.vertical, ProatSpacing.m)
            .background(Color.proatBgRaised)
            .overlay(Divider().opacity(0.5), alignment: .bottom)

            // Reorder list
            List {
                ForEach(powerModeManager.configurations) { config in
                    HStack(spacing: ProatSpacing.s) {
                        Image(systemName: "line.3.horizontal")
                            .font(.system(size: 14))
                            .foregroundColor(.proatText3)

                        ZStack {
                            Circle()
                                .fill(Color.proatBgSunken)
                                .frame(width: 36, height: 36)
                            Text(config.emoji)
                                .font(.system(size: 18))
                        }

                        Text(config.name)
                            .font(.system(size: 14, weight: .medium))
                            .foregroundColor(.proatText1)

                        Spacer()

                        HStack(spacing: ProatSpacing.xs - 2) {
                            if config.isDefault {
                                Text("Standaard")
                                    .font(.system(size: 11, weight: .semibold))
                                    .padding(.horizontal, ProatSpacing.xs - 2)
                                    .padding(.vertical, 2)
                                    .background(Capsule().fill(LinearGradient.proatTeal))
                                    .foregroundColor(.white)
                            }
                            if !config.isEnabled {
                                Text("Uitgeschakeld")
                                    .font(.system(size: 11, weight: .medium))
                                    .padding(.horizontal, ProatSpacing.xs)
                                    .padding(.vertical, ProatSpacing.xs / 2)
                                    .background(Capsule().fill(Color.proatBgSunken))
                                    .overlay(
                                        Capsule().stroke(Color.proatBorder, lineWidth: 0.5)
                                    )
                                    .foregroundColor(.proatText2)
                            }
                        }
                    }
                    .padding(.vertical, ProatSpacing.xs)
                    .padding(.horizontal, ProatSpacing.xs + 2)
                    .background(
                        RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                            .fill(Color.proatBgRaised)
                            .overlay(
                                RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                                    .stroke(Color.proatBorder, lineWidth: 1)
                            )
                    )
                    .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16))
                    .listRowBackground(Color.clear)
                    .listRowSeparator(.hidden)
                }
                .onMove(perform: powerModeManager.moveConfigurations)
            }
            .listStyle(.plain)
            .scrollContentBackground(.hidden)
            .padding(.top, ProatSpacing.xs)
        }
        .background(Color.proatBgRaised)
    }
}


struct SectionHeader: View {
    let title: String

    var body: some View {
        Text(title)
            .font(ProatFont.sectie)
            .foregroundColor(.proatText1)
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.bottom, ProatSpacing.xs)
    }
}
