import WidgetKit
import SwiftUI

// MARK: - Brand
//
// Single source of truth for widget colors on iOS. To rebrand the widget,
// edit ONLY this enum.
//
// IMPORTANT: keep these values in sync with the Android counterparts in
// Firebase/android/app/src/main/res/values/colors.xml.
enum WidgetBrand {
    // Background gradient.
    static let gradientStart = Color(red: 0.08, green: 0.03, blue: 0.16)   // #FF140829
    static let gradientEnd   = Color(red: 0.20, green: 0.09, blue: 0.42)   // #FF33176B

    // PRO plan pill (gold) + its soft background.
    static let proGold       = Color(red: 1.00, green: 0.84, blue: 0.00)   // #FFFFD700
    static let proPillBg     = Color(red: 1.00, green: 0.84, blue: 0.00).opacity(0.18)

    // Free plan pill — low-emphasis translucent white.
    static let freePillBg    = Color.white.opacity(0.08)

    // "+" circular button on medium/large widgets.
    static let addButtonBg   = Color.white.opacity(0.18)
}

struct MyWidgetProvider: TimelineProvider {
    func placeholder(in context: Context) -> MyWidgetEntry {
        MyWidgetEntry.defaults()
    }

    func getSnapshot(in context: Context, completion: @escaping (MyWidgetEntry) -> Void) {
        completion(MyWidgetEntry.fromPrefs())
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<MyWidgetEntry>) -> Void) {
        getSnapshot(in: context) { entry in
            completion(Timeline(entries: [entry], policy: .atEnd))
        }
    }
}

struct MyWidgetEntry: TimelineEntry {
    let date: Date
    let greeting: String
    let title: String
    let planText: String
    let isPro: Bool
    let quote: String
    let quoteAuthor: String

    /// Reads the latest data from the shared app group. If a string was never
    /// written (first install before the Flutter app pushed data), falls back
    /// to a time-based greeting in the device language so the widget never
    /// shows a blank gradient.
    static func fromPrefs() -> MyWidgetEntry {
        let prefs = UserDefaults(suiteName: "group.com.aicrus.firebase.kit")
        let storedGreeting = prefs?.string(forKey: "greeting") ?? ""
        let storedTitle = prefs?.string(forKey: "title") ?? ""
        let storedPlan = prefs?.string(forKey: "planText") ?? ""
        let storedIsPro = prefs?.string(forKey: "isPro") == "true"
        let storedQuote = prefs?.string(forKey: "quote") ?? ""
        let storedQuoteAuthor = prefs?.string(forKey: "quoteAuthor") ?? ""

        let defaults = MyWidgetEntry.defaults()
        return MyWidgetEntry(
            date: Date(),
            greeting: storedGreeting.isEmpty ? defaults.greeting : storedGreeting,
            title: storedTitle.isEmpty ? defaults.title : storedTitle,
            planText: storedPlan,
            isPro: storedIsPro,
            quote: storedQuote,
            quoteAuthor: storedQuoteAuthor
        )
    }

    /// Fallback used ONLY in the brief window between the widget being placed
    /// and the Flutter app pushing real values. Kept dead simple — the
    /// time-aware greeting in three languages lives on the Dart side
    /// (home_widget_mywidget_service.dart::_greeting). Duplicating that logic
    /// here was a maintenance trap when adding new locales.
    static func defaults() -> MyWidgetEntry {
        let lang = Locale.current.language.languageCode?.identifier ?? "en"
        let greeting: String
        let hello: String
        switch lang {
        case "pt": (greeting, hello) = ("Olá", "Bem-vindo!")
        case "es": (greeting, hello) = ("Hola", "¡Bienvenido!")
        default:   (greeting, hello) = ("Hello", "Welcome!")
        }
        return MyWidgetEntry(
            date: Date(),
            greeting: greeting,
            title: hello,
            planText: "",
            isPro: false,
            quote: "",
            quoteAuthor: ""
        )
    }
}

struct MyWidgetWidgetView: View {
    var entry: MyWidgetProvider.Entry
    @Environment(\.widgetFamily) var family

