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

import Combine
import SwiftUI

struct OpenRockyTimerListView: View {
    @ObservedObject private var service = OpenRockyTimerService.shared
    @State private var now: Date = Date()

    private let ticker = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        Group {
            if service.timers.isEmpty {
                emptyState
            } else {
                List {
                    Section {
                        ForEach(service.timers.sorted { $0.fireAt < $1.fireAt }) { timer in
                            row(for: timer)
                        }
                        .onDelete { indexSet in
                            let sorted = service.timers.sorted { $0.fireAt < $1.fireAt }
                            for idx in indexSet where sorted.indices.contains(idx) {
                                service.cancel(id: sorted[idx].id)
                            }
                        }
                    } footer: {
                        Text("Swipe to cancel. Timers fire even if Rocky is in the background — we schedule a local notification.")
                    }

                    if service.timers.count > 1 {
                        Section {
                            Button("Cancel All", role: .destructive) {
                                service.cancelAll()
                            }
                        }
                    }
                }
            }
        }
        .navigationTitle("Timers")
        .navigationBarTitleDisplayMode(.inline)
        .onReceive(ticker) { newNow in
            now = newNow
        }
    }

    private var emptyState: some View {
        VStack(spacing: 12) {
            Image(systemName: "timer")
                .font(.system(size: 40))
                .foregroundStyle(.tertiary)
            Text("No active timers")
                .font(.system(size: 16, weight: .medium, design: .rounded))
                .foregroundStyle(.secondary)
            Text("Ask Rocky: \"Set a timer for 5 minutes.\"")
                .font(.system(size: 13))
                .foregroundStyle(.tertiary)
                .multilineTextAlignment(.center)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .padding()
    }

    private func row(for timer: OpenRockyTimer) -> some View {
        let remaining = max(0, timer.fireAt.timeIntervalSince(now))
        return HStack(spacing: 12) {
            ZStack {
                Circle()
                    .fill(Color.orange.opacity(0.14))
                    .frame(width: 36, height: 36)
                Image(systemName: "timer")
                    .foregroundStyle(.orange)
                    .font(.system(size: 16, weight: .bold))
            }
            VStack(alignment: .leading, spacing: 3) {
                Text(timer.label)
                    .font(.system(size: 15, weight: .semibold, design: .rounded))
                HStack(spacing: 6) {
                    Text(Self.formatRemaining(remaining))
                        .font(.system(size: 13, design: .monospaced))
                        .foregroundStyle(.secondary)
                    Text("·")
                        .foregroundStyle(.tertiary)
                    Text(Self.formatFireTime(timer.fireAt))
                        .font(.system(size: 12))
                        .foregroundStyle(.tertiary)
                }
            }
            Spacer()
        }
        .padding(.vertical, 4)
    }

    private static func formatRemaining(_ seconds: TimeInterval) -> String {
        let total = Int(seconds.rounded())
        let h = total / 3600
        let m = (total % 3600) / 60
        let s = total % 60
        if h > 0 {
            return String(format: "%d:%02d:%02d", h, m, s)
        }
        return String(format: "%d:%02d", m, s)
    }

    private static func formatFireTime(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.timeStyle = .short
        formatter.dateStyle = .none
        return "at \(formatter.string(from: date))"
    }
}
