import SwiftUI

struct SessionDetailView: View {
    let session: HermesSession
    let messages: [HermesMessage]
    var preview: String?

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            sessionHeader
            Divider()
            messagesList
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
    }

    private var sessionHeader: some View {
        VStack(alignment: .leading, spacing: 6) {
            Text(preview ?? session.displayTitle)
                .font(.title3.bold())
            HStack(spacing: 16) {
                Label(session.source, systemImage: session.sourceIcon)
                Label(session.model ?? "unknown", systemImage: "cpu")
                Label("\(session.messageCount) msgs", systemImage: "bubble.left")
                Label("\(session.toolCallCount) tools", systemImage: "wrench")
                if let cost = session.estimatedCostUSD {
                    Label(String(format: "$%.4f", cost), systemImage: "dollarsign.circle")
                }
                if let date = session.startedAt {
                    Label(date.formatted(.dateTime.month().day().hour().minute()), systemImage: "calendar")
                }
            }
            .font(.caption)
            .foregroundStyle(.secondary)
        }
        .padding()
    }

    private var messagesList: some View {
        ScrollView {
            LazyVStack(alignment: .leading, spacing: 12) {
                ForEach(messages) { message in
                    MessageBubble(message: message)
                }
            }
            .padding()
        }
    }
}

struct MessageBubble: View {
    let message: HermesMessage

    var body: some View {
        VStack(alignment: message.isUser ? .trailing : .leading, spacing: 4) {
            HStack {
                if message.isUser { Spacer(minLength: 60) }
                VStack(alignment: .leading, spacing: 6) {
                    if !message.content.isEmpty {
                        Text(message.content)
                            .textSelection(.enabled)
                    }
                    if !message.toolCalls.isEmpty {
                        ForEach(message.toolCalls) { call in
                            ToolCallBadge(call: call)
                        }
                    }
                }
                .padding(10)
                .background(message.isUser ? Color.accentColor.opacity(0.15) : Color.secondary.opacity(0.1))
                .clipShape(RoundedRectangle(cornerRadius: 10))
                if !message.isUser { Spacer(minLength: 60) }
            }
            if let time = message.timestamp {
                Text(time, style: .time)
                    .font(.caption2)
                    .foregroundStyle(.tertiary)
            }
        }
        .frame(maxWidth: .infinity, alignment: message.isUser ? .trailing : .leading)
    }
}

struct ToolCallBadge: View {
    let call: HermesToolCall

    @State private var expanded = false

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Button {
                expanded.toggle()
            } label: {
                HStack(spacing: 4) {
                    Image(systemName: call.toolKind.icon)
                        .foregroundStyle(toolColor)
                    Text(call.functionName)
                        .font(.caption.monospaced())
                    Image(systemName: expanded ? "chevron.down" : "chevron.right")
                        .font(.caption2)
                }
            }
            .buttonStyle(.plain)

            if expanded {
                Text(call.argumentsSummary)
                    .font(.caption.monospaced())
                    .foregroundStyle(.secondary)
                    .textSelection(.enabled)
                    .padding(6)
                    .background(.quaternary)
                    .clipShape(RoundedRectangle(cornerRadius: 4))
            }
        }
    }

    private var toolColor: Color {
        switch call.toolKind {
        case .read: return .green
        case .edit: return .blue
        case .execute: return .orange
        case .fetch: return .purple
        case .browser: return .indigo
        case .other: return .secondary
        }
    }
}
