
import Foundation
import UIKit

class InstantPaymentMethodDetailViewController: UIViewController {
    private let paymentMethod: PaymentMethodModel

    private lazy var headerView: UIView = {
        let view = UIView()
        view.backgroundColor = DefaultAppearance.shared.screenBgColor
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    private lazy var headerTitle: UILabel = {
        let label = UILabel()
        label.text = "Payment Details"
        label.font = .systemFont(ofSize: 18, weight: .semibold)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private lazy var backButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        button.tintColor = .systemBlue
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = .clear
        scrollView.showsVerticalScrollIndicator = false
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        return scrollView
    }()

    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = DefaultAppearance.shared.cardColor

        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    private lazy var detailsCardView: UIView = {
        let view = UIView()
        view.backgroundColor = DefaultAppearance.shared.onPrimaryColor
        view.layer.cornerRadius = 16
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOffset = CGSize(width: 0, height: 1)
        view.layer.shadowRadius = 4
        view.layer.shadowOpacity = 0.05
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    private lazy var walletContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = DefaultAppearance.shared.primaryColor
        view.layer.cornerRadius = 12
        view.clipsToBounds = true
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    private lazy var walletImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.tintColor = .white
        imageView.clipsToBounds = true
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()

    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 20, weight: .semibold)
        label.textColor = DefaultAppearance.shared.secondaryLabelColor
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private lazy var balanceLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16)
        label.textColor = DefaultAppearance.shared.secondaryLabelColor
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private lazy var statusLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16, weight: .medium)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private lazy var defaultLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16)
        label.textColor = .systemBlue
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private lazy var actionStackView: UIStackView = {
            let stackView = UIStackView()
            stackView.axis = .horizontal
            stackView.spacing = 16
            stackView.distribution = .fillEqually
            stackView.translatesAutoresizingMaskIntoConstraints = false
            return stackView
        }()

    private lazy var setDefaultButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = .white
        button.layer.cornerRadius = 8
        button.layer.borderWidth = 1
        button.layer.borderColor = UIColor.systemBlue.cgColor
        button.translatesAutoresizingMaskIntoConstraints = false

        let imageConfig = UIImage.SymbolConfiguration(pointSize: 14, weight: .medium)
        let checkmarkImage = UIImage(systemName: "checkmark.circle.fill", withConfiguration: imageConfig)

        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.spacing = 8
        stackView.alignment = .center

        let imageView = UIImageView(image: checkmarkImage)
        imageView.tintColor = .systemBlue

        let label = UILabel()
        label.text = "Set Default"
        label.font = .systemFont(ofSize: 14)
        label.textColor = .systemBlue

        stackView.addArrangedSubview(imageView)
        stackView.addArrangedSubview(label)

        button.addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            stackView.centerXAnchor.constraint(equalTo: button.centerXAnchor),
            stackView.centerYAnchor.constraint(equalTo: button.centerYAnchor)
        ])

        return button
    }()

    private lazy var disableButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = .white
        button.layer.cornerRadius = 8
        button.layer.borderWidth = 1
        button.layer.borderColor = UIColor.systemRed.cgColor
        button.translatesAutoresizingMaskIntoConstraints = false

        let imageConfig = UIImage.SymbolConfiguration(pointSize: 14, weight: .medium)
        let banImage = UIImage(systemName: "slash.circle.fill", withConfiguration: imageConfig)

        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.spacing = 8
        stackView.alignment = .center

        let imageView = UIImageView(image: banImage)
        imageView.tintColor = .systemRed

        let label = UILabel()
        label.text = "Disable"
        label.font = .systemFont(ofSize: 14)
        label.textColor = .systemRed

        stackView.addArrangedSubview(imageView)
        stackView.addArrangedSubview(label)

        button.addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            stackView.centerXAnchor.constraint(equalTo: button.centerXAnchor),
            stackView.centerYAnchor.constraint(equalTo: button.centerYAnchor)
        ])

        return button
    }()

    private lazy var transactionSeparator: UIView = {
        let view = UIView()
        view.backgroundColor = .systemGray5
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    private lazy var transactionsTableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.register(TransactionCell.self, forCellReuseIdentifier: "TransactionCell")
        return tableView
    }()

    init(paymentMethod: PaymentMethodModel) {
        self.paymentMethod = paymentMethod
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = DefaultAppearance.shared.screenBgColor
        setupViews()
        configureDetails()
    }

    private func setupViews() {
        view.addSubview(headerView)
        headerView.addSubview(backButton)
        headerView.addSubview(headerTitle)

        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        contentView.addSubview(detailsCardView)

        detailsCardView.addSubview(walletContainerView)
        walletContainerView.addSubview(walletImageView)
        detailsCardView.addSubview(titleLabel)
        detailsCardView.addSubview(balanceLabel)
        detailsCardView.addSubview(statusLabel)
        detailsCardView.addSubview(defaultLabel)

        actionStackView.addArrangedSubview(setDefaultButton)
        actionStackView.addArrangedSubview(disableButton)
        detailsCardView.addSubview(actionStackView)

        detailsCardView.addSubview(transactionSeparator)
        detailsCardView.addSubview(transactionsTableView)

        NSLayoutConstraint.activate([
            // Header
            headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            headerView.heightAnchor.constraint(equalToConstant: 44),

            backButton.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: 16),
            backButton.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            backButton.widthAnchor.constraint(equalToConstant: 44),
            backButton.heightAnchor.constraint(equalToConstant: 44),

            headerTitle.centerXAnchor.constraint(equalTo: headerView.centerXAnchor),
            headerTitle.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),

            // ScrollView
            scrollView.topAnchor.constraint(equalTo: headerView.bottomAnchor),
            scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),

            // Content View
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),

            // Details Card
            detailsCardView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16),
            detailsCardView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            detailsCardView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),

            // Wallet Container and Image
            walletContainerView.topAnchor.constraint(equalTo: detailsCardView.topAnchor, constant: 0),
            walletContainerView.leadingAnchor.constraint(equalTo: detailsCardView.leadingAnchor, constant: 0),
            walletContainerView.widthAnchor.constraint(equalToConstant: 60),
            walletContainerView.heightAnchor.constraint(equalToConstant: 60),

            walletImageView.centerXAnchor.constraint(equalTo: walletContainerView.centerXAnchor),
            walletImageView.centerYAnchor.constraint(equalTo: walletContainerView.centerYAnchor),
            walletImageView.widthAnchor.constraint(equalToConstant: 40),
            walletImageView.heightAnchor.constraint(equalToConstant: 40),

            // Labels
            titleLabel.topAnchor.constraint(equalTo: walletContainerView.bottomAnchor, constant: 16),
            titleLabel.leadingAnchor.constraint(equalTo: detailsCardView.leadingAnchor, constant: 16),
            titleLabel.trailingAnchor.constraint(equalTo: detailsCardView.trailingAnchor, constant: -16),

            balanceLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8),
            balanceLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
            balanceLabel.trailingAnchor.constraint(equalTo: titleLabel.trailingAnchor),

            statusLabel.topAnchor.constraint(equalTo: balanceLabel.bottomAnchor, constant: 16),
            statusLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),

            defaultLabel.topAnchor.constraint(equalTo: statusLabel.bottomAnchor, constant: 8),
            defaultLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
            defaultLabel.bottomAnchor
                .constraint(
                    lessThanOrEqualTo: detailsCardView.bottomAnchor,
                    constant: -16
                ),


            actionStackView.topAnchor.constraint(equalTo: defaultLabel.bottomAnchor, constant: 24),
            actionStackView.leadingAnchor.constraint(equalTo: detailsCardView.leadingAnchor, constant: 16),
            actionStackView.trailingAnchor.constraint(equalTo: detailsCardView.trailingAnchor, constant: -16),
            actionStackView.heightAnchor.constraint(equalToConstant: 44),

            setDefaultButton.heightAnchor.constraint(equalToConstant: 44),
            disableButton.heightAnchor.constraint(equalToConstant: 44),

            transactionSeparator.topAnchor.constraint(equalTo: actionStackView.bottomAnchor, constant: 24),
            transactionSeparator.leadingAnchor.constraint(equalTo: detailsCardView.leadingAnchor),
            transactionSeparator.trailingAnchor.constraint(equalTo: detailsCardView.trailingAnchor),
            transactionSeparator.heightAnchor.constraint(equalToConstant: 1),

            transactionsTableView.topAnchor.constraint(equalTo: transactionSeparator.bottomAnchor),
            transactionsTableView.leadingAnchor.constraint(equalTo: detailsCardView.leadingAnchor),
            transactionsTableView.trailingAnchor.constraint(equalTo: detailsCardView.trailingAnchor),
            transactionsTableView.bottomAnchor.constraint(equalTo: detailsCardView.bottomAnchor)
        ])


          transactionsTableView.delegate = self
          transactionsTableView.dataSource = self
    }

    private func configureDetails() {
        titleLabel.text = paymentMethod.title
        balanceLabel.text = paymentMethod.subTitle

        statusLabel.text = paymentMethod.isActive ? "Status: Active" : "Status: Inactive"
        statusLabel.textColor = paymentMethod.isActive ? .systemGreen : .systemRed

        defaultLabel.text = paymentMethod.isDefault ? "Default Payment Method" : ""
        defaultLabel.isHidden = !paymentMethod.isDefault

        if !paymentMethod.logo.isEmpty, let logoUrl = URL(string: paymentMethod.logo) {
            URLSession.shared.dataTask(with: logoUrl) { [weak self] data, response, error in
                DispatchQueue.main.async {
                    guard let self = self,
                          let data = data,
                          let originalImage = UIImage(data: data),
                          let ciImage = CIImage(image: originalImage) else {
                        return
                    }

                    if let colorInvertFilter = CIFilter(name: "CIColorInvert") {
                        colorInvertFilter.setValue(ciImage, forKey: kCIInputImageKey)

                        if let outputImage = colorInvertFilter.outputImage {
                            if let whiteColorFilter = CIFilter(name: "CIColorControls") {
                                whiteColorFilter.setValue(outputImage, forKey: kCIInputImageKey)
                                whiteColorFilter.setValue(1.0, forKey: kCIInputBrightnessKey)
                                whiteColorFilter.setValue(0.0, forKey: kCIInputSaturationKey)

                                if let finalOutput = whiteColorFilter.outputImage,
                                   let cgImage = CIContext().createCGImage(finalOutput, from: finalOutput.extent) {
                                    let processedImage = UIImage(cgImage: cgImage)
                                    self.walletImageView.image = processedImage
                                }
                            }
                        }
                    }
                }
            }.resume()
        } else {
            walletImageView.image = UIImage(systemName: "wallet.pass")
        }
    }

    @objc private func backButtonTapped() {
        dismiss(animated: true)
    }
}

