//
//  LNDatePickerPanel.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/3.
//

import Foundation
import UIKit
import SnapKit

class LNDatePickerPanel: LNPopupView {
    var handler: ((TimeInterval) -> Void)?
    
    let titleLabel = UILabel()
    let datePicker = UIDatePicker()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func setDefault(_ date: TimeInterval) {
        datePicker.date = Date(timeIntervalSince1970: date)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNDatePickerPanel {
    private func setupViews() {
        let header = UIView()
        container.addSubview(header)
        header.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(50)
        }
        
        titleLabel.font = .heading_h3
        titleLabel.textColor = .text_5
        header.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        let confirm = UIButton()
        confirm.setTitle(.init(key: "A00002"), for: .normal)
        confirm.setTitleColor(.text_1, for: .normal)
        confirm.setBackgroundImage(.primary_8, for: .normal)
        confirm.layer.cornerRadius = 23.5
        confirm.titleLabel?.font = .heading_h3
        confirm.clipsToBounds = true
        confirm.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            handler?(datePicker.date.timeIntervalSince1970)
            dismiss()
        }), for: .touchUpInside)
        container.addSubview(confirm)
        confirm.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(22)
            make.bottom.equalToSuperview().offset(commonBottomInset)
            make.height.equalTo(47)
        }
        
        datePicker.locale = curLocal
        datePicker.datePickerMode = .date
        datePicker.preferredDatePickerStyle = .wheels
        container.addSubview(datePicker)
        datePicker.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(12)
            make.top.equalTo(header.snp.bottom)
            make.bottom.equalTo(confirm.snp.top).offset(-10)
        }
    }
}
