import Combine
import Foundation
import UIKit
import OSLog

private let logger = Logger(subsystem: "nahbar", category: "UserProfile")

// MARK: - UserProfileStore
// Speichert das eigene Nutzerprofil in UserDefaults (einfache Felder)
// und das Profilfoto als Datei im Documents-Verzeichnis.
// Kein SwiftData – ein einzelnes Profil braucht kein relationales Modell.

final class UserProfileStore: ObservableObject {
    static let shared = UserProfileStore()

    @Published private(set) var name: String        = ""
    @Published private(set) var displayName: String = ""
    @Published private(set) var aboutMe: String     = ""
    @Published private(set) var birthday: Date?     = nil
    @Published private(set) var gender: String      = ""
    @Published private(set) var occupation: String  = ""
    @Published private(set) var location: String    = ""
    @Published private(set) var likes: String       = ""
    @Published private(set) var dislikes: String    = ""
    @Published private(set) var socialStyle: String = ""

    private let defaults   = UserDefaults.standard
    private let storageKey = "nahbar.userProfile"

    private init() { load() }

    // MARK: - Derived

    var isEmpty: Bool {
        name.isEmpty && displayName.isEmpty && occupation.isEmpty && location.isEmpty
        && likes.isEmpty && dislikes.isEmpty && socialStyle.isEmpty && gender.isEmpty
    }

    var initials: String {
        let parts = name.split(separator: " ")
        if parts.count >= 2 {
            return (parts[0].prefix(1) + parts[1].prefix(1)).uppercased()
        }
        return name.isEmpty ? "?" : String(name.prefix(2)).uppercased()
    }

    // MARK: - Foto

    private var photoURL: URL? {
        FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            .first?.appendingPathComponent("nahbar_ich_photo.jpg")
    }

    var hasPhoto: Bool {
        guard let url = photoURL else { return false }
        return FileManager.default.fileExists(atPath: url.path)
    }

    func loadPhoto() -> UIImage? {
        guard let url = photoURL,
              let data = try? Data(contentsOf: url) else { return nil }
        return UIImage(data: data)
    }

    func savePhoto(_ image: UIImage?) {
        guard let url = photoURL else { return }
        do {
            if let image, let data = image.jpegData(compressionQuality: 0.82) {
                try data.write(to: url, options: .atomic)
            } else {
                try? FileManager.default.removeItem(at: url)
            }
        } catch {
            logger.error("Profilfoto konnte nicht gespeichert werden: \(error.localizedDescription)")
        }
        objectWillChange.send()
    }

    // MARK: - Geschlecht (gezieltes Update ohne alle Felder)

    func updateGender(_ value: String) {
        gender = value
        save()
    }

    // MARK: - Update (batch, explizit durch Nutzer bestätigt)

    func update(
        name: String,
        birthday: Date?,
        gender: String,
        occupation: String,
        location: String,
        likes: String,
        dislikes: String,
        socialStyle: String,
        displayName: String = "",
        aboutMe: String = ""
    ) {
        self.name        = name
        self.displayName = displayName
        self.aboutMe     = aboutMe
        self.birthday    = birthday
        self.gender      = gender
        self.occupation  = occupation
        self.location    = location
        self.likes       = likes
        self.dislikes    = dislikes
        self.socialStyle = socialStyle
        save()
    }

    // MARK: - Persistenz

    private func save() {
        var dict: [String: Any] = [
            "name":        name,
            "displayName": displayName,
            "aboutMe":     aboutMe,
            "gender":      gender,
            "occupation":  occupation,
            "location":    location,
            "likes":       likes,
            "dislikes":    dislikes,
            "socialStyle": socialStyle
        ]
        if let bd = birthday { dict["birthday"] = bd.timeIntervalSince1970 }
        defaults.set(dict, forKey: storageKey)
        logger.debug("UserProfile gespeichert")
    }

    // MARK: - Reset (Entwickler-Tool)

    func reset() {
        defaults.removeObject(forKey: storageKey)
        if let url = photoURL { try? FileManager.default.removeItem(at: url) }
        name = ""; displayName = ""; aboutMe = ""; gender = ""
        birthday = nil; occupation = ""; location = ""
        likes = ""; dislikes = ""; socialStyle = ""
        logger.info("UserProfile zurückgesetzt")
    }

    private func load() {
        guard let dict = defaults.dictionary(forKey: storageKey) else { return }
        name        = dict["name"]        as? String ?? ""
        displayName = dict["displayName"] as? String ?? ""
        aboutMe     = dict["aboutMe"]     as? String ?? ""
        gender      = dict["gender"]      as? String ?? ""
        occupation  = dict["occupation"]  as? String ?? ""
        location    = dict["location"]    as? String ?? ""
        likes       = dict["likes"]       as? String ?? ""
        // Migration: alte "Interessen" in "Mag ich" übernehmen, falls noch nicht gesetzt
        if likes.isEmpty, let legacy = dict["interests"] as? String, !legacy.isEmpty {
            likes = legacy
        }
        dislikes    = dict["dislikes"]    as? String ?? ""
        socialStyle = dict["socialStyle"] as? String ?? ""
        if let ts = dict["birthday"] as? Double {
            birthday = Date(timeIntervalSince1970: ts)
        }
        logger.debug("UserProfile geladen: \(self.name)")
    }
}
