import SwiftUI
import CoreText
import WidgetKit

// Stesso stile "Stazione" del widget Instagram (Tabellone), così stanno bene uno sotto l'altro.
enum Stile {
    static let background = Color(hex: 0x151515)
    static let tileTop = Color(hex: 0x404040)
    static let tileBottom = Color(hex: 0x353535)
    static let seam = Color(hex: 0x0A0A0A)
    static let digit = Color(hex: 0xF3EFE4)
    static let label = Color(hex: 0xA8A8A8)
    static let muted = Color(hex: 0x8D8D8D)
    static let track = Color(hex: 0x3A3A3A)
    static let accent = Color(hex: 0xF2B33D)
    static let green = Color(hex: 0x7FC77A)
    static let red = Color(hex: 0xF0614A)

    static func color(_ level: Level) -> Color {
        switch level {
        case .ok: return green
        case .attenzione: return accent
        case .rischio, .esaurito: return red
        }
    }

    /// Le palette restano scure se va tutto bene, diventano gialle o rosse se c'è da stare attenti.
    static func tiles(_ level: Level) -> (top: Color, bottom: Color, text: Color) {
        switch level {
        case .ok: return (tileTop, tileBottom, digit)
        case .attenzione: return (Color(hex: 0xF2B33D), Color(hex: 0xE3A22C), background)
        case .rischio, .esaurito: return (Color(hex: 0xE8553E), Color(hex: 0xD44A35), Color(hex: 0xFFF4EE))
        }
    }

    private static let fontsRegistered: Void = {
        for name in ["BarlowCondensed-SemiBold", "BarlowCondensed-Medium"] {
            if let url = Bundle.main.url(forResource: name, withExtension: "ttf") {
                CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)
            }
        }
    }()

    static func font(_ size: CGFloat, medium: Bool = false) -> Font {
        _ = fontsRegistered
        return .custom(medium ? "BarlowCondensed-Medium" : "BarlowCondensed-SemiBold", size: size)
    }
}

extension Color {
    init(hex: UInt32) {
        self.init(red: Double((hex >> 16) & 0xFF) / 255,
                  green: Double((hex >> 8) & 0xFF) / 255,
                  blue: Double(hex & 0xFF) / 255)
    }
}

/// Una paletta del tabellone con la sua cifra.
struct FlapTile: View {
    let character: String
    let width: CGFloat
    var level: Level = .ok
    @Environment(\.widgetRenderingMode) private var renderingMode

    var body: some View {
        let height = width * 1.56
        let vibrant = renderingMode != .fullColor
        let colors = Stile.tiles(level)
        let strong = level != .ok
        ZStack {
            VStack(spacing: 0) {
                if vibrant {
                    Color.primary.opacity(strong ? 0.5 : 0.16)
                    Color.primary.opacity(strong ? 0.4 : 0.10)
                } else {
                    colors.top
                    colors.bottom
                }
            }
            Text(character)
                .font(Stile.font(width * 1.25))
                .foregroundStyle(vibrant ? Color.primary : colors.text)
                .offset(y: -width * 0.04)
            Rectangle().fill(Stile.seam).frame(height: 1)
            HStack {
                Rectangle().fill(Stile.seam).frame(width: 2, height: height * 0.12)
                Spacer()
                Rectangle().fill(Stile.seam).frame(width: 2, height: height * 0.12)
            }
        }
        .frame(width: width, height: height)
        .clipShape(RoundedRectangle(cornerRadius: width * 0.15, style: .continuous))
    }
}

/// La percentuale settimanale sulle palette, col simbolo % accanto.
struct PercentFlaps: View {
    let value: Double?
    let tile: CGFloat
    var level: Level = .ok

    var body: some View {
        let characters = value.map { Array(String(Int($0.rounded()))).map(String.init) } ?? ["-", "-"]
        HStack(alignment: .lastTextBaseline, spacing: 4) {
            ForEach(Array(characters.enumerated()), id: \.offset) { index, character in
                FlapTile(character: character, width: tile, level: level)
                    .id(characters.count - index)
            }
            Text("%")
                .font(Stile.font(tile * 0.8))
                .foregroundStyle(Stile.label)
                .padding(.leading, 2)
        }
    }
}

