import WidgetKit
import SwiftUI

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

    /// 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 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
        )
    }

    /// Time-aware fallback used when the Flutter side has not yet written
    /// data. Picks the language from the device locale so the first render
    /// is at least in the user's language; once the app runs, the real
    /// values (in the app locale) overwrite this.
    static func defaults() -> MyWidgetEntry {
        let hour = Calendar.current.component(.hour, from: Date())
        let lang = Locale.current.language.languageCode?.identifier ?? "en"
        let (morning, afternoon, evening, hello): (String, String, String, String)
        switch lang {
        case "pt": (morning, afternoon, evening, hello) = ("Bom dia", "Boa tarde", "Boa noite", "Olá!")
        case "es": (morning, afternoon, evening, hello) = ("Buenos días", "Buenas tardes", "Buenas noches", "¡Hola!")
        default:   (morning, afternoon, evening, hello) = ("Good morning", "Good afternoon", "Good evening", "Hi there!")
        }
        let greeting: String
        if hour < 12 { greeting = morning }
        else if hour < 18 { greeting = afternoon }
        else { greeting = evening }
        return MyWidgetEntry(
            date: Date(),
            greeting: greeting,
            title: hello,
            planText: "",
            isPro: false,
            quote: ""
        )
    }
}

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)

            // Motivational quote only on the large widget — small/medium
            // don't have the vertical room. Thin, low-emphasis typography
            // so the title stays the hero element.
            if family == .systemLarge && !entry.quote.isEmpty {
                Spacer().frame(height: 12)
                Text(entry.quote)
                    .font(.system(size: 15, weight: .light, design: .rounded))
                    .italic()
                    .foregroundStyle(.white.opacity(0.7))
                    .lineLimit(4)
                    .lineSpacing(2)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding(.trailing, 8)
            }

            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(Color(red: 1.0, green: 0.84, blue: 0.0))
                            .padding(.horizontal, 10)
                            .padding(.vertical, 5)
                            .background(Color(red: 1.0, green: 0.84, blue: 0.0).opacity(0.18))
                            .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(Color.white.opacity(0.08))
                            .clipShape(Capsule())
                    }
                }

                if family != .systemSmall {
                    Spacer(minLength: 12)
                    ZStack {
                        Circle()
                            .fill(Color.white.opacity(0.18))
                            .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: [
                            Color(red: 0.08, green: 0.03, blue: 0.16),
                            Color(red: 0.20, green: 0.09, blue: 0.42),
                        ]),
                        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: "")
}

#Preview("Medium", as: .systemMedium) {
    MyWidgetWidget()
} timeline: {
    MyWidgetEntry(date: .now, greeting: "Boa tarde", title: "Olá, Paulo!", planText: "Plano grátis", isPro: false, quote: "")
}

#Preview("Large", as: .systemLarge) {
    MyWidgetWidget()
} timeline: {
    MyWidgetEntry(date: .now, greeting: "Boa noite", title: "Olá, Paulo!", planText: "PRO", isPro: true, quote: "Sempre parece impossível, até que seja feito.")
}
