import SwiftUI
import CoreData

// MARK: - AI Analysis State

private enum AnalysisState {
    case idle
    case loading
    case result(AIAnalysisResult, Date)
    case error(String)
}

// MARK: - Timeline Item

private enum LogbuchItem: Identifiable {
    case moment(Moment)
    case logEntry(LogEntry)

    var id: String {
        switch self {
        case .moment(let m):   return "m-\(m.id)"
        case .logEntry(let e): return "e-\(e.id)"
        }
    }

    var date: Date {
        switch self {
        case .moment(let m):   return m.createdAt
        case .logEntry(let e): return e.loggedAt
        }
    }

    var icon: String {
        switch self {
        case .moment(let m):   return m.type.icon
        case .logEntry(let e): return e.type.icon
        }
    }

    var label: String {
        switch self {
        case .moment(let m):   return m.type.rawValue
        case .logEntry(let e): return e.type.rawValue
        }
    }

    var title: String {
        switch self {
        case .moment(let m):   return m.text
        case .logEntry(let e): return e.title
        }
    }

    var isLogEntry: Bool {
        if case .logEntry = self { return true }
        return false
    }
}

// MARK: - Logbuch View

struct LogbuchView: View {
    @Environment(\.nahbarTheme) var theme
    @Environment(\.dismiss) var dismiss
    @StateObject private var store = StoreManager.shared
    let person: Person