/// Barra del consumo. Il segno verticale è dove dovresti essere adesso (tabella di marcia sulle ore di lavoro).
struct UsageBar: View {
    let used: Double
    var marker: Double?
    var level: Level = .ok
    var height: CGFloat = 6

    var body: some View {
        GeometryReader { geo in
            let w = geo.size.width
            ZStack(alignment: .leading) {
                Capsule().fill(Stile.track)
                Capsule()
                    .fill(level == .ok ? Stile.digit : Stile.color(level))
                    .frame(width: max(height, w * min(1, used / 100)))
                if let marker {
                    Rectangle()
                        .fill(level == .ok ? Stile.accent : Stile.digit)
                        .frame(width: 2, height: height + 6)
                        .offset(x: min(w - 2, max(0, w * marker - 1)))
                }
            }
        }
        .frame(height: height + 6)
    }
}

// MARK: - Viste del widget

private struct SectionLabel: View {
    let text: String
    var size: CGFloat = 12
    var color: Color = Stile.label

    var body: some View {
        Text(text)
            .font(Stile.font(size))
            .tracking(1.6)
            .foregroundStyle(color)
            .lineLimit(1)
    }
}

/// Le 5 ore in una riga: etichetta, percentuale, barra e quando finisce.
private struct FiveBlock: View {
    let five: FiveReport?
    let now: Date

    var body: some View {
        VStack(alignment: .leading, spacing: 3) {
            HStack(alignment: .firstTextBaseline) {
                SectionLabel(text: "5 ORE", size: 12)
                Spacer(minLength: 4)
                Text(five.map { Testi.pct($0.used) } ?? "-")
                    .font(Stile.font(17))
                    .foregroundStyle(five.map { $0.level == .ok ? Stile.digit : Stile.color($0.level) } ?? Stile.muted)
                }
            UsageBar(used: five?.used ?? 0, level: five?.level ?? .ok, height: 4)
            Text(five.map { Testi.fiveDetail($0, now: now) } ?? "nessun dato")
                .font(Stile.font(12, medium: true))
                .foregroundStyle(five.map { $0.exhaustAt != nil ? Stile.color($0.level) : Stile.muted } ?? Stile.muted)
                .lineLimit(1)
        }
    }
}

private struct WaitingView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 6) {
            SectionLabel(text: "CLAUDE")
            Spacer(minLength: 0)
            Text("In attesa dei dati di Claude Code")
                .font(Stile.font(16, medium: true))
                .foregroundStyle(Stile.muted)
            Text("Apri Riserva e usa Claude Code")
                .font(Stile.font(13, medium: true))
                .foregroundStyle(Stile.muted.opacity(0.8))
            Spacer(minLength: 0)
        }
        .frame(maxWidth: .infinity, alignment: .leading)
    }
}

struct MediumRiserva: View {
    let report: Report
    private let side: CGFloat = 124

