import UIKit
import SwiftUI

/// Screen 3: Group name + avatar + selected members list + Create button — Telegram parity.
/// Custom glass header: back chevron + "New Group" + glass "Create" button.
/// Horizontal avatar + name field in glass card (matching Telegram layout).
final class GroupSetupViewController: UIViewController {

    // MARK: - Callbacks

    var onOpenChat: ((ChatRoute) -> Void)?

    // MARK: - Data

    private let selectedContacts: [Dialog]
    private var groupTitle = ""
    private var groupDescription = ""
    private var selectedPhoto: UIImage?
    private var isCreating = false

    // MARK: - Layout Constants

    private enum Layout {
        static let avatarSize: CGFloat = 64
        static let maxTitleLength = 80
        static let maxDescriptionLength = 255
        static let sideInset: CGFloat = 16
        static let headerBarHeight: CGFloat = 44
    }

    // MARK: - Header Views

    private let backButton = ComposeGlassBackButton()
    private let headerTitleLabel = UILabel()
    private let createButton = ComposeGlassActionButton()
    private let loadingIndicator = UIActivityIndicatorView(style: .medium)

    // MARK: - Content Views

    private let scrollView = UIScrollView()
    private let contentView = UIView()
    private let infoCard = TelegramGlassUIView(frame: .zero)
    private let avatarContainer = UIView()
    private let avatarImageView = UIImageView()
    private let cameraIcon = UIImageView()
    private let nameTextField = UITextField()
    private let descriptionTextField = UITextField()
    private let descriptionSeparator = UIView()
    private let membersHeaderLabel = UILabel()
    private var memberViews: [UIView] = []

    // MARK: - Init

    init(selectedContacts: [Dialog]) {
        self.selectedContacts = selectedContacts
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) { fatalError() }

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor { $0.userInterfaceStyle == .dark ? .black : .white }
        hidesBottomBarWhenPushed = true

        setupCustomHeader()
        setupScrollView()
        setupInfoCard()
        setupMembersSection()

