import SwiftUI

/// Manage saved panel layouts: apply, rename, delete, and choose which one new
/// launches open with. Reached from the Panels toolbar menu.
struct ManageLayoutsSheet: View {
    @Environment(PanelLayoutStore.self) private var panels
    @Environment(\.dismiss) private var dismiss
    @Environment(\.appPalette) private var palette

    @State private var renamingID: UUID?
    @State private var renameDraft = ""
    @State private var newName = ""

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            HStack {
                Text("Layouts").font(.title3.weight(.semibold))
                Spacer()
                Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
            }
            .padding(16)
            Divider()

            if panels.saved.isEmpty {
                VStack(spacing: 6) {
                    Image(systemName: "rectangle.split.3x1").font(.largeTitle).foregroundStyle(.tertiary)
                    Text("No saved layouts yet").foregroundStyle(.secondary)
                    Text("Arrange panels, then use “Save Current Layout” in the Panels menu.")
                        .font(.caption).foregroundStyle(.tertiary).multilineTextAlignment(.center)
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity).padding(24)
            } else {
                ScrollView {
                    VStack(spacing: 0) {
                        ForEach(panels.saved) { saved in
                            row(saved)
                            Divider()
                        }
                    }
                }
            }

            Divider()
            HStack(spacing: 8) {
                TextField("Save current arrangement as…", text: $newName)
                    .textFieldStyle(.roundedBorder)
                    .onSubmit(saveCurrent)
                Button("Save", action: saveCurrent)
                    .disabled(newName.trimmingCharacters(in: .whitespaces).isEmpty)
            }
            .padding(16)
        }
        .frame(width: 460, height: 420)
    }

    private func row(_ saved: PanelLayout) -> some View {
        let isDefault = panels.defaultLayoutID == saved.id
        return HStack(spacing: 10) {
            Button {
                panels.setDefault(isDefault ? nil : saved.id)
            } label: {
                Image(systemName: isDefault ? "house.fill" : "house")
                    .foregroundStyle(isDefault ? palette.accent : .secondary)
            }
            .buttonStyle(.plain)
            .help(isDefault ? "This is the default layout" : "Make this the default layout")

            VStack(alignment: .leading, spacing: 2) {
                if renamingID == saved.id {
                    TextField("Name", text: $renameDraft, onCommit: { commitRename(saved.id) })
                        .textFieldStyle(.roundedBorder)
                } else {
                    Text(saved.name).font(.body.weight(.medium))
                }
                Text(summary(saved)).font(.caption).foregroundStyle(.secondary)
            }
            Spacer()
            Button("Apply") { panels.apply(saved) }
                .buttonStyle(.bordered)
            Menu {
                Button("Rename", systemImage: "pencil") {
                    renameDraft = saved.name
                    renamingID = saved.id
                }
                Button("Delete", systemImage: "trash", role: .destructive) {
                    panels.deleteSaved(saved.id)
                }
            } label: {
                Image(systemName: "ellipsis.circle")
            }
            .menuStyle(.borderlessButton)
            .menuIndicator(.hidden)
            .fixedSize()
        }
        .padding(.horizontal, 16).padding(.vertical, 10)
    }

    /// "2 left · 1 bottom" style breakdown of where a layout puts its panels.
    private func summary(_ layout: PanelLayout) -> String {
        var parts: [String] = []
        if !layout.left.isEmpty { parts.append("\(layout.left.count) left") }
        if !layout.right.isEmpty { parts.append("\(layout.right.count) right") }
        if !layout.bottom.isEmpty { parts.append("\(layout.bottom.count) bottom") }
        return parts.isEmpty ? "Just chat" : parts.joined(separator: " · ")
    }

    private func commitRename(_ id: UUID) {
        panels.renameSaved(id, to: renameDraft)
        renamingID = nil
    }

    private func saveCurrent() {
        let name = newName.trimmingCharacters(in: .whitespaces)
        guard !name.isEmpty else { return }
        panels.saveWorking(as: name)
        newName = ""
    }
}
