//
// OpenRocky — Voice-first AI Agent
// https://github.com/openrocky
//
// Developed by everettjf with the assistance of Claude Code and Codex.
// Date: 2026-05-04
// Copyright (c) 2026 everettjf. All rights reserved.
//

import SwiftUI

/// Compact panel that shows what the chat sub-agent is doing right now —
/// header (delegate-task description), per-subtask status, last few tool /
/// skill events. Sits below `statusText` in the voice overlay so the user
/// can watch the back-end agent work instead of staring at a single status
/// line that flickers between event boundaries.
struct OpenRockyDelegateProgressPanel: View {
    let progress: OpenRockyDelegateProgress

    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            header

            ForEach(progress.subtasks) { subtask in
                subtaskBlock(subtask)
            }
        }
        .padding(.horizontal, 14)
        .padding(.vertical, 12)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(
            RoundedRectangle(cornerRadius: 14, style: .continuous)
                .fill(Color.white.opacity(0.05))
                .overlay(
                    RoundedRectangle(cornerRadius: 14, style: .continuous)
                        .stroke(Color.white.opacity(0.08), lineWidth: 1)
                )
        )
    }

    // MARK: - Header

    private var header: some View {
        HStack(spacing: 8) {
            Image(systemName: progress.isFinished ? "checkmark.circle.fill" : "arrow.triangle.branch")
                .font(.system(size: 13, weight: .bold))
                .foregroundStyle(progress.isFinished ? OpenRockyPalette.success : OpenRockyPalette.accent)

            VStack(alignment: .leading, spacing: 2) {
                Text(progress.isFinished ? "Delegate-task done" : "Delegating...")
                    .font(.system(size: 12, weight: .bold, design: .rounded))
                    .foregroundStyle(.white)

                if !progress.taskDescription.isEmpty {
                    Text(progress.taskDescription)
                        .font(.system(size: 11, weight: .medium, design: .rounded))
                        .foregroundStyle(OpenRockyPalette.muted)
                        .lineLimit(2)
                }
            }
            Spacer(minLength: 0)

            if let total = progress.planTotalCount, let succeeded = progress.planSucceededCount {
                Text("\(succeeded)/\(total)")
                    .font(.system(size: 11, weight: .bold, design: .monospaced))
                    .foregroundStyle(OpenRockyPalette.muted)
            }
        }
    }

    // MARK: - Subtask block

    @ViewBuilder
    private func subtaskBlock(_ subtask: OpenRockyDelegateProgress.Subtask) -> some View {
        VStack(alignment: .leading, spacing: 6) {
            HStack(spacing: 6) {
                Image(systemName: subtaskIcon(for: subtask.status, succeeded: subtask.succeeded))
                    .font(.system(size: 10, weight: .bold))
                    .foregroundStyle(subtaskTint(for: subtask))

                Text("Subtask \(subtask.index + 1)/\(subtask.totalCount)")
                    .font(.system(size: 11, weight: .bold, design: .rounded))
                    .foregroundStyle(.white)

                Text(subtask.description)
                    .font(.system(size: 11, weight: .medium, design: .rounded))
                    .foregroundStyle(OpenRockyPalette.muted)
                    .lineLimit(1)

                Spacer(minLength: 0)

                if let elapsed = subtask.elapsedSeconds, subtask.status == .completed {
                    Text(String(format: "%.1fs", elapsed))
                        .font(.system(size: 10, weight: .medium, design: .monospaced))
                        .foregroundStyle(OpenRockyPalette.muted)
                }
            }

            if !subtask.toolEvents.isEmpty {
                VStack(alignment: .leading, spacing: 3) {
                    ForEach(subtask.toolEvents) { event in
                        toolEventRow(event)
                    }
                }
                .padding(.leading, 16)
            }
        }
    }

    @ViewBuilder
    private func toolEventRow(_ event: OpenRockyDelegateProgress.ToolEvent) -> some View {
        HStack(spacing: 6) {
            switch event.status {
            case .running:
                ProgressView()
                    .controlSize(.mini)
                    .tint(OpenRockyPalette.accent)
            case .completed(let succeeded):
                Image(systemName: succeeded ? "checkmark.circle.fill" : "xmark.circle.fill")
                    .font(.system(size: 10, weight: .bold))
                    .foregroundStyle(succeeded ? OpenRockyPalette.success : OpenRockyPalette.warning)
            }

            // [skill] / [tool] tag — quick read of what the sub-agent is using
            Text(event.isSkill ? "skill" : (event.name.hasPrefix("mcp-") ? "mcp" : "tool"))
                .font(.system(size: 9, weight: .bold, design: .rounded))
                .foregroundStyle(OpenRockyPalette.muted)
                .padding(.horizontal, 4)
                .padding(.vertical, 1)
                .background(
                    Capsule().fill(Color.white.opacity(0.06))
                )

            Text(event.name)
                .font(.system(size: 11, weight: .semibold, design: .monospaced))
                .foregroundStyle(.white)

            if !event.argsPreview.isEmpty, event.status == .running {
                Text(event.argsPreview)
                    .font(.system(size: 10, weight: .regular, design: .monospaced))
                    .foregroundStyle(OpenRockyPalette.muted)
                    .lineLimit(1)
            }

            Spacer(minLength: 0)

            if let elapsed = event.elapsedSeconds {
                Text(String(format: "%.1fs", elapsed))
                    .font(.system(size: 10, weight: .medium, design: .monospaced))
                    .foregroundStyle(OpenRockyPalette.muted)
            }
        }
    }

    // MARK: - Helpers

    private func subtaskIcon(for status: OpenRockyDelegateProgress.Subtask.Status, succeeded: Bool?) -> String {
        switch status {
        case .running: return "play.circle.fill"
        case .thinking: return "brain"
        case .completed: return (succeeded ?? false) ? "checkmark.circle.fill" : "xmark.circle.fill"
        }
    }

    private func subtaskTint(for subtask: OpenRockyDelegateProgress.Subtask) -> Color {
        switch subtask.status {
        case .running, .thinking:
            return OpenRockyPalette.accent
        case .completed:
            return (subtask.succeeded ?? false) ? OpenRockyPalette.success : OpenRockyPalette.warning
        }
    }
}
