import SwiftUI
import PhotosUI

struct EditProfilePage: View {
    @StateObject private var viewModel = ProfileViewModel()
    @State private var nickname: String = ""
    @State private var learningIdentity: String = ""
    @State private var learningDirection: String = ""
    @State private var bio: String = ""
    @State private var currentGoal: String = ""
    @State private var saved = false
    @State private var isSaving = false
    @State private var saveError: String?
    @State private var avatarUrl: String?
    @State private var isUploadingAvatar = false
    @State private var selectedPhotoItem: PhotosPickerItem?
    @State private var showPhotoPicker = false

    var body: some View {
        ZStack {
            Color.zxBg0.ignoresSafeArea()
            ScrollView {
                VStack(spacing: 16) {
                    // MARK: - Avatar
                    VStack(spacing: 12) {
                        ZStack {
                            if let url = avatarUrl, let imageUrl = URL(string: url) {
                                AsyncImage(url: imageUrl) { phase in
                                    switch phase {
                                    case .success(let image):
                                        image.resizable().scaledToFill()
                                    case .failure:
                                        defaultAvatar
                                    default:
                                        defaultAvatar
                                    }
                                }
                                .frame(width: 88, height: 88)
                                .clipShape(Circle())
                            } else {
                                defaultAvatar
                            }

                            if isUploadingAvatar {
                                Circle().fill(Color.black.opacity(0.5)).frame(width: 88, height: 88)
                                ProgressView().tint(.white)
                            }
                        }

                        Button {
                            showPhotoPicker = true
                        } label: {
                            Text(isUploadingAvatar ? "上传中..." : "更换头像")
                                .font(.system(size: 13, weight: .medium))
                                .foregroundColor(Color.zxPrimary)
                        }
                        .disabled(isUploadingAvatar)
                    }
                    .padding(.top, 8)

                    sectionHeader("基本信息")
                    VStack(spacing: 0) {
                        ZXEditField(title: "昵称", text: $nickname, placeholder: "你的昵称")
                        ZXSettingDivider()
                        ZXEditField(title: "学习身份", text: $learningIdentity, placeholder: "如：考研学生、软件工程师")
                    }
                    .background(Color.zxFill004).clipShape(RoundedRectangle(cornerRadius: 20))
                    .overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.zxBorder006, lineWidth: 1))

                    sectionHeader("学习档案")
                    VStack(spacing: 0) {
                        ZXEditField(title: "学习方向", text: $learningDirection, placeholder: "如：机器学习、公考申论")
                        ZXSettingDivider()
                        ZXEditField(title: "当前目标", text: $currentGoal, placeholder: "如：通过 6 月 CFA 一级")
                    }
                    .background(Color.zxFill004).clipShape(RoundedRectangle(cornerRadius: 20))
                    .overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.zxBorder006, lineWidth: 1))

