import SwiftUI
import UIKit

struct MonitorView: View {
    @Bindable var monitor: VideoMonitor
    @Environment(\.openURL) private var openURL
    @State private var csvURLDraft = ""

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(alignment: .leading, spacing: 18) {
                    HeaderView(status: monitor.status)

                    if let video = monitor.latestVideo {
                        LatestVideoView(video: video) {
                            openURL(video.videoURL)
                        }
                    } else {
                        ContentUnavailableView(
                            "暂无视频记录",
                            systemImage: "video.slash",
                            description: Text(monitor.emptyStateMessage)
                        )
                    }

                    StatusGrid(monitor: monitor)

                    APNsTokenView(
                        token: monitor.deviceToken,
                        status: monitor.remoteNotificationStatus
                    )

                    ServerConfigView(
                        csvURLDraft: $csvURLDraft,
                        save: {
                            Task {
                                await monitor.updateCSVURL(csvURLDraft)
                                csvURLDraft = monitor.csvURLText
                            }
                        },
                        reset: {
                            Task {
                                await monitor.resetCSVURLToDefault()
                                csvURLDraft = monitor.csvURLText
                            }
                        }
                    )
                }
                .padding()
            }
            .background(Color(.systemGroupedBackground))
            .navigationTitle("陕西联合监测")
            .toolbar {
                ToolbarItemGroup(placement: .topBarTrailing) {
                    Button {
                        Task {
                            await monitor.checkNow()
                        }
                    } label: {
                        Image(systemName: "arrow.clockwise")
                    }
                    .accessibilityLabel("立即检查")
                }
            }
            .onAppear {
                csvURLDraft = monitor.csvURLText
            }
        }
    }
}

private struct HeaderView: View {
    let status: VideoMonitor.Status

    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack(spacing: 12) {
                Image(systemName: "shield.lefthalf.filled")
                    .font(.system(size: 30, weight: .semibold))
                    .foregroundStyle(.white)
                    .frame(width: 54, height: 54)
                    .background(Color(red: 0.73, green: 0.06, blue: 0.09), in: RoundedRectangle(cornerRadius: 8))

                VStack(alignment: .leading, spacing: 4) {
                    Text("陕西联合")
                        .font(.title2.bold())
                    Text("B 站官方账号")
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                }

                Spacer()

                StatusBadge(status: status)
            }
        }
        .padding(16)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 8))
    }
}

private struct StatusBadge: View {
    let status: VideoMonitor.Status

    var body: some View {
        Label(status.title, systemImage: iconName)
            .font(.caption.weight(.semibold))
            .padding(.horizontal, 10)
            .padding(.vertical, 7)
            .foregroundStyle(foregroundColor)
            .background(backgroundColor, in: Capsule())
    }

    private var iconName: String {
        switch status {
        case .checking:
            "clock.arrow.circlepath"
        case .newVideo:
            "bell.badge.fill"
        case .failed:
            "exclamationmark.triangle.fill"
        case .empty:
            "tray"
        case .idle:
            "pause.circle"
        case .ready:
            "checkmark.circle.fill"
        }
    }

    private var foregroundColor: Color {
        switch status {
        case .newVideo:
            Color(red: 0.55, green: 0.05, blue: 0.08)
        case .failed:
            .orange
        default:
            .green
        }
    }

    private var backgroundColor: Color {
        foregroundColor.opacity(0.14)
    }
}

private struct LatestVideoView: View {
    let video: VideoRecord
    let openVideo: () -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: 14) {
            Label("最新视频", systemImage: "play.rectangle.fill")
                .font(.headline)
                .foregroundStyle(Color(red: 0.73, green: 0.06, blue: 0.09))

            Text(video.title)
                .font(.title3.weight(.semibold))
                .fixedSize(horizontal: false, vertical: true)

            Label(video.publishTimeText, systemImage: "calendar")
                .font(.subheadline)
                .foregroundStyle(.secondary)

            Button(action: openVideo) {
                Label("打开视频", systemImage: "safari")
                    .frame(maxWidth: .infinity)
            }
            .buttonStyle(.borderedProminent)
            .tint(Color(red: 0.73, green: 0.06, blue: 0.09))
        }
        .padding(16)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 8))
    }
}

private struct StatusGrid: View {
    let monitor: VideoMonitor

    var body: some View {
        Grid(horizontalSpacing: 12, verticalSpacing: 12) {
            GridRow {
                MetricTile(
                    title: "检查频率",
                    value: "10 秒",
                    iconName: "timer"
                )
                MetricTile(
                    title: "通知权限",
                    value: monitor.notificationsEnabled ? "已开启" : "未开启",
                    iconName: monitor.notificationsEnabled ? "bell.fill" : "bell.slash"
                )
            }
            GridRow {
                MetricTile(
                    title: "最近检查",
                    value: monitor.lastCheckedAt?.dashboardText ?? "尚未检查",
                    iconName: "clock"
                )
                MetricTile(
                    title: "判断依据",
                    value: "发布时间",
                    iconName: "calendar.badge.clock"
                )
            }
        }
    }
}

private struct APNsTokenView: View {
    let token: String
    let status: String

    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Label("APNs 设备 Token", systemImage: "bell.badge")
                .font(.headline)

            Text(status)
                .font(.subheadline)
                .foregroundStyle(token.isEmpty ? Color.secondary : Color.green)

            if !token.isEmpty {
                Text(token)
                    .font(.caption.monospaced())
                    .foregroundStyle(.secondary)
                    .textSelection(.enabled)
                    .lineLimit(4)

                Button {
                    UIPasteboard.general.string = token
                } label: {
                    Label("复制 Token", systemImage: "doc.on.doc")
                        .frame(maxWidth: .infinity)
                }
                .buttonStyle(.bordered)
            }
        }
        .padding(16)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 8))
    }

}

private struct ServerConfigView: View {
    @Binding var csvURLDraft: String
    let save: () -> Void
    let reset: () -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Label("服务器 CSV 地址", systemImage: "server.rack")
                .font(.headline)

            TextField("https://huaiyumacbook-pro.tail432a28.ts.net/bilibili_latest_videos_259655230.csv", text: $csvURLDraft)
                .textInputAutocapitalization(.never)
                .autocorrectionDisabled()
                .keyboardType(.URL)
                .font(.footnote.monospaced())
                .textFieldStyle(.roundedBorder)

            HStack(spacing: 10) {
                Button(action: save) {
                    Label("保存并检查", systemImage: "checkmark.circle")
                        .frame(maxWidth: .infinity)
                }
                .buttonStyle(.borderedProminent)
                .tint(Color(red: 0.73, green: 0.06, blue: 0.09))

                Button(action: reset) {
                    Label("默认地址", systemImage: "arrow.uturn.backward.circle")
                        .frame(maxWidth: .infinity)
                }
                .buttonStyle(.bordered)
            }
        }
        .padding(16)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 8))
    }
}

private struct MetricTile: View {
    let title: String
    let value: String
    let iconName: String

    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Image(systemName: iconName)
                .font(.title3)
                .foregroundStyle(Color(red: 0.73, green: 0.06, blue: 0.09))
            Text(title)
                .font(.caption)
                .foregroundStyle(.secondary)
            Text(value)
                .font(.headline)
                .lineLimit(2)
                .minimumScaleFactor(0.8)
        }
        .padding(14)
        .frame(maxWidth: .infinity, minHeight: 116, alignment: .leading)
        .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 8))
    }
}

#Preview {
    MonitorView(monitor: VideoMonitor())
}
