//
//  LNRoomGiftPanel.swift
//  Gami
//
//  Created by OneeChan on 2026/3/23.
//

import Foundation
import UIKit
import SnapKit


class LNRoomGiftPanel: LNPopupView {
    private let headerView = LNRoomGiftHeaderView()
    private let listView = LNRoomGiftListView()
    private let bottomView = LNRoomGiftBottomView()
    
    private weak var roomSession: LNRoomSession?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func update(_ room: LNRoomSession?, selectedUid: String? = nil) {
        roomSession = room
        headerView.update(room, selectedUid: selectedUid)
        listView.update(room)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNRoomGiftPanel: LNRoomGiftListViewDelegate {
    func onRoomGiftListView(_ view: LNRoomGiftListView, didSelect index: Int) {
        checkSendEnable()
    }
}

extension LNRoomGiftPanel: LNRoomGiftBottomViewDelegate {
    func onRoomGiftBottomViewDidTapBalance(_ view: LNRoomGiftBottomView) {
        dismiss()
        pushToDiamondView()
    }
    
    func onRoomGiftBottomViewDidTapSend(_ view: LNRoomGiftBottomView) {
        if headerView.selection.isEmpty {
            showToast(.init(key: "A00391"))
            return
        }
        guard let gift = listView.selectedGift else {
            return
        }
        roomSession?.sendGift(gift: gift, to: headerView.selection, count: bottomView.curCount) { _ in }
    }
}

extension LNRoomGiftPanel {
    private func checkSendEnable() {
        bottomView.enable = listView.selectedGift != nil
    }
    
    private func setupViews() {
        touchOutsideToCancel = true
        container.backgroundColor = .fill_7
        
        container.addSubview(headerView)
        headerView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.horizontalEdges.equalToSuperview()
        }
        
        let separator = UIView()
        separator.backgroundColor = .text_1.withAlphaComponent(0.12)
        container.addSubview(separator)
        separator.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(10)
            make.horizontalEdges.equalToSuperview().inset(10)
            make.height.equalTo(0.5)
        }
        
        listView.delegate = self
        container.addSubview(listView)
        listView.snp.makeConstraints { make in
            make.top.equalTo(separator.snp.bottom).offset(10)
            make.horizontalEdges.equalToSuperview()
            make.height.equalTo(256)
        }
        
        bottomView.delegate = self
        container.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.top.equalTo(listView.snp.bottom)
            make.horizontalEdges.equalToSuperview()
            make.bottom.equalToSuperview().offset(commonBottomInset + 12)
        }
    }
}
