//
//  YHRecommendedAppointmentLiveView.swift
//  galaxy
//
//  Created by alexzzw on 2024/12/29.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHRecommendedAppointmentLiveView: UIView {
    var appointmentButtonEvent: (() -> Void)?
    var buttonClickEvent: (() -> Void)?

    private lazy var containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white.withAlphaComponent(0.08)
        return view
    }()

    private lazy var liveTitleLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_B(ofSize: 16)
        label.textColor = .white
        return label
    }()

    private lazy var timeLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 12)
        label.textColor = .white.withAlphaComponent(0.5)
        return label
    }()

    private lazy var avatarImageView: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFit
        view.clipsToBounds = true
        view.layer.cornerRadius = 9
        return view
    }()

    private lazy var anchorLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 12)
        label.textColor = .white.withAlphaComponent(0.5)
        return label
    }()

    private lazy var appointmentButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("预约", for: .normal)
        button.setTitle("已预约", for: .selected)
        button.setTitleColor(UIColor.mainTextColor, for: .normal)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 12)
        button.backgroundColor = .white
        button.addTarget(self, action: #selector(appointmentButtonClicked), for: .touchUpInside)
        return button
    }()

    @objc private func appointmentButtonClicked() {
        if appointmentButton.isSelected {
            return
        }
        appointmentButtonEvent?()
    }
    
    @objc private func tapButton(gestureRecognizer: UITapGestureRecognizer) {
        buttonClickEvent?()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(containerView)
        containerView.addSubview(liveTitleLabel)
        containerView.addSubview(timeLabel)
        containerView.addSubview(avatarImageView)
        containerView.addSubview(anchorLabel)
        containerView.addSubview(appointmentButton)

        containerView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.bottom.equalToSuperview()
        }

        liveTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(16)
            make.right.lessThanOrEqualTo(appointmentButton.snp.left).offset(-16)
        }

        timeLabel.snp.makeConstraints { make in
            make.left.equalTo(liveTitleLabel.snp.left)
            make.top.equalTo(liveTitleLabel.snp.bottom).offset(6)
            make.right.lessThanOrEqualTo(appointmentButton.snp.left).offset(-16)
        }

        avatarImageView.snp.makeConstraints { make in
            make.left.equalTo(liveTitleLabel.snp.left)
            make.top.equalTo(timeLabel.snp.bottom).offset(8)
            make.width.height.equalTo(18)
            make.bottom.equalToSuperview().offset(-16)
        }

        anchorLabel.snp.makeConstraints { make in
            make.left.equalTo(avatarImageView.snp.right).offset(4)
            make.centerY.equalTo(avatarImageView)
            make.right.lessThanOrEqualTo(appointmentButton.snp.left).offset(-16)
        }

        appointmentButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.centerY.equalToSuperview()
            make.width.equalTo(77)
            make.height.equalTo(32)
        }
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapButton(gestureRecognizer:)))
        addGestureRecognizer(tap)
    }

    func updateAppointmentButton(isAppointmented: Bool) {
        if isAppointmented {
            self.appointmentButton.isSelected = true
        } else {
            self.appointmentButton.isSelected = false
        }
    }
    
    func updateViews(liveTitle: String, fromTime: String, endTime: String, avatar: String, anchorName: String, isAppointmented: Bool) {
        liveTitleLabel.text = liveTitle
        var timeStr = "直播时间：" + fromTime
        if !fromTime.isEmpty, !endTime.isEmpty {
            let time = isSameDayAndGetShortEndTime(date1String: fromTime, date2String: endTime)
            timeStr += "~" + time
        }
        timeLabel.text = timeStr
        if let url = URL(string: avatar) {
            avatarImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
        } else {
            avatarImageView.image = UIImage(named: "global_default_image")
        }
        anchorLabel.text = anchorName
        updateAppointmentButton(isAppointmented: isAppointmented)
    }
    
    private func isSameDayAndGetShortEndTime(date1String: String, date2String: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM月dd日HH:mm"
        let date1 = dateFormatter.date(from: date1String)
        let date2 = dateFormatter.date(from: date2String)
        guard let date1 = date1, let date2 = date2 else {
            return date2String
        }
        let calendar = Calendar.current
        let components1 = calendar.dateComponents([.month, .day, .hour, .minute], from: date1)
        let components2 = calendar.dateComponents([.month, .day, .hour, .minute], from: date2)
        if components1.month == components2.month &&
            components1.day == components2.day {
            let hour = components2.hour ?? 0
            let minute = components2.minute ?? 0
            return String(format: "%02d:%02d", hour, minute)
        }
        return date2String
    }
}
