//
//  LNRoomInfoEditPanel.swift
//  Gami
//
//  Created by OneeChan on 2026/3/16.
//

import Foundation
import UIKit
import SnapKit


class LNRoomInfoEditPanel: LNPopupView {
    private let cover = LNImageUploadView()
    private let coverLabel = UILabel()
    
    private let nameLabel = UILabel()
    private let nameCountLabel = UILabel()
    private var curName: String = "" {
        didSet {
            if !curName.isEmpty {
                nameLabel.textColor = .text_1
                nameLabel.text = curName
                nameCountLabel.text = "\(curName.count)/\(LNRoomManager.RoomNameMaxInput)"
            } else {
                nameLabel.textColor = .text_2
                nameLabel.text = .init(key: "A00316")
                nameCountLabel.text = "0/\(LNRoomManager.RoomNameMaxInput)"
            }
            
            checkCreate()
        }
    }
    
    private let muteSwitch = UISwitch()
    private let saveButton = UIButton()
    
    private weak var roomSession: LNRoomSession?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func update(_ room: LNRoomSession?) {
        roomSession = room
        
        if let room {
            cover.loadImage(url: room.roomInfo.coverURL)
            curName = room.roomInfo.liveName
            muteSwitch.isOn = room.roomInfo.forbidAudio
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNRoomInfoEditPanel: LNImageUploadViewDelegate {
    func onImageUploadView(view: LNImageUploadView, didUploadImage url: String) {
        checkCreate()
    }
}

extension LNRoomInfoEditPanel {
    private func checkCreate() {
        saveButton.isEnabled = !curName.isEmpty && cover.imageUrl?.isEmpty == false
    }
    
    private func setupViews() {
        container.backgroundColor = .fill_7
        
        let header = buildHeader()
        container.addSubview(header)
        header.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 16
        container.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalTo(header.snp.bottom)
            make.horizontalEdges.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(commonBottomInset)
        }
        
        stackView.addArrangedSubview(buildCover())
        stackView.addArrangedSubview(buildTextInfo())
        stackView.addArrangedSubview(buildSettings())
        
        saveButton.setBackgroundImage(.primary_8, for: .normal)
        saveButton.setTitle(.init(key: "A00185"), for: .normal)
        saveButton.layer.cornerRadius = 23.5
        saveButton.clipsToBounds = true
        saveButton.titleLabel?.font = .heading_h3
        saveButton.titleEdgeInsets = .init(top: 0, left: 4, bottom: 0, right: 0)
        saveButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            guard let roomSession else { return }
            guard let imageUrl = cover.imageUrl else { return }
            
            roomSession.updateRoomInfo(name: curName, cover: imageUrl, forbidAudio: muteSwitch.isOn) { [weak self] success in
                guard let self else { return }
                guard success else { return }
                dismiss()
            }
        }), for: .touchUpInside)
        stackView.addArrangedSubview(saveButton)
        saveButton.snp.makeConstraints { make in
            make.height.equalTo(47)
        }
    }
    
    private func buildHeader() -> UIView {
        let container = UIView()
        container.snp.makeConstraints { make in
            make.height.equalTo(52)
        }
        
        let titleLabel = UILabel()
        titleLabel.text = .init(key: "A00211")
        titleLabel.font = .heading_h3
        titleLabel.textColor = .text_1
        container.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        return container
    }
    
    private func buildCover() -> UIView {
        let container = UIView()
        
        let holder = UIView()
        holder.backgroundColor = .fill_2
        holder.layer.cornerRadius = 12
        holder.clipsToBounds = true
        holder.onTap { [weak self] in
            guard let self else { return }
            LNBottomSheetMenu.showImageSelectMenu(options: .init(allowEdit: true)) { [weak self] image, _ in
                guard let self else { return }
                if let image {
                    cover.uploadImage(image: image)
                }
            }
        }
        container.addSubview(holder)
        holder.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.verticalEdges.equalToSuperview()
            make.width.height.equalTo(105)
        }
        
        let config = UIImage.SymbolConfiguration(pointSize: 17)
        let plus = UIImageView()
        plus.image = .init(systemName: "plus", withConfiguration: config)
        plus.tintColor = .text_3
        holder.addSubview(plus)
        plus.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        cover.delegate = self
        cover.showClearButton = false
        holder.addSubview(cover)
        cover.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let bottom = UIView()
        bottom.backgroundColor = .black.withAlphaComponent(0.3)
        holder.addSubview(bottom)
        bottom.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(22)
        }
        
        coverLabel.text = .init(key: "A00226")
        coverLabel.font = .body_s
        coverLabel.textColor = .text_1
        bottom.addSubview(coverLabel)
        coverLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        return container
    }
    
    private func buildTextInfo() -> UIView {
        let container = UIView()
        
        let titleLabel = UILabel()
        titleLabel.font = .heading_h5
        titleLabel.textColor = .text_2
        titleLabel.text = .init(key: "A00315")
        container.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        nameCountLabel.font = .body_s
        nameCountLabel.textColor = .text_2
        container.addSubview(nameCountLabel)
        nameCountLabel.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel)
            make.trailing.equalToSuperview()
        }
        
        let holder = UIView()
        holder.layer.cornerRadius = 8
        holder.backgroundColor = .fill.withAlphaComponent(0.1)
        holder.onTap { [weak self] in
            guard let self else { return }
            let panel = LNRoomNameInputPanel()
            panel.handler = { [weak self] name in
                guard let self else { return }
                curName = name
            }
            panel.update(curName)
            panel.popup(self)
        }
        container.addSubview(holder)
        holder.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.bottom.equalToSuperview()
            make.height.equalTo(46)
        }
        
        nameLabel.text = .init(key: "A00316")
        nameLabel.font = .heading_h4
        nameLabel.textColor = .text_1
        holder.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(12)
            make.centerY.equalToSuperview()
        }
        
        return container
    }
    
    private func buildSettings() -> UIView {
        let container = UIView()
        
        let titleLabel = UILabel()
        titleLabel.font = .heading_h4
        titleLabel.textColor = .text_1
        titleLabel.text = .init(key: "A00317")
        container.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        let scaleX: CGFloat = 40.0 / 51.0
        let scaleY: CGFloat = 24.5 / 31.0
        muteSwitch.onTintColor = .primary_5
        muteSwitch.transform = CGAffineTransform(scaleX: scaleX, y: scaleY)
        container.addSubview(muteSwitch)
        muteSwitch.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview()
            make.trailing.equalToSuperview()
            make.leading.greaterThanOrEqualTo(titleLabel.snp.trailing).offset(12)
        }
        
        return container
    }
}
