//
//  ContentByChannelView.swift
//  SodaLive
//
//  Created by klaus on 2/20/25.
//

import SwiftUI
import Kingfisher

struct ContentByChannelView: View {
    
    @AppStorage("token") private var token: String = UserDefaults.string(forKey: UserDefaultsKey.token)
    
    let title: String
    let creatorList: [ContentCreatorResponse]
    let contentList: [GetAudioContentRankingItem]
    let onClickCreator: (Int) -> Void
    
    @State private var selectedCreatorId = 0
    
    let columns = [
        GridItem(.flexible(), spacing: 13.3),
        GridItem(.flexible(), spacing: 13.3)
    ]
    
    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            Text(title)
                .font(.custom(Font.bold.rawValue, size: 18.3))
                .foregroundColor(.grayee)
                .padding(.horizontal, 13.3)
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 22) {
                    ForEach(0..<creatorList.count, id: \.self) { index in
                        let item = creatorList[index]
                        
                        ContentCreatorView(
                            isSelected: item.creatorId == selectedCreatorId,
                            item: item
                        )
                        .onTapGesture {
                            let creatorId = item.creatorId
                            selectedCreatorId = creatorId
                            onClickCreator(creatorId)
                        }
                    }
                }
                .padding(.horizontal, 13.3)
            }
            
            LazyVGrid(columns: columns, spacing: 13.3) {
                ForEach(0..<contentList.count, id: \.self) { index in
                    let content = contentList[index]
                    
                    VStack(alignment: .leading, spacing: 8) {
                        ZStack(alignment:.bottom) {
                            GeometryReader { geometry in
                                KFImage(URL(string: content.coverImageUrl))
                                    .cancelOnDisappear(true)
                                    .resizable()
                                    .scaledToFill()
                                    .frame(width: geometry.size.width, height: geometry.size.width)
                                    .clipShape(RoundedRectangle(cornerRadius: 5.3))
                                    .clipped()
                            }
                            .aspectRatio(1, contentMode: .fit)
                            
                            HStack(spacing: 0) {
                                HStack(spacing: 2) {
                                    if content.price > 0 {
                                        Image("ic_card_can_gray_32")
                                    }
                                    
                                    Text(content.price > 0 ? "\(content.price)" : "무료")
                                        .font(.custom(Font.medium.rawValue, size: 12))
                                        .foregroundColor(Color.white)
                                }
                                .padding(4)
                                .background(Color.gray33.opacity(0.7))
                                .cornerRadius(10)
                                
                                Spacer()
                                
                                Text(content.duration)
                                    .font(.custom(Font.medium.rawValue, size: 12))
                                    .foregroundColor(Color.white)
                                    .padding(4)
                                    .background(Color.gray33.opacity(0.7))
                                    .cornerRadius(10)
                            }
                            .padding(.horizontal, 2.7)
                            .padding(.bottom, 2.7)
                        }
                        
                        Text(content.title)
                            .font(.custom(Font.medium.rawValue, size: 13.3))
                            .foregroundColor(.grayd2)
                            .lineLimit(1)
                        
                        HStack(spacing: 5.3) {
                            KFImage(URL(string: content.creatorProfileImageUrl))
                                .cancelOnDisappear(true)
                                .downsampling(size: CGSize(width: 21, height: 21))
                                .resizable()
                                .frame(width: 21, height: 21)
                                .clipShape(Circle())
                                .clipped()
                            
                            Text(content.creatorNickname)
                                .font(.custom(Font.medium.rawValue, size: 10))
                                .foregroundColor(.gray77)
                        }
                        .onTapGesture {
                            if !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                                AppState.shared
                                    .setAppStep(step: .creatorDetail(userId: content.creatorId))
                            } else {
                                AppState.shared
                                    .setAppStep(step: .login)
                            }
                        }
                    }
                    .onTapGesture {
                        if !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                            AppState.shared
                                .setAppStep(step: .contentDetail(contentId: content.contentId))
                        } else {
                            AppState.shared
                                .setAppStep(step: .login)
                        }
                    }
                }
            }
            .padding(.horizontal, 13.3)
        }
        .onAppear {
            if !self.creatorList.isEmpty {
                selectedCreatorId = creatorList[0].creatorId
            }
        }
    }
}

#Preview {
    ContentByChannelView(
        title: "채널별 인기 콘텐츠",
        creatorList: [
            ContentCreatorResponse(
                creatorId: 1,
                creatorNickname: "유저1",
                creatorProfileImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png"
            ),
            ContentCreatorResponse(
                creatorId: 2,
                creatorNickname: "유저2",
                creatorProfileImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png"
            )
        ],
        contentList: [
            GetAudioContentRankingItem(
                contentId: 1,
                title: "안녕하세요 오늘은 커버곡을 들려드릴께요....안녕하세요 오늘은 커버곡을 들려드릴께요....",
                coverImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png",
                themeStr: "커버곡",
                price: 100,
                duration: "00:30:20",
                creatorId: 1,
                creatorNickname: "유저1",
                creatorProfileImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png"
            ),
            GetAudioContentRankingItem(
                contentId: 2,
                title: "안녕하세요 오늘은 커버곡을 들려드릴께요....",
                coverImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png",
                themeStr: "커버곡",
                price: 0,
                duration: "00:30:20",
                creatorId: 1,
                creatorNickname: "유저1",
                creatorProfileImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png"
            ),
            GetAudioContentRankingItem(
                contentId: 3,
                title: "안녕하세요 오늘은 커버곡을 들려드릴께요....안녕하세요 오늘은 커버곡을 들려드릴께요....",
                coverImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png",
                themeStr: "커버곡",
                price: 50,
                duration: "00:30:20",
                creatorId: 1,
                creatorNickname: "유저1",
                creatorProfileImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png"
            ),
            GetAudioContentRankingItem(
                contentId: 4,
                title: "안녕하세요 오늘은 커버곡을 들려드릴께요....안녕하세요 오늘은 커버곡을 들려드릴께요....",
                coverImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png",
                themeStr: "커버곡",
                price: 50,
                duration: "00:30:20",
                creatorId: 1,
                creatorNickname: "유저1",
                creatorProfileImageUrl: "https://test-cf.sodalive.net/profile/default-profile.png"
            )
        ]
    ) { _ in }
}
