import SwiftUI
import PhotosUI
import SwiftData
import Contacts

private let socialStyleOptions = [
    "Introvertiert",
    "Eher introvertiert",
    "Ausgeglichen",
    "Eher extrovertiert",
    "Extrovertiert"
]

// MARK: - IchView

struct IchView: View {
    @Environment(\.nahbarTheme) var theme
    @EnvironmentObject var profileStore: UserProfileStore

    @StateObject private var personalityStore = PersonalityStore.shared

    @State private var profilePhoto: UIImage? = nil
    @State private var showingEdit = false
    @State private var showingQuiz = false
    @State private var showingPersonalityDetail = false

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(alignment: .leading, spacing: 28) {
                    headerSection
                    if !profileStore.isEmpty { infoSection }
                    if profileStore.isEmpty  { emptyState   }
                    personalitySection
                }
                .padding(.horizontal, 20)
                .padding(.top, 12)
                .padding(.bottom, 48)
            }
            .background(theme.backgroundPrimary.ignoresSafeArea())
            .navigationBarHidden(true)
        }
        .sheet(isPresented: $showingEdit, onDismiss: {
            profilePhoto = profileStore.loadPhoto()
        }) {
            IchEditView()
        }

        .onAppear {
            profilePhoto = profileStore.loadPhoto()
        }
        .sheet(isPresented: $showingQuiz) {
            PersonalityQuizView { _ in
                showingQuiz = false
            }
        }
        .sheet(isPresented: $showingPersonalityDetail) {
            if let profile = personalityStore.profile {
                NavigationStack {
                    PersonalityResultView(profile: profile) {
                        showingPersonalityDetail = false
                    }
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbar {
                        ToolbarItem(placement: .topBarTrailing) {
                            Button("Fertig") { showingPersonalityDetail = false }
                        }
                    }
                }
            }
        }
    }

    // MARK: - Persönlichkeit

    @ViewBuilder
    private var personalitySection: some View {
        VStack(alignment: .leading, spacing: 10) {
            SectionHeader(title: "Persönlichkeit", icon: "brain")
            if let profile = personalityStore.profile, profile.isComplete {
                PersonalityProfileCard(
                    profile: profile,
                    onRetake:      { showingQuiz = true },
                    onShowDetails: { showingPersonalityDetail = true }
                )
            } else if !personalityStore.hasSkippedQuiz {
                QuizPromptCard(onStart: { showingQuiz = true })
            }
        }
    }

    // MARK: - Header

    private var headerSection: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Text("Ich")
                    .font(.system(size: 32, weight: .light, design: theme.displayDesign))
                    .foregroundStyle(theme.contentPrimary)
                Spacer()
                Button { showingEdit = true } label: {
                    Image(systemName: "pencil")
                        .font(.system(size: 15, weight: .medium))
                        .foregroundStyle(theme.contentTertiary)
                        .padding(8)
                        .background(theme.backgroundSecondary)
                        .clipShape(Circle())
                }
            }

            HStack(spacing: 16) {
                // Avatar
                avatarView
                    .frame(width: 68, height: 68)
                    .clipShape(Circle())

                VStack(alignment: .leading, spacing: 5) {
                    Text(profileStore.name.isEmpty ? "Dein Name" : profileStore.name)
                        .font(.system(size: 22, weight: .light, design: theme.displayDesign))
                        .foregroundStyle(
                            profileStore.name.isEmpty ? theme.contentTertiary : theme.contentPrimary
                        )

                    if let birthday = profileStore.birthday {
                        HStack(spacing: 5) {
                            Image(systemName: "birthday.cake")
                                .font(.system(size: 11))
                                .foregroundStyle(theme.contentTertiary)
                            Text(birthday.formatted(
                                .dateTime.day().month(.wide)
                            ))
                            .font(.system(size: 13))
                            .foregroundStyle(theme.contentTertiary)
                        }
                    }

                    if !profileStore.occupation.isEmpty {
                        Text(profileStore.occupation)
                            .font(.system(size: 13))
                            .foregroundStyle(theme.contentSecondary)
                    }
                }

                Spacer()
            }
            .padding(16)
            .background(theme.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
        }
    }

    @ViewBuilder
    private var avatarView: some View {
        if let photo = profilePhoto {
            Image(uiImage: photo)
                .resizable()
                .scaledToFill()
        } else {
            Text(profileStore.initials)
                .font(.system(size: 24, weight: .medium, design: theme.displayDesign))
                .foregroundStyle(theme.accent)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(theme.accent.opacity(0.12))
        }
    }

    // MARK: - Info

    private var infoSection: some View {
        VStack(alignment: .leading, spacing: 10) {
            // Über mich
            let hasUeberMich = !profileStore.location.isEmpty || !profileStore.socialStyle.isEmpty
            if hasUeberMich {
                SectionHeader(title: "Über mich", icon: "person")
                VStack(spacing: 0) {
                    if !profileStore.location.isEmpty {
                        infoRow(label: "Wohnort", value: profileStore.location)
                        if !profileStore.socialStyle.isEmpty { RowDivider() }
                    }
                    if !profileStore.socialStyle.isEmpty {
                        infoRow(label: "Sozialstil", value: profileStore.socialStyle)
                    }
                }
                .background(theme.surfaceCard)
                .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
            }

            // Vorlieben
            SectionHeader(title: "Vorlieben", icon: "heart")
            if profileStore.likes.isEmpty && profileStore.dislikes.isEmpty {
                // Nudge: fehlende Vorlieben
                Button { showingEdit = true } label: {
                    HStack(spacing: 12) {
                        Image(systemName: "sparkles")
                            .font(.system(size: 14))
                            .foregroundStyle(theme.accent)
                        Text("Uns fehlt noch was – wir würden gerne mehr von dir erfahren.")
                            .font(.system(size: 14))
                            .foregroundStyle(theme.contentSecondary)
                            .multilineTextAlignment(.leading)
                        Spacer()
                        Image(systemName: "chevron.right")
                            .font(.system(size: 11, weight: .medium))
                            .foregroundStyle(theme.contentTertiary)
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 14)
                    .background(theme.accent.opacity(0.06))
                    .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    .overlay(
                        RoundedRectangle(cornerRadius: theme.radiusCard)
                            .strokeBorder(theme.accent.opacity(0.18), lineWidth: 1)
                    )
                }
                .buttonStyle(.plain)
            } else {
                VStack(spacing: 0) {
                    if !profileStore.likes.isEmpty {
                        InterestChipRow(label: "Mag ich", text: profileStore.likes, color: .green)
                        if !profileStore.dislikes.isEmpty { RowDivider() }
                    }
                    if !profileStore.dislikes.isEmpty {
                        InterestChipRow(label: "Mag ich nicht", text: profileStore.dislikes, color: .red)
                    }
                }
                .background(theme.surfaceCard)
                .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
            }
        }
    }

    private func infoRow(label: String, value: String) -> some View {
        HStack(alignment: .top, spacing: 12) {
            Text(label)
                .font(.system(size: 13))
                .foregroundStyle(theme.contentTertiary)
                .frame(width: 80, alignment: .leading)
            Text(value)
                .font(.system(size: 15))
                .foregroundStyle(theme.contentPrimary)
                .fixedSize(horizontal: false, vertical: true)
            Spacer()
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

    // MARK: - Empty State

    private var emptyState: some View {
        VStack(spacing: 16) {
            Text("Wer bist du?")
                .font(.system(size: 20, weight: .light, design: theme.displayDesign))
                .foregroundStyle(theme.contentPrimary)
            Text("Füge deine eigenen Infos hinzu – damit nahbar noch besser versteht, in welchem Kontext du Beziehungen pflegst.")
                .font(.system(size: 14))
                .foregroundStyle(theme.contentTertiary)
                .multilineTextAlignment(.center)
            Button { showingEdit = true } label: {
                Text("Profil einrichten")
                    .font(.system(size: 15, weight: .medium))
                    .foregroundStyle(.white)
                    .padding(.horizontal, 24)
                    .padding(.vertical, 12)
                    .background(theme.accent)
                    .clipShape(Capsule())
            }
        }
        .frame(maxWidth: .infinity)
        .padding(.top, 12)
    }

}

// MARK: - IchEditView

struct IchEditView: View {
    @Environment(\.nahbarTheme) var theme
    @Environment(\.dismiss) var dismiss
    @EnvironmentObject var profileStore: UserProfileStore

    @Query private var allPeople: [Person]

    @State private var name: String
    @State private var hasBirthday: Bool
    @State private var birthday: Date

    @State private var gender: String
    @State private var occupation: String
    @State private var location: String
    @State private var likes: String
    @State private var dislikes: String
    @State private var socialStyle: String
    @State private var selectedPhoto: UIImage?
    @State private var photoPickerItem: PhotosPickerItem? = nil
    @State private var showingContactPicker = false

    init() {
        let store = UserProfileStore.shared
        _name        = State(initialValue: store.name)
        _hasBirthday = State(initialValue: store.birthday != nil)
        _birthday    = State(initialValue: store.birthday ?? IchEditView.defaultBirthday)
        _gender      = State(initialValue: store.gender)
        _occupation  = State(initialValue: store.occupation)
        _location    = State(initialValue: store.location)
        _likes       = State(initialValue: store.likes)
        _dislikes    = State(initialValue: store.dislikes)
        _socialStyle = State(initialValue: store.socialStyle)
        _selectedPhoto = State(initialValue: store.loadPhoto())
    }

    private static var defaultBirthday: Date {
        Calendar.current.date(from: DateComponents(year: 1990, month: 1, day: 1)) ?? Date()
    }

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

                    // Foto
                    photoSection

                    // Name
                    formSection("Name") {
                        TextField("Wie heißt du?", text: $name)
                            .font(.system(size: 22, weight: .light, design: theme.displayDesign))
                            .foregroundStyle(theme.contentPrimary)
                            .tint(theme.accent)
                    }

                    // Geburtstag
                    formSection("Geburtstag") {
                        VStack(spacing: 0) {
                            HStack {
                                Text("Datum angeben")
                                    .font(.system(size: 15))
                                    .foregroundStyle(theme.contentPrimary)
                                Spacer()
                                Toggle("", isOn: $hasBirthday)
                                    .tint(theme.accent)
                                    .labelsHidden()
                            }
                            .padding(.horizontal, 14)
                            .padding(.vertical, 11)

                            if hasBirthday {
                                Divider().padding(.horizontal, 14)
                                DatePicker("", selection: $birthday, displayedComponents: .date)
                                    .datePickerStyle(.compact)
                                    .labelsHidden()
                                    .tint(theme.accent)
                                    .environment(\.locale, Locale(identifier: "de_DE"))
                                    .padding(.horizontal, 14)
                                    .padding(.vertical, 10)
                            }
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    }

                    // Details
                    formSection("Details") {
                        VStack(spacing: 0) {
                            genderPickerRow
                            Divider().padding(.leading, 16)
                            inlineField("Beruf", text: $occupation)
                            Divider().padding(.leading, 16)
                            inlineField("Wohnort", text: $location)
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    }

                    // Vorlieben
                    formSection("Vorlieben") {
                        VStack(spacing: 0) {
                            InterestTagEditor(
                                label: "Mag ich",
                                text: $likes,
                                suggestions: preferenceSuggestions,
                                tagColor: .green
                            )
                            Divider().padding(.leading, 16)
                            InterestTagEditor(
                                label: "Mag nicht",
                                text: $dislikes,
                                suggestions: preferenceSuggestions,
                                tagColor: .red
                            )
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    }

                    // Sozialstil
                    formSection("Sozialstil") {
                        Picker("Sozialstil", selection: $socialStyle) {
                            Text("Nicht angegeben").tag("")
                            ForEach(socialStyleOptions, id: \.self) { option in
                                Text(option).tag(option)
                            }
                        }
                        .pickerStyle(.menu)
                        .tint(theme.accent)
                        .padding(.horizontal, 14)
                        .padding(.vertical, 11)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    }
                }
                .padding(.horizontal, 20)
                .padding(.top, 16)
                .padding(.bottom, 48)
            }
            .background(theme.backgroundPrimary.ignoresSafeArea())
            .navigationTitle("Profil bearbeiten")
            .navigationBarTitleDisplayMode(.inline)
            .themedNavBar()
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button("Abbrechen") { dismiss() }
                        .foregroundStyle(theme.contentSecondary)
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Button("Speichern") { save() }
                        .font(.system(size: 15, weight: .semibold))
                        .foregroundStyle(theme.accent)
                }
                ToolbarItem(placement: .bottomBar) {
                    Button {
                        showingContactPicker = true
                    } label: {
                        Label("Vom Kontakt übernehmen", systemImage: "person.crop.circle")
                            .font(.system(size: 14))
                    }
                    .foregroundStyle(theme.accent)
                }
            }
        }
        .overlay(alignment: .center) {
            SingleContactPickerTrigger(isPresented: $showingContactPicker, onSelect: applyContact)
                .frame(width: 0, height: 0)
                .allowsHitTesting(false)
        }
        .onChange(of: photoPickerItem) { _, item in
            Task {
                guard let item else { return }
                if let data = try? await item.loadTransferable(type: Data.self),
                   let image = UIImage(data: data)?.resizedForAvatar() {
                    selectedPhoto = image
                }
            }
        }
    }

    // MARK: - Photo Section

    private var photoSection: some View {
        HStack {
            Spacer()
            ZStack(alignment: .bottomTrailing) {
                // Avatar
                Group {
                    if let photo = selectedPhoto {
                        Image(uiImage: photo)
                            .resizable()
                            .scaledToFill()
                    } else {
                        Text(previewInitials)
                            .font(.system(size: 32, weight: .medium, design: theme.displayDesign))
                            .foregroundStyle(theme.accent)
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .background(theme.accent.opacity(0.12))
                    }
                }
                .frame(width: 90, height: 90)
                .clipShape(Circle())

                // Foto-Picker Button
                PhotosPicker(selection: $photoPickerItem, matching: .images) {
                    Image(systemName: "camera.fill")
                        .font(.system(size: 12, weight: .semibold))
                        .foregroundStyle(.white)
                        .padding(7)
                        .background(theme.accent)
                        .clipShape(Circle())
                        .overlay(
                            Circle().stroke(theme.backgroundPrimary, lineWidth: 2)
                        )
                }
                .offset(x: 4, y: 4)
            }
            Spacer()
        }
        .padding(.top, 8)
    }

    private var previewInitials: 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: - Gender Picker

    private let genderOptions = ["Männlich", "Weiblich", "Divers"]

    private var genderPickerRow: some View {
        HStack(spacing: 12) {
            Text("Geschlecht")
                .font(.system(size: 15))
                .foregroundStyle(theme.contentTertiary)
                .frame(width: 80, alignment: .leading)
            Picker("Geschlecht", selection: $gender) {
                Text("Nicht angegeben").tag("")
                ForEach(genderOptions, id: \.self) { option in
                    Text(option).tag(option)
                }
            }
            .pickerStyle(.menu)
            .tint(theme.accent)
            .frame(maxWidth: .infinity, alignment: .leading)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

    // MARK: - Contact Import

    private func applyContact(_ contact: CNContact) {
        let imported = ContactImport.from(contact)
        if !imported.name.isEmpty { name = imported.name }
        if !imported.occupation.isEmpty { occupation = imported.occupation }
        if !imported.location.isEmpty { location = imported.location }
        if let bday = imported.birthday {
            birthday = bday
            hasBirthday = true
        }
        if let data = imported.photoData {
            selectedPhoto = UIImage(data: data)
        }
    }

    // MARK: - Suggestion Pool

    private var preferenceSuggestions: [String] {
        InterestTagHelper.allSuggestions(
            from: allPeople,
            likes: profileStore.likes,
            dislikes: profileStore.dislikes
        )
    }

    // MARK: - Helpers

    @ViewBuilder
    private func formSection<Content: View>(_ label: String, @ViewBuilder content: () -> Content) -> some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(label.uppercased())
                .font(.system(size: 11, weight: .semibold))
                .tracking(0.8)
                .foregroundStyle(theme.contentTertiary)
            content()
        }
    }

    @ViewBuilder
    private func inlineField(_ label: String, text: Binding<String>) -> some View {
        HStack(spacing: 12) {
            Text(label)
                .font(.system(size: 15))
                .foregroundStyle(theme.contentTertiary)
                .frame(width: 80, alignment: .leading)
            TextField(label, text: text)
                .font(.system(size: 15))
                .foregroundStyle(theme.contentPrimary)
                .tint(theme.accent)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

    private func save() {
        profileStore.update(
            name: name.trimmingCharacters(in: .whitespaces),
            birthday: hasBirthday ? birthday : nil,
            gender: gender,
            occupation: occupation.trimmingCharacters(in: .whitespaces),
            location: location.trimmingCharacters(in: .whitespaces),
            likes: likes.trimmingCharacters(in: .whitespaces),
            dislikes: dislikes.trimmingCharacters(in: .whitespaces),
            socialStyle: socialStyle
        )
        profileStore.savePhoto(selectedPhoto)
        dismiss()
    }
}