// Add TableView delegate and datasource
extension InstantPaymentMethodDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2 // For demo, adjust based on actual transaction data
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TransactionCell", for: indexPath) as! TransactionCell
        // Configure cell with transaction data
        let isFirst = indexPath.row == 0
        cell.configure(date: isFirst ? "Nov 11, 2024 11:07 AM" : "Nov 10, 2024 11:07 AM",
                      amount: isFirst ? "-50" : "-10")
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
}


// Add Transaction Cell
class TransactionCell: UITableViewCell {
    private let dateLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 14)
        label.textColor = .black
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private let typeLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 12)
        label.textColor = .systemGray
        label.text = "Payment"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private let amountLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 14)
        label.textColor = .systemRed
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private let arrowImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.tintColor = .systemRed
        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.image = UIImage(systemName: "arrow.up.right")
        return imageView
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupCell()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupCell() {
        selectionStyle = .none
        backgroundColor = .clear

        contentView.addSubview(arrowImageView)
        contentView.addSubview(dateLabel)
        contentView.addSubview(typeLabel)
        contentView.addSubview(amountLabel)

        NSLayoutConstraint.activate([
            arrowImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            arrowImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
            arrowImageView.widthAnchor.constraint(equalToConstant: 24),
            arrowImageView.heightAnchor.constraint(equalToConstant: 24),

            dateLabel.leadingAnchor.constraint(equalTo: arrowImageView.trailingAnchor, constant: 12),
            dateLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),

            typeLabel.leadingAnchor.constraint(equalTo: dateLabel.leadingAnchor),
            typeLabel.topAnchor.constraint(equalTo: dateLabel.bottomAnchor, constant: 4),

            amountLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            amountLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
        ])
    }

    func configure(date: String, amount: String) {
        dateLabel.text = date
        amountLabel.text = amount
    }
}