    var body: some View {
        if let week = report.week {
            HStack(spacing: 14) {
                VStack(alignment: .leading, spacing: 0) {
                    HStack(alignment: .firstTextBaseline) {
                        SectionLabel(text: "SETTIMANA")
                        Spacer(minLength: 4)
                        if let seen = report.lastSeen {
                            Text(Testi.time(seen))
                                .font(Stile.font(11, medium: true))
                                .foregroundStyle(Stile.muted)
                        }
                    }
                    Spacer(minLength: 0)
                    PercentFlaps(value: week.used, tile: 38, level: week.level)
                    Spacer(minLength: 0)
                    UsageBar(used: week.used, marker: week.target / 100, level: week.level)
                    Text("\(Testi.pct(week.free)) libero · reset \(Testi.when(week.reset, now: report.now))")
                        .font(Stile.font(12, medium: true))
                        .foregroundStyle(Stile.label)
                        .lineLimit(1)
                        .minimumScaleFactor(0.8)
                        .padding(.top, 3)
                }
                .frame(maxWidth: .infinity, alignment: .leading)

                Rectangle().fill(Color.white.opacity(0.1)).frame(width: 1)

                VStack(alignment: .leading, spacing: 0) {
                    SectionLabel(text: "A QUESTO RITMO", size: 11)
                    Text(Testi.verdict(week, now: report.now))
                        .font(Stile.font(21))
                        .foregroundStyle(Stile.color(week.level))
                        .lineLimit(1)
                        .minimumScaleFactor(0.6)
                    let detail = Testi.verdictDetail(week, now: report.now)
                    if !detail.isEmpty {
                        Text(detail)
                            .font(Stile.font(12, medium: true))
                            .foregroundStyle(Stile.label)
                            .lineLimit(1)
                            .minimumScaleFactor(0.8)
                    }
                    Text(Testi.plan(week))
                        .font(Stile.font(12, medium: true))
                        .foregroundStyle(week.ahead ? Stile.accent : Stile.muted)
                        .lineLimit(1)
                        .minimumScaleFactor(0.8)
                        .padding(.top, 1)
                    Spacer(minLength: 4)
                    FiveBlock(five: report.five, now: report.now)
                }
                .frame(width: side, alignment: .leading)
            }
        } else {
            WaitingView()
        }
    }
}

struct SmallRiserva: View {
    let report: Report

    var body: some View {
        if let week = report.week {
            VStack(alignment: .leading, spacing: 0) {
                SectionLabel(text: "SETTIMANA", size: 11)
                Spacer(minLength: 0)
                PercentFlaps(value: week.used, tile: 30, level: week.level)
                Spacer(minLength: 0)
                UsageBar(used: week.used, marker: week.target / 100, level: week.level, height: 5)
                Text(Testi.verdict(week, now: report.now))
                    .font(Stile.font(17))
                    .foregroundStyle(Stile.color(week.level))
                    .lineLimit(1)
                    .minimumScaleFactor(0.6)
                    .padding(.top, 2)
                Spacer(minLength: 0)
                HStack(alignment: .firstTextBaseline, spacing: 4) {
                    SectionLabel(text: "5 ORE", size: 11)
                    Text(report.five.map { Testi.pct($0.used) } ?? "-")
                        .font(Stile.font(14))
                        .foregroundStyle(report.five.map { $0.level == .ok ? Stile.digit : Stile.color($0.level) } ?? Stile.muted)
                    Spacer(minLength: 2)
                    Text(report.five.map { Testi.fiveDetail($0, now: report.now) } ?? "")
                        .font(Stile.font(11, medium: true))
                        .foregroundStyle(Stile.muted)
                        .lineLimit(1)
                        .minimumScaleFactor(0.7)
                }
            }
        } else {
            WaitingView()
        }
    }
}

// MARK: - Esempi per anteprime e galleria dei widget

extension UsageStore.Saved {
    /// Una settimana finta: 38% usato, reset fra 4 giorni, 5 ore al 25%.
    static func sample(now: Date = Date(), weekUsed: Double = 38, perDay: Double = 12) -> UsageStore.Saved {
        let reset = now.addingTimeInterval(4 * 86_400 + 3 * 3600)
        let fiveReset = now.addingTimeInterval(2 * 3600)
        var readings: [Reading] = []
        for h in stride(from: 30, through: 0, by: -1) {
            let t = now.addingTimeInterval(-Double(h) * 3600)
            let w = max(0, weekUsed - perDay * Double(h) / 24)
            readings.append(Reading(date: t, fiveHour: h == 0 ? 25 : nil, fiveHourReset: h == 0 ? fiveReset : nil,
                                    week: w.rounded(), weekReset: reset))
        }
        return UsageStore.Saved(readings: readings, lastSeen: now)
    }
}
