import SwiftUI

struct SettingsView: View {
    @ObservedObject var viewModel: LoginViewModel
    @EnvironmentObject private var themeManager: ThemeManager
    @AppStorage("messengerModeEnabled") private var isMessengerModeEnabled: Bool = false
    @State private var isThemeExpanded = false
    @State private var isSecurityActive = false
    @State private var messengerProfile: ProfileDataPayload?
    @State private var isMessengerProfileLoading = false
    @State private var messengerProfileError: String?
    private let themeOptions = ThemeOption.ordered
    private let profileService = ProfileService()
    private let messengerAvatarSize: CGFloat = 96

    private var selectedThemeOption: ThemeOption {
        ThemeOption.option(for: themeManager.theme)
    }

    var body: some View {
        Form {
            if shouldShowLegacySupportBanner {
                LegacySupportBanner()
                    .listRowInsets(EdgeInsets(top: 12, leading: 0, bottom: 4, trailing: 0))
                    .listRowBackground(Color.clear)
            }
            
            if isMessengerModeEnabled {
                messengerProfileHeaderSection
            }

            // MARK: - Профиль
            Section(header: Text(NSLocalizedString("Профиль", comment: ""))) {
//                NavigationLink(destination: EditProfileView()) {
//                    Label("Мой профиль", systemImage: "person.crop.circle")
//                }
                
                NavigationLink(destination: EditProfileView()) {
                    Label(NSLocalizedString("Редактировать профиль", comment: ""), systemImage: "person.crop.circle")
                }
                
                NavigationLink(destination: BlockedUsersView()) {
                    Label(NSLocalizedString("Чёрный список", comment: ""), systemImage: "hand.raised.fill")
                }
            }

            // MARK: - Безопасность
            Section(header: Text(NSLocalizedString("Безопасность", comment: ""))) {
                NavigationLink(destination: EditPrivacyView()) {
                    Label(NSLocalizedString("Конфиденциальность", comment: ""), systemImage: "lock.fill")
                }

                NavigationLink(destination: ChangePasswordView()) {
                    Label(NSLocalizedString("Сменить пароль", comment: ""), systemImage: "key")
                }
                NavigationLink(destination: ActiveSessionsView()) {
                    Label(NSLocalizedString("Активные сессии", comment: ""), systemImage: "iphone")
                }
                NavigationLink(isActive: $isSecurityActive) {
                    SecuritySettingsView(viewModel: viewModel)
                } label: {
                    Label(NSLocalizedString("Безопасность", comment: ""), systemImage: "lock.shield")
                }
            }

            // MARK: - Приложение
            Section(header: Text("Приложение")) {
                Button(action: openLanguageSettings) {
                    Label("Язык", systemImage: "globe")
                }

                DisclosureGroup(isExpanded: $isThemeExpanded) {
                    VStack(alignment: .leading, spacing: 12) {
                        ForEach(Array(themeOptions.enumerated()), id: \.element.id) { index, option in
                            themeRow(for: option)
                            if index < themeOptions.count - 1 {
                                Divider()
                            }
                        }
                    }
                    .padding(.vertical, 4)
                } label: {
                    Label("Темы", systemImage: "moon.fill")
                }

                NavigationLink(destination: DataSettingsView(currentUserId: viewModel.userId)) {
                    Label("Данные", systemImage: "externaldrive")
                }

                NavigationLink(destination: OtherSettingsView()) {
                    Label("Другое", systemImage: "ellipsis.circle")
                }
            }

            // MARK: - Уведомления
            Section(header: Text("Уведомления")) {
                NavigationLink(destination: Text("Заглушка: Push-уведомления")) {
                    Label("Push-уведомления", systemImage: "bell")
                }
            }

            // MARK: - Поддержка
            Section(header: Text("Поддержка")) {
                NavigationLink(destination: FAQView()) {
                    Label("Частые вопросы", systemImage: "questionmark.circle")
                }
                NavigationLink(destination: FeedbackView()) {
                    Label("Обратная связь", systemImage: "paperplane")
                }
            }

            // MARK: - О приложении
//            Section(header: Text("О приложении")) {
//                VStack(alignment: .leading, spacing: 6) {
//                    Text(AppInfo.text_1)
//                    Text(AppInfo.text_2)
//                    Text(AppInfo.text_3)
//                }
//                .font(.footnote)
//                .foregroundColor(.gray)
//                .padding(.vertical, 4)
//            }
            
            Section(header: Text(NSLocalizedString("О приложении", comment: ""))) {
                VStack(alignment: .leading, spacing: 6) {
                    Text(
                        "\(NSLocalizedString("Версия:", comment: "")) \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "")")
                    Text(
                        "\(NSLocalizedString("Сборка:", comment: "")) \(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "")")
                    Text("© 2025 Yobble Org. \(NSLocalizedString("Все права защищены.", comment: ""))")
                }
                .font(.footnote)
                .foregroundColor(.gray)
                .padding(.vertical, 4)
            }

            // MARK: - Выход
            Section {
                Button(action: {
                    viewModel.logoutCurrentUser()
                }) {
                    HStack {
                        Image(systemName: "arrow.backward.square")
                        Text("Выйти из аккаунта")
                    }
                    .foregroundColor(.red)
                }
            }
        }
        .navigationTitle("Настройки")
        .onAppear {
            loadMessengerProfileIfNeeded()
        }
        .onChange(of: isMessengerModeEnabled) { newValue in
            if newValue {
                loadMessengerProfileIfNeeded(force: true)
            }
        }
    }

