//
//  IdentityAlertView.swift
//  OrderScheduling
//
//  Created by 中道 on 2025/12/19.
//

import UIKit
import SnapKit

final class IdentityAlertView: UIView {
    
    // MARK: - Public Callbacks
    var onConfirm: (() -> Void)?
    var onLater: (() -> Void)?
    
    // MARK: - UI
    private let containerView = UIView()
    private let iconContainer = UIView()
    private let iconImageView = UIImageView()
    private let gradientLayer = CAGradientLayer()
    private let titleLabel = UILabel()
    private let messageLabel = UILabel()
    private let confirmButton = UIButton(type: .system)
    private let laterButton = UIButton(type: .system)
    
    // MARK: - Init
    
    /// times: 第几次提醒；totalTimes: 总次数，比如 3
    init(times: Int = 1, totalTimes: Int = 3, isLast: Bool) {
        super.init(frame: .zero)
        setupUI(times: times, totalTimes: totalTimes, isLast:isLast)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer.frame = containerView.bounds
    }
}

// MARK: - UI

private extension IdentityAlertView {
    func setupUI(times: Int, totalTimes: Int, isLast: Bool) {
        backgroundColor = .clear
        
        // 容器（白色卡片，顶部有渐变）
        addSubview(containerView)
        addSubview(iconContainer)
        
        containerView.layer.cornerRadius = 18
        containerView.layer.masksToBounds = true
        
        // 渐变背景：上浅橙，下白色，模拟设计稿上半段渐变
        gradientLayer.colors = [
            UIColor(red: 0xFF/255.0, green: 0xE4/255.0, blue: 0xD7/255.0, alpha: 1).cgColor,
            UIColor.white.cgColor
        ]
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.25)
        containerView.layer.insertSublayer(gradientLayer, at: 0)
        
        // 先约束图标容器：居中，顶在 entry 顶部；宽高 52
        iconContainer.layer.cornerRadius = 26
        iconContainer.layer.masksToBounds = true
        iconContainer.backgroundColor = .clear
        
        iconContainer.snp.makeConstraints { make in
            make.top.equalToSuperview()        // 让图标顶部贴住 entry 顶部
            make.centerX.equalToSuperview()
            make.width.height.equalTo(52)
        }
        
        // 再约束白色卡片：顶部经过图标中心，实现“图标一半悬在卡片外”的效果
        containerView.snp.makeConstraints { make in
            make.top.equalTo(iconContainer.snp.centerY)
            make.left.right.bottom.equalToSuperview()
        }
        
        // 感叹号图标（切好的 52x52 图片，内含背景样式）
        iconImageView.image = UIImage(named: "IdentityAlertNotice")
        iconImageView.contentMode = .scaleAspectFit
        iconContainer.addSubview(iconImageView)
        iconImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 标题
        titleLabel.text = "重要提示"
        titleLabel.font = .boldSystemFont(ofSize: 18)
        titleLabel.textColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1)
        titleLabel.textAlignment = .center
        containerView.addSubview(titleLabel)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(iconContainer.snp.bottom).offset(16)
            make.left.right.equalToSuperview().inset(20)
        }
        
        // 文案
        let reminderText = isLast ? "本次为最后一次提醒" : "此为第\(times)次提醒"
        let message = """
        中道救援将通过您确认的身份及联系方式，向您发送通知。请务必仔细核对您的身份及联系方式等关键信息，以免因无法接收通知而受到损失。\n
        \(reminderText)，请及时确认。若\(totalTimes)次提醒仍未确认，您将无法承接案件。
        """
        
        let attr = NSMutableAttributedString(string: message)
        let fullRange = NSRange(location: 0, length: attr.length)
        let paragraph = NSMutableParagraphStyle()
        paragraph.lineSpacing = 4
        paragraph.alignment = .center
        
        attr.addAttributes([
            .font: UIFont.systemFont(ofSize: 14),
            .foregroundColor: UIColor(red: 0x66/255, green: 0x66/255, blue: 0x66/255, alpha: 1),
            .paragraphStyle: paragraph
        ], range: fullRange)
        
        // 高亮 “将无法承接案件。”
        if let highlightRange = (message as NSString).range(of: "请务必仔细核对您的身份及联系方式等关键信息").optionalNonEmpty {
            attr.addAttribute(.foregroundColor,
                              value: UIColor(red: 0xF5/255, green: 0x52/255, blue: 0x3C/255, alpha: 1),
                              range: highlightRange)
        }
        
        messageLabel.attributedText = attr
        messageLabel.numberOfLines = 0
        containerView.addSubview(messageLabel)
        
        messageLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
            make.left.right.equalToSuperview().inset(24)
        }
        
        // 立即确认按钮
        confirmButton.setTitle("立即确认", for: .normal)
        confirmButton.setTitleColor(.white, for: .normal)
        confirmButton.titleLabel?.font = .boldSystemFont(ofSize: 16)
        confirmButton.backgroundColor = UIColor(red: 0xFF/255, green: 0x6B/255, blue: 0x50/255, alpha: 1)
        confirmButton.layer.cornerRadius = 20
        confirmButton.layer.masksToBounds = true
        confirmButton.addTarget(self, action: #selector(handleConfirm), for: .touchUpInside)
        containerView.addSubview(confirmButton)
        
        confirmButton.snp.makeConstraints { make in
            make.top.equalTo(messageLabel.snp.bottom).offset(20)
            make.left.right.equalToSuperview().inset(40)
            make.height.equalTo(40)
        }
        
        // 稍后提醒按钮
        laterButton.setTitle(isLast ? "放弃" : "稍后提醒", for: .normal)
        laterButton.setTitleColor(UIColor(red: 0x99/255, green: 0x99/255, blue: 0x99/255, alpha: 1), for: .normal)
        laterButton.titleLabel?.font = .systemFont(ofSize: 14)
        laterButton.addTarget(self, action: #selector(handleLater), for: .touchUpInside)
        containerView.addSubview(laterButton)
        
        laterButton.snp.makeConstraints { make in
            make.top.equalTo(confirmButton.snp.bottom).offset(12)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
        }
    }
}

// MARK: - Actions

private extension IdentityAlertView {
    @objc func handleConfirm() {
        onConfirm?()
    }
    
    @objc func handleLater() {
        onLater?()
    }
}

private extension NSRange {
    var optionalNonEmpty: NSRange? {
        return location != NSNotFound && length > 0 ? self : nil
    }
}