        nameTextField.becomeFirstResponder()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        layoutCustomHeader()
    }

    // MARK: - Custom Glass Header

    private func setupCustomHeader() {
        backButton.addTarget(self, action: #selector(backTapped), for: .touchUpInside)
        backButton.layer.zPosition = 55
        view.addSubview(backButton)

        headerTitleLabel.text = "New Group"
        headerTitleLabel.font = .systemFont(ofSize: 17, weight: .semibold)
        headerTitleLabel.textColor = UIColor(RosettaColors.Adaptive.text)
        headerTitleLabel.textAlignment = .center
        headerTitleLabel.layer.zPosition = 55
        view.addSubview(headerTitleLabel)

        createButton.title = "Create"
        createButton.isEnabled = false
        createButton.addTarget(self, action: #selector(createTapped), for: .touchUpInside)
        createButton.layer.zPosition = 55
        view.addSubview(createButton)
    }

    private func layoutCustomHeader() {
        let safeTop = view.safeAreaInsets.top
        let centerY = safeTop + Layout.headerBarHeight * 0.5

        let backSize = backButton.intrinsicContentSize
        backButton.frame = CGRect(
            x: 8,
            y: centerY - backSize.height * 0.5,
            width: backSize.width,
            height: backSize.height
        )

        let createSize = createButton.intrinsicContentSize
        createButton.frame = CGRect(
            x: view.bounds.width - 8 - createSize.width,
            y: centerY - createSize.height * 0.5,
            width: createSize.width,
            height: createSize.height
        )

        let titleWidth: CGFloat = 200
        headerTitleLabel.frame = CGRect(
            x: (view.bounds.width - titleWidth) / 2,
            y: centerY - 11,
            width: titleWidth,
            height: 22
        )
    }

    // MARK: - Scroll View

    private func setupScrollView() {
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.keyboardDismissMode = .onDrag
        view.addSubview(scrollView)

        contentView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.addSubview(contentView)

        let topOffset = Layout.headerBarHeight + 16

        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: topOffset),
            scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),

            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
        ])

        view.bringSubviewToFront(backButton)
        view.bringSubviewToFront(headerTitleLabel)
        view.bringSubviewToFront(createButton)
    }

    // MARK: - Info Card (Avatar + Name + Description)

    private func setupInfoCard() {
        // Glass card background
        infoCard.translatesAutoresizingMaskIntoConstraints = false
        infoCard.isUserInteractionEnabled = false
        infoCard.fixedCornerRadius = 20
        contentView.addSubview(infoCard)

        // Avatar circle (tappable for photo picker)
        avatarContainer.translatesAutoresizingMaskIntoConstraints = false
        avatarContainer.backgroundColor = UIColor(RosettaColors.figmaBlue).withAlphaComponent(0.2)
        avatarContainer.layer.cornerRadius = Layout.avatarSize / 2
        avatarContainer.clipsToBounds = true
        let avatarTap = UITapGestureRecognizer(target: self, action: #selector(avatarTapped))
        avatarContainer.addGestureRecognizer(avatarTap)
        contentView.addSubview(avatarContainer)

        // Avatar image (shown after photo selection)
        avatarImageView.contentMode = .scaleAspectFill
        avatarImageView.clipsToBounds = true
        avatarImageView.layer.cornerRadius = Layout.avatarSize / 2
        avatarImageView.translatesAutoresizingMaskIntoConstraints = false
        avatarImageView.isHidden = true
        avatarContainer.addSubview(avatarImageView)

        let config = UIImage.SymbolConfiguration(pointSize: 24, weight: .medium)
        cameraIcon.image = UIImage(systemName: "camera.fill", withConfiguration: config)
        cameraIcon.tintColor = UIColor(RosettaColors.figmaBlue)
        cameraIcon.contentMode = .scaleAspectFit
        cameraIcon.translatesAutoresizingMaskIntoConstraints = false
        avatarContainer.addSubview(cameraIcon)

        // Name text field
        nameTextField.translatesAutoresizingMaskIntoConstraints = false
        nameTextField.placeholder = "Group Name"
        nameTextField.font = .systemFont(ofSize: 17)
        nameTextField.textColor = UIColor(RosettaColors.Adaptive.text)
        nameTextField.tintColor = UIColor(RosettaColors.figmaBlue)
        nameTextField.returnKeyType = .next
        nameTextField.delegate = self
        nameTextField.addTarget(self, action: #selector(nameChanged), for: .editingChanged)

        let nameAttrs: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor(RosettaColors.Adaptive.textSecondary),
            .font: UIFont.systemFont(ofSize: 17)
        ]
        nameTextField.attributedPlaceholder = NSAttributedString(string: "Group Name", attributes: nameAttrs)
        contentView.addSubview(nameTextField)

        // Separator between name and description
        descriptionSeparator.translatesAutoresizingMaskIntoConstraints = false
        descriptionSeparator.backgroundColor = UIColor { traits in
            traits.userInterfaceStyle == .dark
                ? UIColor.white.withAlphaComponent(0.08)
                : UIColor.black.withAlphaComponent(0.08)
        }
        contentView.addSubview(descriptionSeparator)

        // Description text field
        descriptionTextField.translatesAutoresizingMaskIntoConstraints = false
        descriptionTextField.placeholder = "Description"
        descriptionTextField.font = .systemFont(ofSize: 17)
        descriptionTextField.textColor = UIColor(RosettaColors.Adaptive.text)
        descriptionTextField.tintColor = UIColor(RosettaColors.figmaBlue)
        descriptionTextField.returnKeyType = .done
        descriptionTextField.delegate = self
        descriptionTextField.addTarget(self, action: #selector(descriptionChanged), for: .editingChanged)

        let descAttrs: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor(RosettaColors.Adaptive.textSecondary),
            .font: UIFont.systemFont(ofSize: 17)
        ]
        descriptionTextField.attributedPlaceholder = NSAttributedString(string: "Description", attributes: descAttrs)
        contentView.addSubview(descriptionTextField)

        // Card height: avatar area (name row) + separator + description row
        let nameRowHeight: CGFloat = Layout.avatarSize + 24
        let descRowHeight: CGFloat = 44
        let cardHeight: CGFloat = nameRowHeight + descRowHeight

        NSLayoutConstraint.activate([
            infoCard.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
            infoCard.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Layout.sideInset),
            infoCard.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -Layout.sideInset),
            infoCard.heightAnchor.constraint(equalToConstant: cardHeight),

            avatarContainer.leadingAnchor.constraint(equalTo: infoCard.leadingAnchor, constant: 12),
            avatarContainer.topAnchor.constraint(equalTo: infoCard.topAnchor, constant: 12),
            avatarContainer.widthAnchor.constraint(equalToConstant: Layout.avatarSize),
            avatarContainer.heightAnchor.constraint(equalToConstant: Layout.avatarSize),

            avatarImageView.topAnchor.constraint(equalTo: avatarContainer.topAnchor),
            avatarImageView.leadingAnchor.constraint(equalTo: avatarContainer.leadingAnchor),
            avatarImageView.trailingAnchor.constraint(equalTo: avatarContainer.trailingAnchor),
            avatarImageView.bottomAnchor.constraint(equalTo: avatarContainer.bottomAnchor),

            cameraIcon.centerXAnchor.constraint(equalTo: avatarContainer.centerXAnchor),
            cameraIcon.centerYAnchor.constraint(equalTo: avatarContainer.centerYAnchor),

            nameTextField.leadingAnchor.constraint(equalTo: avatarContainer.trailingAnchor, constant: 12),
            nameTextField.trailingAnchor.constraint(equalTo: infoCard.trailingAnchor, constant: -12),
            nameTextField.centerYAnchor.constraint(equalTo: avatarContainer.centerYAnchor),

            descriptionSeparator.topAnchor.constraint(equalTo: infoCard.topAnchor, constant: nameRowHeight),
            descriptionSeparator.leadingAnchor.constraint(equalTo: infoCard.leadingAnchor, constant: 12),
            descriptionSeparator.trailingAnchor.constraint(equalTo: infoCard.trailingAnchor, constant: -12),
            descriptionSeparator.heightAnchor.constraint(equalToConstant: 0.5),

            descriptionTextField.topAnchor.constraint(equalTo: descriptionSeparator.bottomAnchor),
            descriptionTextField.leadingAnchor.constraint(equalTo: infoCard.leadingAnchor, constant: 12),
            descriptionTextField.trailingAnchor.constraint(equalTo: infoCard.trailingAnchor, constant: -12),
            descriptionTextField.bottomAnchor.constraint(equalTo: infoCard.bottomAnchor),
        ])
    }

    // MARK: - Members Section

    private func setupMembersSection() {
        guard !selectedContacts.isEmpty else {
            contentView.bottomAnchor.constraint(equalTo: infoCard.bottomAnchor, constant: 20).isActive = true
            return
        }

        membersHeaderLabel.translatesAutoresizingMaskIntoConstraints = false
        membersHeaderLabel.text = "\(selectedContacts.count) MEMBERS"
        membersHeaderLabel.font = .systemFont(ofSize: 13, weight: .regular)
        membersHeaderLabel.textColor = UIColor(RosettaColors.Adaptive.textSecondary)
        contentView.addSubview(membersHeaderLabel)

        NSLayoutConstraint.activate([
            membersHeaderLabel.topAnchor.constraint(equalTo: infoCard.bottomAnchor, constant: 24),
            membersHeaderLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Layout.sideInset),
        ])

        var previousAnchor = membersHeaderLabel.bottomAnchor

        for (index, dialog) in selectedContacts.enumerated() {
            let row = createMemberRow(dialog: dialog, isLast: index == selectedContacts.count - 1)
            row.translatesAutoresizingMaskIntoConstraints = false
            contentView.addSubview(row)
            memberViews.append(row)

            NSLayoutConstraint.activate([
                row.topAnchor.constraint(equalTo: previousAnchor, constant: index == 0 ? 8 : 0),
                row.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
                row.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
                row.heightAnchor.constraint(equalToConstant: 52),
            ])

            previousAnchor = row.bottomAnchor
        }

        contentView.bottomAnchor.constraint(equalTo: previousAnchor, constant: 20).isActive = true
    }

    private func createMemberRow(dialog: Dialog, isLast: Bool) -> UIView {
        let row = UIView()

        let avatarSize: CGFloat = 36
        let avatarBg = UIView()
        avatarBg.clipsToBounds = true
        avatarBg.layer.cornerRadius = avatarSize / 2
        avatarBg.translatesAutoresizingMaskIntoConstraints = false
        row.addSubview(avatarBg)

        let initialsLabel = UILabel()
        initialsLabel.textAlignment = .center
        initialsLabel.font = .systemFont(ofSize: avatarSize * 0.38, weight: .bold)
        initialsLabel.translatesAutoresizingMaskIntoConstraints = false
        row.addSubview(initialsLabel)

        let colorPair = RosettaColors.avatarColors[dialog.avatarColorIndex % RosettaColors.avatarColors.count]
        let tintUIColor = UIColor(colorPair.tint)
        let textUIColor = UIColor(colorPair.text)

        let image = AvatarRepository.shared.loadAvatar(publicKey: dialog.opponentKey)
        let avatarImageView = UIImageView()
        avatarImageView.contentMode = .scaleAspectFill
        avatarImageView.clipsToBounds = true
        avatarImageView.layer.cornerRadius = avatarSize / 2
        avatarImageView.translatesAutoresizingMaskIntoConstraints = false
        row.addSubview(avatarImageView)

        if let image {
            avatarImageView.image = image
            avatarBg.isHidden = true
            initialsLabel.isHidden = true
        } else {
            avatarImageView.isHidden = true
            let mantineDark = UIColor(red: 0x1A/255.0, green: 0x1B/255.0, blue: 0x1E/255.0, alpha: 1)
            avatarBg.backgroundColor = UIColor { traits in
                let dark = traits.userInterfaceStyle == .dark
                let base: UIColor = dark ? mantineDark : .white
                return base.blended(with: tintUIColor, alpha: dark ? 0.15 : 0.10)
            }
            initialsLabel.text = dialog.initials
            initialsLabel.textColor = UIColor { traits in
                traits.userInterfaceStyle == .dark ? textUIColor : tintUIColor
            }
        }

        let nameLabel = UILabel()
        nameLabel.text = dialog.opponentTitle
        nameLabel.font = .systemFont(ofSize: 16)
        nameLabel.textColor = UIColor(RosettaColors.Adaptive.text)
        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        row.addSubview(nameLabel)

        if !isLast {
            let separator = UIView()
            separator.backgroundColor = UIColor { traits in
                traits.userInterfaceStyle == .dark
                    ? UIColor.white.withAlphaComponent(0.08)
                    : UIColor.black.withAlphaComponent(0.08)
            }
            separator.translatesAutoresizingMaskIntoConstraints = false
            row.addSubview(separator)
            NSLayoutConstraint.activate([
                separator.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 64),
                separator.trailingAnchor.constraint(equalTo: row.trailingAnchor),
                separator.bottomAnchor.constraint(equalTo: row.bottomAnchor),
                separator.heightAnchor.constraint(equalToConstant: 0.5),
            ])
        }

        NSLayoutConstraint.activate([
            avatarBg.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: Layout.sideInset),
            avatarBg.centerYAnchor.constraint(equalTo: row.centerYAnchor),
            avatarBg.widthAnchor.constraint(equalToConstant: avatarSize),
            avatarBg.heightAnchor.constraint(equalToConstant: avatarSize),

            initialsLabel.centerXAnchor.constraint(equalTo: avatarBg.centerXAnchor),
            initialsLabel.centerYAnchor.constraint(equalTo: avatarBg.centerYAnchor),

            avatarImageView.leadingAnchor.constraint(equalTo: avatarBg.leadingAnchor),
            avatarImageView.topAnchor.constraint(equalTo: avatarBg.topAnchor),
            avatarImageView.widthAnchor.constraint(equalToConstant: avatarSize),
            avatarImageView.heightAnchor.constraint(equalToConstant: avatarSize),

            nameLabel.leadingAnchor.constraint(equalTo: avatarBg.trailingAnchor, constant: 12),
            nameLabel.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -Layout.sideInset),
            nameLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
        ])

        return row
    }

    // MARK: - Actions

    @objc private func backTapped() {
        navigationController?.popViewController(animated: true)
    }

    @objc private func nameChanged() {
        var text = nameTextField.text ?? ""
        if text.count > Layout.maxTitleLength {
            text = String(text.prefix(Layout.maxTitleLength))
            nameTextField.text = text
        }
        groupTitle = text
        createButton.isEnabled = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !isCreating
    }

    @objc private func descriptionChanged() {
        var text = descriptionTextField.text ?? ""
        if text.count > Layout.maxDescriptionLength {
            text = String(text.prefix(Layout.maxDescriptionLength))
            descriptionTextField.text = text
        }
        groupDescription = text
    }

    @objc private func avatarTapped() {
        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.delegate = self
        picker.allowsEditing = true
        present(picker, animated: true)
    }

    @objc private func createTapped() {
        guard !isCreating else { return }
        let trimmedTitle = groupTitle.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmedTitle.isEmpty else { return }

        isCreating = true
        createButton.isEnabled = false
        nameTextField.isEnabled = false
        descriptionTextField.isEnabled = false

        // Replace create button with loading indicator
        loadingIndicator.color = UIColor(RosettaColors.Adaptive.text)
        loadingIndicator.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(loadingIndicator)
        loadingIndicator.frame = createButton.frame
        loadingIndicator.startAnimating()
        createButton.isHidden = true

        let contactKeys = selectedContacts.map(\.opponentKey)
        let trimmedDescription = groupDescription.trimmingCharacters(in: .whitespacesAndNewlines)
        let photo = selectedPhoto

        Task { @MainActor in
            do {
                let route = try await GroupService.shared.createGroupAndSendInvites(
                    title: trimmedTitle,
                    description: trimmedDescription,
                    contactKeys: contactKeys
                )

                // Save selected photo as group avatar locally
                if let photo {
                    AvatarRepository.shared.saveAvatar(publicKey: route.publicKey, image: photo)
                }

                guard let navController = navigationController else { return }
                if let rootVC = navController.viewControllers.first {
                    navController.setViewControllers([rootVC], animated: false)
                    DispatchQueue.main.async { self.onOpenChat?(route) }
                }
            } catch {
                isCreating = false
                createButton.isEnabled = true
                createButton.isHidden = false
                nameTextField.isEnabled = true
                descriptionTextField.isEnabled = true
                loadingIndicator.removeFromSuperview()

                let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel))
                present(alert, animated: true)
            }
        }
    }
}

// MARK: - UITextFieldDelegate

extension GroupSetupViewController: UITextFieldDelegate {

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField === nameTextField {
            descriptionTextField.becomeFirstResponder()
        } else {
            textField.resignFirstResponder()
        }
        return true
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentText = textField.text ?? ""
        guard let range = Range(range, in: currentText) else { return true }
        let newText = currentText.replacingCharacters(in: range, with: string)
        let maxLength = textField === nameTextField ? Layout.maxTitleLength : Layout.maxDescriptionLength
        return newText.count <= maxLength
    }
}

// MARK: - UIImagePickerControllerDelegate

extension GroupSetupViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        picker.dismiss(animated: true)
        guard let image = info[.editedImage] as? UIImage ?? info[.originalImage] as? UIImage else { return }
        selectedPhoto = image
        avatarImageView.image = image
        avatarImageView.isHidden = false
        cameraIcon.isHidden = true
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}