    @ViewBuilder
    private var messengerProfileHeaderSection: some View {
        if messengerProfile != nil || isMessengerProfileLoading || messengerProfileError != nil {
            Section {
                if let profile = messengerProfile {
                    ProfileHeaderCardView(
                        avatar: messengerAvatar(for: profile),
                        displayName: messengerDisplayName(for: profile),
                        presenceStatus: nil,
                        statusTags: [],
                        isOfficial: self.messengerProfile?.isVerified ?? false
                    )
                    .listRowInsets(EdgeInsets(top: 16, leading: 0, bottom: 8, trailing: 0))
                    .listRowBackground(Color.clear)
                } else if isMessengerProfileLoading {
                    HStack {
                        Spacer()
                        ProgressView()
                        Spacer()
                    }
                    .padding(.vertical, 24)
                    .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
                    .listRowBackground(Color.clear)
                } else if let error = messengerProfileError {
                    VStack(spacing: 8) {
                        Text(error)
                            .font(.footnote)
                            .multilineTextAlignment(.center)
                        Button(NSLocalizedString("Повторить", comment: "Messenger profile header retry")) {
                            loadMessengerProfileIfNeeded(force: true)
                        }
                        .buttonStyle(.borderedProminent)
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 16)
                    .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
                    .listRowBackground(Color.clear)
                }
            }
        }
    }

    private func openLanguageSettings() {
        guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
        UIApplication.shared.open(url)
    }

    private func loadMessengerProfileIfNeeded(force: Bool = false) {
        guard isMessengerModeEnabled else { return }
        if isMessengerProfileLoading { return }
        if !force, messengerProfile != nil { return }

        isMessengerProfileLoading = true
        messengerProfileError = nil

        Task {
            do {
                let profile = try await profileService.fetchMyProfile()
                await MainActor.run {
                    messengerProfile = profile
                    isMessengerProfileLoading = false
                }
            } catch {
                await MainActor.run {
                    messengerProfileError = error.localizedDescription
                    isMessengerProfileLoading = false
                }
            }
        }
    }

    @ViewBuilder
    private func messengerAvatar(for profile: ProfileDataPayload) -> some View {
        if let fileId = profile.avatars?.current?.fileId,
           let url = URL(string: "\(AppConfig.API_SERVER)/v1/storage/download/avatar/\(profile.userId.uuidString)?file_id=\(fileId)") {
            CachedAvatarView(url: url, fileId: fileId, userId: profile.userId.uuidString) {
                messengerAvatarPlaceholder(for: profile)
            }
            .aspectRatio(contentMode: .fill)
            .frame(width: messengerAvatarSize, height: messengerAvatarSize)
            .clipShape(Circle())
        } else {
            messengerAvatarPlaceholder(for: profile)
        }
    }

