//
//  TSChatViewController+Ex.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/10.
//
import InputBarAccessoryView
import MessageKit
import UIKit
import MapKit


// MARK: MessagesDataSource
extension TSChatViewController {
    
    var currentSender: SenderType {
        return viewModel.kUserSender
    }
    
    func numberOfSections(in _: MessagesCollectionView) -> Int {
        return 1
    }
    
    func numberOfItems(inSection section: Int, in messagesCollectionView: MessagesCollectionView) -> Int{
        messageList.count
    }
    
    func messageForItem(at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageType {
        messageList[indexPath.item]
    }
    
    func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
//        if indexPath.item % 3 == 0 {
//            return NSAttributedString(
//                string: MessageKitDateFormatter.shared.string(from: message.sentDate),
//                attributes: [
//                    NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
//                    NSAttributedString.Key.foregroundColor: UIColor.darkGray,
//                ])
//        }
        return nil
    }
    
    func cellBottomLabelAttributedText(for _: MessageType, at _: IndexPath) -> NSAttributedString? {
        NSAttributedString(
            string: "Read",
            attributes: [
                NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
                NSAttributedString.Key.foregroundColor: UIColor.darkGray,
            ])
    }
    
    func messageTopLabelAttributedText(for message: MessageType, at _: IndexPath) -> NSAttributedString? {
        let name = message.sender.displayName
        return NSAttributedString(
            string: name,
            attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption1)])
    }
    
    func messageBottomLabelAttributedText(for message: MessageType, at _: IndexPath) -> NSAttributedString? {
        let dateString = formatter.string(from: message.sentDate)
        return NSAttributedString(
            string: dateString,
            attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)])
    }
    
    func textCell(
        for message: MessageType,
        at indexPath: IndexPath,
        in messagesCollectionView: MessagesCollectionView)
    -> UICollectionViewCell?
    {
        let cell = messagesCollectionView.dequeueReusableCell(
            TSTextMessageContentCell.self,
            for: indexPath)
        cell.configure(
            with: message,
            at: indexPath,
            in: messagesCollectionView,
            dataSource: self,
            and: textMessageSizeCalculator)
        
        return cell
    }
}



// MARK: MessagesLayoutDelegate

extension TSChatViewController: MessagesLayoutDelegate {
    func customCellSizeCalculator(for message: any MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CellSizeCalculator {
        self.textMessageSizeCalculator
    }
}


// MARK: MessagesDisplayDelegate

extension TSChatViewController: MessagesDisplayDelegate {
    // MARK: - Text Messages
    
    func textColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
        return UIColor.mainBg
        //      isFromCurrentSender(message: message) ? UIColor.mainBg : .white
    }
    
    func detectorAttributes(for detector: DetectorType, and _: MessageType, at _: IndexPath) -> [NSAttributedString.Key: Any] {
        switch detector {
        case .hashtag, .mention: return [.foregroundColor: UIColor.blue]
        default: return MessageLabel.defaultAttributes
        }
    }
    
    func enabledDetectors(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> [DetectorType] {
        [.url, .address, .phoneNumber, .date, .transitInformation, .mention, .hashtag]
    }
    
    // MARK: - All Messages
     
    func backgroundColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
        isFromCurrentSender(message: message) ? .themeColor : UIColor.white.withAlphaComponent(0.05)//"#222222".uiColor
    }
    
    func messageStyle(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> MessageStyle {
        let tail: MessageStyle.TailCorner = isFromCurrentSender(message: message) ? .bottomRight : .bottomLeft
        if let image = UIImage(named: "bobbly") {
            return .customImageTail(image, tail)
        } else {
            return .bubbleTail(tail, .curved)
        }
    }
    
    func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) {
        //    let avatar = SampleData.shared.getAvatarFor(sender: message.sender)
        //设置聊天头像
//        avatarView.set(avatar: Avatar(image: UIImage(named: "App-Icon")))
    }
    
    func configureMediaMessageImageView(
        _ imageView: UIImageView,
        for message: MessageType,
        at _: IndexPath,
        in _: MessagesCollectionView)
    {
        if case MessageKind.photo(let media) = message.kind, let imageURL = media.url {
            imageView.kf.setImage(with: imageURL)
        } else {
            imageView.kf.cancelDownloadTask()
        }
    }
    
    // MARK: - Location Messages
    
    func annotationViewForLocation(message _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> MKAnnotationView? {
        let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
        let pinImage = #imageLiteral(resourceName: "ic_map_marker")
        annotationView.image = pinImage
        annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
        return annotationView
    }
    
    func animationBlockForLocation(
        message _: MessageType,
        at _: IndexPath,
        in _: MessagesCollectionView) -> ((UIImageView) -> Void)?
    {
        { view in
            view.layer.transform = CATransform3DMakeScale(2, 2, 2)
            UIView.animate(
                withDuration: 0.6,
                delay: 0,
                usingSpringWithDamping: 0.9,
                initialSpringVelocity: 0,
                options: [],
                animations: {
                    view.layer.transform = CATransform3DIdentity
                },
                completion: nil)
        }
    }
    
    func snapshotOptionsForLocation(
        message _: MessageType,
        at _: IndexPath,
        in _: MessagesCollectionView)
    -> LocationMessageSnapshotOptions
    {
        LocationMessageSnapshotOptions(
            showsBuildings: true,
            showsPointsOfInterest: true,
            span: MKCoordinateSpan(latitudeDelta: 10, longitudeDelta: 10))
    }
    
    // MARK: - Audio Messages
    
    func audioTintColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
        isFromCurrentSender(message: message) ? .white : UIColor(red: 15 / 255, green: 135 / 255, blue: 255 / 255, alpha: 1.0)
    }
    
    func configureAudioCell(_ cell: AudioMessageCell, message: MessageType) {
        
    }
}


// MARK: MessageCellDelegate

extension TSChatViewController: MessageCellDelegate {
    func didTapBackground(in cell: MessageCollectionViewCell) {
        
        guard let msgCell = cell as? TSMessageContentCell else { return }
        
        guard let indexPath = messagesCollectionView.indexPath(for: cell) else{ return }
        
        guard let cellTapType = msgCell.cellTapType else{ return }
        
        guard let model = messageList.safeObj(At: indexPath.item) else{ return }

        switch cellTapType {
        case .copyMsg:
            if case let .attributedText(text) = model.kind{
                //拷贝文字到截切板
                UIPasteboard.general.string = text.string
                kSavePhotoSuccesswShared.show(atView: self.view,text: "Copyed Successfully".localized,showViewBtn:false)
            }
            
        case .refreshMsg:
            if case let .attributedText(text) = model.kind{
            
                guard let questionModel = messageList.safeObj(At: indexPath.item-1) else{ return }
                var questionString = ""
                if case let .attributedText(text) = questionModel.kind{
                    questionString = text.string
                }else if case let .text(text) = questionModel.kind{
                    questionString = text
                }
                
                if questionString.count > 0 {
                    generativeAIChat(questionString: questionString,indexPath:indexPath)
                }
            }
        
        }
    }
}

// MARK: MessageLabelDelegate

extension TSChatViewController: MessageLabelDelegate {
    func didSelectCustom(_ pattern: String, match _: String?) {
        print("Custom data detector patter selected: \(pattern)")
    }
}
