//
//  CustomTopUIView.swift
//  MyTatvaCare
//
//  Created by Nirav Ramani on 05/05/25.
//

import UIKit

@IBDesignable
class CustomTopUIView: UIView {

    private let demoButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle(" Watch CGM Demo", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 18
        button.layer.masksToBounds = true
        button.titleLabel?.font = FontManager.font(ofSize: 14, weight: .medium)
        button.tintColor = .white
        let playImage = loadImage(named: "ic_play")?.withTintColor(.white) ?? UIImage(systemName: "play.fill")?.withRenderingMode(.alwaysOriginal).withTintColor(.white)
        button.setImage(playImage, for: .normal)

        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    private let whatsappButton: UIButton = {
        let button = UIButton(type: .system)
        let image = loadImage(named: "ic_whatsapp") ?? UIImage(systemName: "message.fill")!
        button.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)
        button.backgroundColor = .green
        button.layer.cornerRadius = 18
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    private let closeButton: UIButton = {
        let button = UIButton(type: .custom)
        let image = loadImage(named: "ic_close")
        button.setImage(image, for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    // MARK: - Callbacks
    var onDemoTapped: (() -> Void)?
    var onWhatsAppTapped: (() -> Void)?
    var onCloseTapped: (() -> Void)?

    
    // For Interface Builder
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setupView()
    }
    
    override var intrinsicContentSize: CGSize {
        // Calculate the intrinsic size based on subviews
        layoutIfNeeded()
        let height = max(demoButton.intrinsicContentSize.height, whatsappButton.frame.height, closeButton.frame.height)
        let width = demoButton.intrinsicContentSize.width + 8 + 40 + 8 + 40
        return CGSize(width: width, height: height)
    }
   
    override func layoutSubviews() {
        super.layoutSubviews()
        applyGradientToDemoButton()
    }
    
    private func applyGradientToDemoButton() {
        // Remove old gradients
        demoButton.layer.sublayers?.removeAll(where: { $0 is CAGradientLayer })
        
        let startEndColor = UIColor(hex: "#3538CD")
        let middleColor = UIColor(hex: "#6172F3")

        let gradient = createCenterColorGradient(
            frame: demoButton.bounds,
            startEndColor: startEndColor,
            middleColor: middleColor,
            isHorizontal: true
        )
        
        demoButton.layer.insertSublayer(gradient, at: 0)
    }

    private func setupView() {
        // Prevent multiple adds in Interface Builder
        if demoButton.superview == nil {
            addSubview(demoButton)
            addSubview(whatsappButton)
            addSubview(closeButton)

            NSLayoutConstraint.activate([
                demoButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
                demoButton.centerYAnchor.constraint(equalTo: centerYAnchor),
                demoButton.heightAnchor.constraint(equalToConstant: 36),
                demoButton.widthAnchor.constraint(equalToConstant: 160),

                whatsappButton.leadingAnchor.constraint(equalTo: demoButton.trailingAnchor, constant: 8),
                whatsappButton.centerYAnchor.constraint(equalTo: demoButton.centerYAnchor),
                whatsappButton.widthAnchor.constraint(equalToConstant: 36),
                whatsappButton.heightAnchor.constraint(equalToConstant: 36),

                //closeButton.leadingAnchor.constraint(equalTo: whatsappButton.trailingAnchor, constant: 8),
                closeButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
                closeButton.centerYAnchor.constraint(equalTo: demoButton.centerYAnchor),
                closeButton.widthAnchor.constraint(equalToConstant: 36),
                closeButton.heightAnchor.constraint(equalToConstant: 36),
            ])
            
            demoButton.addTarget(self, action: #selector(demoButtonTapped), for: .touchUpInside)
            whatsappButton.addTarget(self, action: #selector(whatsappButtonTapped), for: .touchUpInside)
            closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)

        }
    }
    
    func showOnlyClose() {
        demoButton.isHidden = true
        whatsappButton.isHidden = true
    }
    
    @objc private func demoButtonTapped() {
        onDemoTapped?()
    }

    @objc private func whatsappButtonTapped() {
        onWhatsAppTapped?()
    }

    @objc private func closeButtonTapped() {
        onCloseTapped?()
    }

    func createCenterColorGradient(
        frame: CGRect,
        startEndColor: UIColor,
        middleColor: UIColor,
        isHorizontal: Bool = false
    ) -> CAGradientLayer {
        
        let gradient = CAGradientLayer()
        gradient.frame = frame

        gradient.colors = [
            startEndColor.cgColor,
            middleColor.cgColor,
            startEndColor.cgColor
        ]

        // Location: 0.0 (start), 0.5 (middle), 1.0 (end)
        gradient.locations = [0.0, 0.5, 1.0]

        // Direction
        gradient.startPoint = CGPoint(x: 0, y: 0.5)
        gradient.endPoint = isHorizontal ? CGPoint(x: 1, y: 0.5) : CGPoint(x: 0.5, y: 1)

        return gradient
    }

}