    private func messengerAvatarPlaceholder(for profile: ProfileDataPayload) -> some View {
        Circle()
            .fill(Color.accentColor.opacity(0.15))
            .frame(width: messengerAvatarSize, height: messengerAvatarSize)
            .overlay(
                Text(messengerInitials(for: profile))
                    .font(.system(size: messengerAvatarSize * 0.45, weight: .semibold))
                    .foregroundColor(Color.accentColor)
            )
    }

    private func messengerInitials(for profile: ProfileDataPayload) -> String {
        if let name = profile.fullName?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty {
            let components = name.split(separator: " ")
            let initials = components.prefix(2).compactMap { $0.first }
            if !initials.isEmpty {
                return initials.map { String($0) }.joined().uppercased()
            }
        }
        return String(profile.login.prefix(1)).uppercased()
    }

    private func messengerDisplayName(for profile: ProfileDataPayload) -> String {
        if let name = profile.fullName?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty {
            return name
        }
        return "@\(profile.login)"
    }

//    private func messengerStatusTags(for profile: ProfileDataPayload) -> [ProfileHeaderCardView.StatusTag] {
//        var tags: [ProfileHeaderCardView.StatusTag] = []
//        tags.append(
//            ProfileHeaderCardView.StatusTag(
//                icon: "at",
//                text: "@\(profile.login)",
//                background: Color.white.opacity(0.18),
//                tint: .white
//            )
//        )
//
//        if let createdAt = profile.createdAt {
//            let formatted = SettingsView.membershipFormatter.string(from: createdAt)
//            tags.append(
//                ProfileHeaderCardView.StatusTag(
//                    icon: "calendar",
//                    text: String(
//                        format: NSLocalizedString("С %@ на Yobble", comment: "Messenger profile membership"),
//                        formatted
//                    ),
//                    background: Color.white.opacity(0.12),
//                    tint: .white
//                )
//            )
//        }
//
//        return tags
//    }

    private func themeRow(for option: ThemeOption) -> some View {
        let isSelected = option == selectedThemeOption

        return Button(action: {
            selectTheme(option)
        }) {
            HStack(spacing: 12) {
                Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
                    .foregroundColor(isSelected ? .accentColor : .secondary)
                VStack(alignment: .leading, spacing: 2) {
                    Text(option.title)
                        .foregroundColor(.primary)
                    if let note = option.note {
                        Text(note)
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                }
                Spacer()
            }
            .contentShape(Rectangle())
        }
        .disabled(!option.isEnabled)
        .opacity(option.isEnabled ? 1.0 : 0.5)
        .buttonStyle(.plain)
    }

    private func selectTheme(_ option: ThemeOption) {
        guard let mappedTheme = option.mappedTheme else { return }
        themeManager.setTheme(mappedTheme)
    }

    private var shouldShowLegacySupportBanner: Bool {
#if os(iOS)
        let requiredVersion = OperatingSystemVersion(majorVersion: 16, minorVersion: 0, patchVersion: 0)
        return !ProcessInfo.processInfo.isOperatingSystemAtLeast(requiredVersion)
#else
        return false
#endif
    }

    private static let membershipFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        formatter.timeStyle = .none
        return formatter
    }()
}

private struct LegacySupportBanner: View {
    var body: some View {
        HStack(alignment: .top, spacing: 12) {
            Image(systemName: "exclamationmark.triangle.fill")
                .font(.system(size: 24, weight: .semibold))
                .foregroundColor(.yellow)

            VStack(alignment: .leading, spacing: 4) {
                Text("Экспериментальная поддержка iOS 15")
                    .font(.headline)
                Text("Поддержка iOS 15 работает в экспериментальном режиме. Для лучшей совместимости требуется iOS 16+.")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }

            Spacer(minLength: 0)
        }
        .padding(16)
        .background(
            RoundedRectangle(cornerRadius: 14, style: .continuous)
                .fill(Color.yellow.opacity(0.15))
        )
        .overlay(
            RoundedRectangle(cornerRadius: 14, style: .continuous)
                .stroke(Color.yellow.opacity(0.4), lineWidth: 1)
        )
    }
}