    @State private var analysisState: AnalysisState = .idle
    @State private var showPaywall = false
    @State private var remainingRequests: Int = AIAnalysisService.shared.remainingRequests

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 28) {

                // Timeline
                if mergedItems.isEmpty {
                    emptyState
                } else {
                    ForEach(groupedItems, id: \.0) { month, items in
                        monthSection(month: month, items: items)
                    }
                }

                // PRO: KI-Analyse
                aiAnalysisCard
            }
            .padding(.horizontal, 20)
            .padding(.top, 16)
            .padding(.bottom, 48)
        }
        .background(theme.backgroundPrimary.ignoresSafeArea())
        .navigationTitle("Logbuch")
        .navigationBarTitleDisplayMode(.inline)
        .themedNavBar()
        .sheet(isPresented: $showPaywall) { PaywallView() }
        .onReceive(
            NotificationCenter.default.publisher(
                for: Notification.Name("NSManagedObjectContextObjectsDidChangeNotification")
            )
        ) { notification in
            guard notification.userInfo?[NSInvalidatedAllObjectsKey] != nil else { return }
            dismiss()
        }
        .onAppear {
            if let cached = AIAnalysisService.shared.loadCached(for: person) {
                analysisState = .result(cached.asResult, cached.analyzedAt)
            }
            remainingRequests = AIAnalysisService.shared.remainingRequests
        }
    }

    // MARK: - Month Section

    private func monthSection(month: String, items: [LogbuchItem]) -> some View {
        VStack(alignment: .leading, spacing: 10) {
            Text(month.uppercased())
                .font(.system(size: 11, weight: .semibold))
                .tracking(0.8)
                .foregroundStyle(theme.contentTertiary)

            VStack(spacing: 0) {
                ForEach(Array(items.enumerated()), id: \.element.id) { index, item in
                    logbuchRow(item: item)
                    if index < items.count - 1 {
                        RowDivider()
                    }
                }
            }
            .background(theme.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
        }
    }

    // MARK: - Row

    private func logbuchRow(item: LogbuchItem) -> some View {
        HStack(alignment: .top, spacing: 12) {
            Image(systemName: item.icon)
                .font(.system(size: 14, weight: .light))
                .foregroundStyle(item.isLogEntry ? theme.accent : theme.contentTertiary)
                .frame(width: 20)
                .padding(.top, 2)

            VStack(alignment: .leading, spacing: 3) {
                Text(item.title)
                    .font(.system(size: 15, design: theme.displayDesign))
                    .foregroundStyle(theme.contentPrimary)
                    .fixedSize(horizontal: false, vertical: true)

                HStack(spacing: 6) {
                    Text(item.label)
                        .font(.system(size: 12))
                        .foregroundStyle(theme.contentTertiary)
                    Text("·")
                        .font(.system(size: 12))
                        .foregroundStyle(theme.contentTertiary)
                    Text(item.date.formatted(.dateTime.day().month(.abbreviated).year().locale(Locale(identifier: "de_DE"))))
                        .font(.system(size: 12))
                        .foregroundStyle(theme.contentTertiary)
                }
            }

            Spacer()
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

    // MARK: - Empty State

    private var emptyState: some View {
        VStack(spacing: 8) {
            Image(systemName: "book.closed")
                .font(.system(size: 32, weight: .light))
                .foregroundStyle(theme.contentTertiary)
            Text("Noch keine Einträge")
                .font(.system(size: 16, weight: .light))
                .foregroundStyle(theme.contentSecondary)
            Text("Momente und abgeschlossene Schritte erscheinen hier.")
                .font(.system(size: 14))
                .foregroundStyle(theme.contentTertiary)
                .multilineTextAlignment(.center)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 48)
    }

    // MARK: - PRO: KI-Analyse

    private var aiAnalysisCard: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack(spacing: 6) {
                SectionHeader(title: "KI-Auswertung", icon: "sparkles")
                if !store.isPro {
                    Text("PRO")
                        .font(.system(size: 10, weight: .bold))
                        .foregroundStyle(theme.accent)
                        .padding(.horizontal, 7)
                        .padding(.vertical, 3)
                        .background(theme.accent.opacity(0.10))
                        .clipShape(Capsule())
                }
            }

            if !store.isPro {
                // Locked state
                Button { showPaywall = true } label: {
                    HStack(spacing: 10) {
                        Image(systemName: "sparkles")
                            .foregroundStyle(theme.accent)
                        Text("nahbar Pro freischalten für KI-Analyse")
                            .font(.system(size: 14, weight: .medium))
                            .foregroundStyle(theme.accent)
                        Spacer()
                        Image(systemName: "chevron.right")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                    }
                    .padding(16)
                    .background(theme.surfaceCard)
                    .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                }
            } else {
                // Active state
                VStack(alignment: .leading, spacing: 0) {
                    switch analysisState {
                    case .idle:
                        Button {
                            Task { await runAnalysis() }
                        } label: {
                            HStack(spacing: 10) {
                                Image(systemName: "sparkles")
                                    .foregroundStyle(theme.accent)
                                Text("\(person.firstName) analysieren")
                                    .font(.system(size: 15, weight: .medium))
                                    .foregroundStyle(theme.contentPrimary)
                                Spacer()
                                Image(systemName: "chevron.right")
                                    .font(.system(size: 12))
                                    .foregroundStyle(theme.contentTertiary)
                            }
                            .padding(16)
                        }

                    case .loading:
                        HStack(spacing: 12) {
                            ProgressView().tint(theme.accent)
                            VStack(alignment: .leading, spacing: 2) {
                                Text("Analysiere Logbuch…")
                                    .font(.system(size: 14))
                                    .foregroundStyle(theme.contentSecondary)
                                Text("Das kann bis zu einer Minute dauern.")
                                    .font(.system(size: 12))
                                    .foregroundStyle(theme.contentTertiary)
                            }
                        }
                        .padding(16)

                    case .result(let result, let date):
                        VStack(alignment: .leading, spacing: 0) {
                            analysisSection(icon: "waveform.path", title: "Muster & Themen", text: result.patterns)
                            RowDivider()
                            analysisSection(icon: "person.2", title: "Beziehungsqualität", text: result.relationship)
                            RowDivider()
                            analysisSection(icon: "arrow.right.circle", title: "Empfehlung", text: result.recommendation)
                            RowDivider()
                            HStack(spacing: 0) {
                                // Zeitstempel
                                VStack(alignment: .leading, spacing: 1) {
                                    Text("Analysiert")
                                        .font(.system(size: 11))
                                        .foregroundStyle(theme.contentTertiary)
                                    Text(date.formatted(.dateTime.day().month(.abbreviated).hour().minute().locale(Locale(identifier: "de_DE"))))
                                        .font(.system(size: 11))
                                        .foregroundStyle(theme.contentTertiary)
                                }
                                .padding(.leading, 16)
                                .padding(.vertical, 12)

                                Spacer()

                                // Aktualisieren
                                Button {
                                    Task { await runAnalysis() }
                                } label: {
                                    HStack(spacing: 4) {
                                        Image(systemName: "arrow.clockwise")
                                            .font(.system(size: 12))
                                        Text(remainingRequests > 0 ? "Aktualisieren (\(remainingRequests))" : "Limit erreicht")
                                            .font(.system(size: 13))
                                    }
                                    .foregroundStyle(remainingRequests > 0 ? theme.accent : theme.contentTertiary)
                                }
                                .disabled(remainingRequests == 0 || isPurchasing)
                                .padding(.trailing, 16)
                                .padding(.vertical, 12)
                            }
                        }

                    case .error(let msg):
                        VStack(alignment: .leading, spacing: 8) {
                            Label("Analyse fehlgeschlagen", systemImage: "exclamationmark.triangle")
                                .font(.system(size: 14, weight: .medium))
                                .foregroundStyle(theme.contentSecondary)
                            Text(msg)
                                .font(.system(size: 12))
                                .foregroundStyle(theme.contentTertiary)
                            Button {
                                Task { await runAnalysis() }
                            } label: {
                                Text("Erneut versuchen")
                                    .font(.system(size: 13, weight: .medium))
                                    .foregroundStyle(theme.accent)
                            }
                        }
                        .padding(16)
                    }
                }
                .background(theme.surfaceCard)
                .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
            }
        }
    }

    private func analysisSection(icon: String, title: String, text: String) -> some View {
        HStack(alignment: .top, spacing: 12) {
            Image(systemName: icon)
                .font(.system(size: 13))
                .foregroundStyle(theme.accent)
                .frame(width: 20)
                .padding(.top, 2)
            VStack(alignment: .leading, spacing: 6) {
                Text(title)
                    .font(.system(size: 13, weight: .semibold))
                    .foregroundStyle(theme.contentSecondary)
                Text(LocalizedStringKey(text))
                    .font(.system(size: 14, design: theme.displayDesign))
                    .foregroundStyle(theme.contentPrimary)
                    .fixedSize(horizontal: false, vertical: true)
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

    private var isPurchasing: Bool {
        if case .loading = analysisState { return true }
        return false
    }

    private func runAnalysis() async {
        guard !mergedItems.isEmpty else { return }
        guard !AIAnalysisService.shared.isRateLimited else { return }
        analysisState = .loading
        do {
            let result = try await AIAnalysisService.shared.analyze(person: person)
            remainingRequests = AIAnalysisService.shared.remainingRequests
            analysisState = .result(result, Date())
        } catch {
            // Bei Fehler alten Cache wiederherstellen falls vorhanden
            if let cached = AIAnalysisService.shared.loadCached(for: person) {
                analysisState = .result(cached.asResult, cached.analyzedAt)
            } else {
                analysisState = .error(error.localizedDescription)
            }
        }
    }

    // MARK: - Data

    private var mergedItems: [LogbuchItem] {
        let moments  = person.sortedMoments.map  { LogbuchItem.moment($0) }
        let entries  = person.sortedLogEntries.map { LogbuchItem.logEntry($0) }
        return (moments + entries).sorted { $0.date > $1.date }
    }

    private var groupedItems: [(String, [LogbuchItem])] {
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM yyyy"
        formatter.locale = Locale(identifier: "de_DE")

        var result: [(String, [LogbuchItem])] = []
        var currentKey = ""
        var currentGroup: [LogbuchItem] = []

        for item in mergedItems {
            let key = formatter.string(from: item.date)
            if key != currentKey {
                if !currentGroup.isEmpty { result.append((currentKey, currentGroup)) }
                currentKey = key
                currentGroup = [item]
            } else {
                currentGroup.append(item)
            }
        }
        if !currentGroup.isEmpty { result.append((currentKey, currentGroup)) }
        return result
    }
}
