import SwiftUI

// Account screen — fourth, smallest, intentionally not on screen by
// default (the page indicator nudges users to the previous tabs first).
// Phase A.1 was display-only with DevAuth; Phase B grows the two
// affordances the plan §3 prescribes:
//
//   - "Re-sync from iPhone": asks the phone to re-push the active
//     account's handoff payload via WCSession sendMessage. Fire-and-
//     forget — the response lands on `WatchSession.handleApplication
//     Context` and hot-reloads AuthState in turn. Useful when the
//     phone rotated a token while the watch was off-wrist (the
//     resulting next-foreground push from the phone covers most
//     cases, but the manual button is the explicit escape hatch for
//     the rare race).
//
//   - "Sign out on this Watch": local-only — wipes the watch's
//     keychain + AuthState and lands on EmptyAuthView. Does NOT
//     touch the phone. The phone-side account stays signed in;
//     re-syncing rebuilds the watch's session from the phone's
//     current handoff. The phone has a parallel per-device vs.
//     global sign-out split for the same reason: scoping the
//     destructive action to the device the user is holding.

struct AccountView: View {
    @EnvironmentObject var auth: AuthState
    @State private var lastAction: String?
    @State private var actionAt: Date = .distantPast
    // The audit numbers are a sign-off artifact for Phase C exit
    // criterion #4 (≤70 reloads/day). The view re-reads on appearance
    // and on a low-frequency timer; nothing else needs to subscribe.
    // Two counters — one per widget kind — share the same UTC-day
    // rollover via `ComplicationAudit`.
    @State private var todaysReloadCount: Int?
    @State private var todaysLatestMediaReloadCount: Int?

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 8) {
                Text(Branding.name)
                    .font(.headline)
                if let creds = auth.credentials {
                    if let s = creds.avatarUrl, let url = URL(string: s) {
                        // `.id(creds.accountId)` forces SwiftUI to discard
                        // the prior AsyncImage instance on account switch.
                        // Without it, AsyncImage's URL-keyed in-memory cache
                        // can serve a previously-seen avatar even though
                        // the semantic account context changed.
                        AsyncImage(url: url) { phase in
                            switch phase {
                            case .success(let image):
                                image.resizable().aspectRatio(contentMode: .fill)
                            default:
                                Circle().fill(.secondary.opacity(0.2))
                            }
                        }
                        .id(creds.accountId)
                        .frame(width: 56, height: 56)
                        .clipShape(Circle())
                        .overlay(
                            Circle().strokeBorder(.secondary.opacity(0.2), lineWidth: 0.5)
                        )
                        .padding(.bottom, 2)
                    }
                    Text("@\(creds.username)")
                        .font(.subheadline)
                        .foregroundStyle(.primary)
                        .lineLimit(1)
                    Text(creds.instance)
                        .font(.caption2)
                        .foregroundStyle(.secondary)
                        .lineLimit(1)
                    Text(creds.accountType.capitalized)
                        .font(.caption2)
                        .foregroundStyle(.secondary)
                    if let updated = auth.lastHandoffAt {
                        Text("Updated \(relativeTime(updated))")
                            .font(.caption2)
                            .foregroundStyle(.secondary)
                    }

                    Divider()
                        .padding(.vertical, 2)

                    Button {
                        auth.requestReHandoff()
                        flashAction("Asked iPhone to re-sync")
                    } label: {
                        Label("Re-sync from iPhone", systemImage: "arrow.triangle.2.circlepath")
                            .font(.caption)
                    }
                    .buttonStyle(.bordered)

                    Button(role: .destructive) {
                        auth.clear()
                        flashAction("Signed out on Watch")
                    } label: {
                        Label("Sign out on Watch", systemImage: "person.crop.circle.badge.xmark")
                            .font(.caption)
                    }
                    .buttonStyle(.bordered)

                    if let msg = lastAction, Date().timeIntervalSince(actionAt) < 4 {
                        Text(msg)
                            .font(.caption2)
                            .foregroundStyle(.secondary)
                            .lineLimit(2)
                            .padding(.top, 4)
                    }

                    if todaysReloadCount != nil || todaysLatestMediaReloadCount != nil {
                        Divider()
                            .padding(.vertical, 2)
                    }
                    if let count = todaysReloadCount {
                        Text("Tapestry: \(count) reloads today")
                            .font(.caption2)
                            .foregroundStyle(.secondary)
                            .lineLimit(1)
                    }
                    if let count = todaysLatestMediaReloadCount {
                        Text("Latest Media: \(count) reloads today")
                            .font(.caption2)
                            .foregroundStyle(.secondary)
                            .lineLimit(1)
                    }
                } else {
                    Text("Not signed in")
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                }
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding()
        }
        .onAppear { refreshAudit() }
        .task { refreshAudit() }
    }

    private func refreshAudit() {
        todaysReloadCount = AppGroupCache.todaysReloadAudit()?.count ?? 0
        todaysLatestMediaReloadCount =
            AppGroupCache.todaysLatestMediaReloadAudit()?.count ?? 0
    }

    private func flashAction(_ msg: String) {
        lastAction = msg
        actionAt = Date()
    }

    private func relativeTime(_ date: Date) -> String {
        let f = RelativeDateTimeFormatter()
        f.unitsStyle = .abbreviated
        return f.localizedString(for: date, relativeTo: Date())
    }
}