    private var titleSize: CGFloat {
        switch family {
        case .systemSmall: return 24
        case .systemMedium: return 28
        default: return 34
        }
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            Text(entry.greeting)
                .font(.system(size: 11, weight: .medium, design: .rounded))
                .foregroundStyle(.white.opacity(0.55))
                .lineLimit(1)

            Spacer().frame(height: 6)

            // Reserve room on the right so the title never sits flush against
            // the widget edge (looks cramped, especially on small).
            Text(entry.title)
                .font(.system(size: titleSize, weight: .bold, design: .rounded))
                .foregroundStyle(.white)
                .lineLimit(2)
                .minimumScaleFactor(0.75)
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding(.trailing, 8)

            // Quote line counts per iOS widget family (fixed sizes, so we
            // can hand-tune instead of measuring):
            //   small  → 1 line   (just the first sentence, no attribution)
            //   medium → 2 lines  (horizontal, short — fits two short lines)
            //   large  → 4 lines + bold attribution (the whole quote)
            if !entry.quote.isEmpty {
                let lineLimit: Int = {
                    switch family {
                    case .systemSmall:  return 1
                    case .systemMedium: return 2
                    default:            return 4
                    }
                }()

                Spacer().frame(height: 12)
                Text(entry.quote)
                    .font(.system(size: 15, weight: .light, design: .rounded))
                    .italic()
                    .foregroundStyle(.white.opacity(0.7))
                    .lineLimit(lineLimit)
                    .lineSpacing(2)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding(.trailing, 8)

                if family == .systemLarge && !entry.quoteAuthor.isEmpty {
                    // Attribution on its own line, right-aligned and bold so
                    // it reads as the source of the quote rather than part of
                    // the quote itself.
                    Text(entry.quoteAuthor)
                        .font(.system(size: 13, weight: .bold, design: .rounded))
                        .foregroundStyle(.white.opacity(0.7))
                        .frame(maxWidth: .infinity, alignment: .trailing)
                        .padding(.trailing, 8)
                        .padding(.top, 4)
                }
            }

            Spacer()

            // Plan tag + (medium/large only) decorative "+" pill.
            // Small intentionally drops the "+" so the layout breathes —
            // the pill sits flush left like the original design.
            // Empty planText hides the pill (used in logged-out state).
            HStack(alignment: .center, spacing: 8) {
                if !entry.planText.isEmpty {
                    if entry.isPro {
                        Label(entry.planText, systemImage: "star.fill")
                            .font(.system(size: 11, weight: .bold, design: .rounded))
                            .foregroundStyle(WidgetBrand.proGold)
                            .padding(.horizontal, 10)
                            .padding(.vertical, 5)
                            .background(WidgetBrand.proPillBg)
                            .clipShape(Capsule())
                    } else {
                        Text(entry.planText)
                            .font(.system(size: 11, weight: .medium, design: .rounded))
                            .foregroundStyle(.white.opacity(0.45))
                            .padding(.horizontal, 10)
                            .padding(.vertical, 5)
                            .background(WidgetBrand.freePillBg)
                            .clipShape(Capsule())
                    }
                }

                if family != .systemSmall {
                    Spacer(minLength: 12)
                    ZStack {
                        Circle()
                            .fill(WidgetBrand.addButtonBg)
                            .frame(width: 34, height: 34)
                        Image(systemName: "plus")
                            .font(.system(size: 16, weight: .bold))
                            .foregroundStyle(.white)
                    }
                }
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
        .padding()
    }
}

struct MyWidgetWidget: Widget {
    let kind: String = "MyWidgetWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: MyWidgetProvider()) { entry in
            MyWidgetWidgetView(entry: entry)
                .containerBackground(for: .widget) {
                    LinearGradient(
                        gradient: Gradient(colors: [
                            WidgetBrand.gradientStart,
                            WidgetBrand.gradientEnd,
                        ]),
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                }
        }
        .configurationDisplayName("MyWidget")
        .description("Sample home widget generated by kasy")
        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
    }
}

#Preview("Small", as: .systemSmall) {
    MyWidgetWidget()
} timeline: {
    MyWidgetEntry(date: .now, greeting: "Bom dia", title: "Olá, Paulo!", planText: "PRO", isPro: true, quote: "Seu tempo é limitado.", quoteAuthor: "")
}

#Preview("Medium", as: .systemMedium) {
    MyWidgetWidget()
} timeline: {
    MyWidgetEntry(date: .now, greeting: "Boa tarde", title: "Olá, Paulo!", planText: "Plano grátis", isPro: false, quote: "Seu tempo é limitado.\nNão viva a vida de outra pessoa.", quoteAuthor: "")
}

#Preview("Large", as: .systemLarge) {
    MyWidgetWidget()
} timeline: {
    MyWidgetEntry(date: .now, greeting: "Boa noite", title: "Olá, Paulo!", planText: "PRO", isPro: true, quote: "Seu tempo é limitado.\nNão viva a vida de outra pessoa.\nTenha coragem de seguir sua intuição.\nTodo o resto é secundário.", quoteAuthor: "Steve Jobs")
}