                    sectionHeader("个人简介")
                    VStack(spacing: 0) {
                        VStack(alignment: .leading, spacing: 8) {
                            Text("简介").font(.system(size: 12, weight: .semibold)).foregroundColor(Color.zxF035)
                            TextEditor(text: $bio)
                                .frame(minHeight: 100)
                                .scrollContentBackground(.hidden)
                                .padding(12)
                                .background(Color.zxFill003)
                                .clipShape(RoundedRectangle(cornerRadius: 14))
                                .overlay(RoundedRectangle(cornerRadius: 14).stroke(Color.zxBorder008, lineWidth: 1))
                                .tint(Color.zxPurple)
                        }.padding(.horizontal, 16).padding(.vertical, 14)
                    }
                    .background(Color.zxFill004).clipShape(RoundedRectangle(cornerRadius: 20))
                    .overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.zxBorder006, lineWidth: 1))

                    if let error = saveError {
                        Text(error).font(.system(size: 13)).foregroundColor(.red)
                            .padding(.horizontal, 16).padding(.vertical, 10)
                            .background(Color.red.opacity(0.1))
                            .clipShape(RoundedRectangle(cornerRadius: 10))
                    }

                    Button {
                        Task {
                            isSaving = true
                            saveError = nil
                            do {
                                _ = try await UserService.shared.updateProfile(UpdateProfileRequest(
                                    nickname: nickname.isEmpty ? nil : nickname, avatarUrl: avatarUrl
                                ))
                                _ = try await UserService.shared.updateProfileDetail(UpdateProfileDataRequest(
                                    learningIdentity: learningIdentity.isEmpty ? nil : learningIdentity,
                                    learningDirection: learningDirection.isEmpty ? nil : learningDirection,
                                    bio: bio.isEmpty ? nil : bio,
                                    currentGoal: currentGoal.isEmpty ? nil : currentGoal
                                ))
                                saved = true
                            } catch {
                                saveError = "保存失败: \(error.localizedDescription)"
                            }
                            isSaving = false
                        }
                    } label: {
                        HStack(spacing: 8) {
                            if isSaving { ProgressView().tint(.white) }
                            Text(saved ? "已保存" : "保存修改")
                                .font(.system(size: 14, weight: .bold))
                                .foregroundColor(.white)
                        }
                        .frame(maxWidth: .infinity)
                        .frame(height: 52)
                        .background {
                            if isSaving { Color.gray } else { ZXGradient.ctaPurple }
                        }
                        .clipShape(RoundedRectangle(cornerRadius: 16))
                    }
                    .disabled(isSaving)
                }
                .padding(.horizontal, 20).padding(.top, 8).padding(.bottom, 80)
            }
            .scrollIndicators(.hidden)
        }
        .navigationTitle("编辑资料")
        .navigationBarTitleDisplayMode(.inline)
        .animatedTabBarHide()
        .toolbarBackground(.hidden, for: .navigationBar)
        .photosPicker(isPresented: $showPhotoPicker, selection: $selectedPhotoItem, matching: .images)
        .onChange(of: selectedPhotoItem) { _, item in
            guard let item else { return }
            Task { await uploadAvatar(item) }
        }
        .task {
            await viewModel.loadProfile()
            nickname = viewModel.userProfile?.nickname ?? ""
            avatarUrl = viewModel.userProfile?.avatarUrl
            learningIdentity = viewModel.profileData?.learningIdentity ?? ""
            learningDirection = viewModel.profileData?.learningDirection ?? ""
            bio = viewModel.profileData?.bio ?? ""
            currentGoal = viewModel.profileData?.currentGoal ?? ""
        }
    }

    private var defaultAvatar: some View {
        ZStack {
            Circle().fill(Color.zxPurpleBG(0.2)).frame(width: 88, height: 88)
            Image(systemName: "person.crop.circle.fill")
                .font(.system(size: 40))
                .foregroundColor(Color.zxPurple)
        }
    }

    private func uploadAvatar(_ item: PhotosPickerItem) async {
        isUploadingAvatar = true
        defer { isUploadingAvatar = false; selectedPhotoItem = nil }

        guard let data = try? await item.loadTransferable(type: Data.self),
              let image = UIImage(data: data) else { return }

        // 裁剪为正方形
        let size = min(image.size.width, image.size.height)
        let rect = CGRect(
            x: (image.size.width - size) / 2,
            y: (image.size.height - size) / 2,
            width: size, height: size
        )
        guard let cropped = image.cgImage?.cropping(to: rect) else { return }
        let square = UIImage(cgImage: cropped)

        // 缩放到 256x256
        let resized = resizeImage(square, targetSize: CGSize(width: 256, height: 256))

        do {
            let fileId = try await FileUploadService.shared.uploadImage(resized, filename: "avatar.jpg")
            let downloadUrl = try await FileUploadService.shared.getDownloadUrl(fileId: fileId)
            avatarUrl = downloadUrl
            // 立刻更新头像到服务器
            _ = try await UserService.shared.updateProfile(UpdateProfileRequest(
                nickname: nickname.isEmpty ? nil : nickname,
                avatarUrl: downloadUrl
            ))
            ZXToastManager.shared.success("头像已更新")
        } catch {
            ZXToastManager.shared.error(error.localizedDescription)
        }
    }

    private func resizeImage(_ image: UIImage, targetSize: CGSize) -> UIImage {
        let renderer = UIGraphicsImageRenderer(size: targetSize)
        return renderer.image { _ in
            image.draw(in: CGRect(origin: .zero, size: targetSize))
        }
    }

    private func sectionHeader(_ text: String) -> some View {
        Text(text).font(.system(size: 12, weight: .semibold)).foregroundColor(Color.zxF035).tracking(0.5).padding(.top, 4)
    }
}

struct ZXEditField: View {
    let title: String
    @Binding var text: String
    let placeholder: String

    var body: some View {
        HStack(spacing: 12) {
            Text(title).font(.system(size: 14, weight: .semibold)).foregroundColor(Color.zxF0).frame(width: 72, alignment: .leading)
            TextField(placeholder, text: $text)
                .font(.system(size: 14))
                .tint(Color.zxPurple)
                .foregroundColor(Color.zxF0)
            Spacer()
        }
        .padding(.horizontal, 16).padding(.vertical, 14)
    }
}
