//
//  CreatorCommunityAllItemView.swift
//  SodaLive
//
//  Created by klaus on 2023/12/15.
//

import SwiftUI
import Kingfisher

struct CreatorCommunityAllItemView: View {
    
    let item: GetCommunityPostListResponse
    let onClickLike: () -> Void
    let onClickComment: () -> Void
    let onClickWriteComment: (String) -> Void
    let onClickShowReportMenu: () -> Void
    let onClickPurchaseContent: () -> Void
    
    @State var isLike = false
    @State var likeCount = 0
    @State private var textHeight: CGFloat = .zero
    
    @StateObject var playManager = CreatorCommunityMediaPlayerManager.shared
    @StateObject var contentPlayManager = ContentPlayManager.shared
    
    init(
        item: GetCommunityPostListResponse,
        onClickLike: @escaping () -> Void,
        onClickComment: @escaping () -> Void,
        onClickWriteComment: @escaping (String) -> Void,
        onClickShowReportMenu: @escaping () -> Void,
        onClickPurchaseContent: @escaping () -> Void
    ) {
        self.item = item
        self.onClickLike = onClickLike
        self.onClickComment = onClickComment
        self.onClickWriteComment = onClickWriteComment
        self.onClickShowReportMenu = onClickShowReportMenu
        self.onClickPurchaseContent = onClickPurchaseContent
        
        self._isLike = State(initialValue: item.isLike)
        self._likeCount = State(initialValue: item.likeCount)
    }
    
    var body: some View {
        VStack(spacing: 13.3) {
            HStack(spacing: 0) {
                KFImage(URL(string: item.creatorProfileUrl))
                    .cancelOnDisappear(true)
                    .downsampling(
                        size: CGSize(
                            width: 40,
                            height: 40
                        )
                    )
                    .resizable()
                    .frame(width: 40, height: 40)
                    .clipShape(Circle())
                
                VStack(alignment: .leading, spacing: 3) {
                    Text(item.creatorNickname)
                        .font(.custom(Font.medium.rawValue, size: 13.3))
                        .foregroundColor(Color.grayee)
                    
                    Text(item.date)
                        .font(.custom(Font.light.rawValue, size: 13.3))
                        .foregroundColor(Color.gray77)
                }
                .padding(.leading, 11)
                
                Spacer()
                
                if item.price <= 0 || item.existOrdered {
                    Image("ic_seemore_vertical")
                        .padding(.trailing, 8.3)
                        .onTapGesture { onClickShowReportMenu() }
                }
            }
            
            DetectableTextView(text: item.content, textSize: 13.3, font: Font.medium.rawValue)
                .frame(
                    width: screenSize().width - 42,
                    height: textHeight
                )
                .onAppear {
                    self.textHeight = self.estimatedHeight(
                        for: item.content,
                        width: screenSize().width - 42
                    )
                }
                .onChange(of: item.content) { newText in
                    self.textHeight = self.estimatedHeight(
                        for: newText,
                        width: screenSize().width - 42
                    )
                }
            
            if item.price <= 0 || item.existOrdered {
                if let imageUrl = item.imageUrl {
                    ZStack {
                        KFImage(URL(string: imageUrl))
                            .resizable()
                            .frame(maxWidth: .infinity)
                            .scaledToFit()
                        
                        if let audioUrl = item.audioUrl {
                            Image(playManager.isPlaying && playManager.currentPlayingContentId == item.postId ? "btn_audio_content_pause" : "btn_audio_content_play")
                                .onTapGesture {
                                    contentPlayManager.pauseAudio()
                                    playManager.toggleContent(item: CreatorCommunityContentItem(contentId: item.postId, url: audioUrl))
                                }
                        }
                    }
                }
                
                HStack(spacing: 8) {
                    IconAndTitleToggleButton(
                        isChecked: isLike,
                        title: "\(likeCount)",
                        normalIconName: "ic_audio_content_heart_normal",
                        checkedIconName: "ic_audio_content_heart_pressed"
                    ) {
                        if isLike {
                            isLike = false
                            likeCount -= 1
                        } else {
                            isLike = true
                            likeCount += 1
                        }
                        onClickLike()
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)
                
                if item.isCommentAvailable {
                    CreatorCommunityCommentView(
                        commentCount: item.commentCount,
                        commentItem: item.firstComment,
                        onClickWriteComment: onClickWriteComment
                    )
                    .onTapGesture {
                        if item.commentCount > 0 {
                            onClickComment()
                        }
                    }
                }
            } else {
                CreatorCommunityAllItemLockView(
                    price: item.price,
                    onClickPurchaseContent: onClickPurchaseContent)
            }
        }
        .padding(.horizontal, 8)
        .padding(.vertical, 11)
        .background(Color.gray22)
        .cornerRadius(5.3)
        .padding(.horizontal, 13.3)
    }
    
    private func estimatedHeight(for text: String, width: CGFloat) -> CGFloat {
        let textView = UITextView(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude))
        textView.font = UIFont.systemFont(ofSize: 13.3)
        textView.text = text
        return textView.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height
    }
}

struct CreatorCommunityAllItemView_Previews: PreviewProvider {
    static var previews: some View {
        CreatorCommunityAllItemView(
            item: GetCommunityPostListResponse(
                postId: 1,
                creatorId: 1,
                creatorNickname: "민하나",
                creatorProfileUrl: "https://test-cf.sodalive.net/profile/default-profile.png",
                imageUrl: "https://test-cf.sodalive.net/profile/default-profile.png",
                audioUrl: nil,
                content: "너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!너무 조하유 앞으로도 좋은 라이브 많이 들려주세요!",
                price: 10,
                date: "3일전",
                isCommentAvailable: false,
                isAdult: false,
                isLike: true,
                existOrdered: false,
                likeCount: 10,
                commentCount: 0,
                firstComment: nil
            ),
            onClickLike: {},
            onClickComment: {},
            onClickWriteComment: { _ in },
            onClickShowReportMenu: {},
            onClickPurchaseContent: {}
        )
    }
}
