//
//  LNProfileInRoomView.swift
//  Gami
//
//  Created by OneeChan on 2026/3/17.
//

import Foundation
import UIKit
import SnapKit


class LNProfileInRoomView: UIView {
    private var uid: String?
    private let waveView = UIView()
    private let borderColor: UIColor = .fill
    private let borderWidth: CGFloat = 1
    private let fillColor: UIColor = .clear
    private let duration: Double = 2
    private let offset = 10.0
    private let waveCount = 2
    private var borderLayers: [CAShapeLayer] = []
    
    private let roomCover = UIImageView()
    private var roomInfo: LNRoomItemVO?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func update(_ uid: String) {
        self.uid = uid
        reloadRoomInfo()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if borderLayers.first?.bounds.height != waveView.bounds.height {
            for (index, layer) in borderLayers.enumerated() {
                layer.frame = waveView.bounds
                layer.cornerRadius = waveView.bounds.height * 0.5
                layer.removeAllAnimations()
                startAnimate(layer: layer, index: index)
            }
        }
    }
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        
        if window != nil {
            reloadRoomInfo()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNProfileInRoomView {
    private func reloadRoomInfo() {
        guard let uid else { return }
        
        LNRoomManager.shared.getUserCurRoom(uid: uid) { [weak self] res in
            guard let self else { return }
            guard let res else { return }
            roomInfo = res.room
            
            if let room = res.room, !room.roomId.isEmpty {
                isHidden = false
                roomCover.sd_setImage(with: URL(string: room.roomCover))
            } else {
                isHidden = true
            }
        }
    }
}

private extension LNProfileInRoomView {
    func setupViews() {
        onTap { [weak self] in
            guard let self else { return }
            guard let roomInfo else { return }
            pushToRoom(roomInfo.roomId)
        }
        snp.makeConstraints { make in
            make.width.equalTo(83)
            make.height.equalTo(88)
        }
        
        let bg = buildBg()
        addSubview(bg)
        bg.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let waveView = buildWaveView()
        addSubview(waveView)
        waveView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(17.6)
        }
        
        roomCover.layer.cornerRadius = 18
        roomCover.clipsToBounds = true
        addSubview(roomCover)
        roomCover.snp.makeConstraints { make in
            make.center.equalTo(waveView)
            make.width.height.equalTo(37)
        }
        
        let bottom = buildBottom()
        addSubview(bottom)
        bottom.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-6)
        }
    }
    
    func startAnimate(layer: CAShapeLayer, index: Int) {
        let scaleAnim = CABasicAnimation(keyPath: "transform.scale")
        scaleAnim.fromValue = 1.0
        scaleAnim.toValue = 1.0 + offset / CGFloat(layer.bounds.width / 2)
        scaleAnim.duration = duration
        
        let opacityAnim = CABasicAnimation(keyPath: "opacity")
        opacityAnim.fromValue = 1.0
        opacityAnim.toValue = 0.0
        opacityAnim.duration = duration
        
        let animGroup = CAAnimationGroup()
        animGroup.animations = [scaleAnim, opacityAnim]
        animGroup.duration = duration
        animGroup.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        animGroup.isRemovedOnCompletion = false
        animGroup.fillMode = .forwards
        animGroup.repeatCount = .infinity
        animGroup.beginTime = CACurrentMediaTime() + Double(index) * duration * 0.5
        layer.add(animGroup, forKey: "scaleAndFadeGroup")
    }
    
    func buildBg() -> UIView {
        let container = UIView()
        
        let bg = UIImageView()
        bg.image = .primary_7
        bg.alpha = 0.3
        bg.layer.cornerRadius = 16
        bg.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
        bg.clipsToBounds = true
        bg.layer.borderColor = UIColor.fill.withAlphaComponent(0.3).cgColor
        bg.layer.borderWidth = 0.5
        container.addSubview(bg)
        bg.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview()
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview().offset(0.5)
        }
        
        let blurEffect = UIBlurEffect(style: .regular)
        let blurView = UIVisualEffectView(effect: blurEffect)
        blurView.layer.cornerRadius = 16
        blurView.alpha = 0.85
        blurView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
        blurView.clipsToBounds = true
        container.addSubview(blurView)
        blurView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        return container
    }
    
    func buildWaveView() -> UIView {
        waveView.snp.makeConstraints { make in
            make.width.height.equalTo(36.5)
        }
        
        for _ in 0..<waveCount {
            let borderLayer = CAShapeLayer()
            borderLayer.borderColor = borderColor.cgColor
            borderLayer.borderWidth = borderWidth
            borderLayer.backgroundColor = fillColor.cgColor
            waveView.layer.addSublayer(borderLayer)
            borderLayers.append(borderLayer)
        }
        
        return waveView
    }
    
    func buildBottom() -> UIView {
        let bottom = UIView()
        
        let textLabel = UILabel()
        textLabel.text = .init(key: "A00351")
        textLabel.font = .heading_h5
        textLabel.textColor = .text_1
        bottom.addSubview(textLabel)
        textLabel.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview()
            make.leading.equalToSuperview()
        }
        
        let arrow = UIImageView.arrowImageView(size: 9, weight: .medium)
        arrow.tintColor = .fill
        bottom.addSubview(arrow)
        arrow.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(textLabel.snp.trailing).offset(3)
            make.trailing.equalToSuperview()
        }
        
        return bottom
    }
}
