//
//  SearchView.swift
//  SodaLive
//
//  Created by klaus on 3/27/25.
//

import SwiftUI
import Kingfisher

struct SearchViewTabItem {
    let title: String
    let tab: SearchViewModel.CurrentTab
}

struct SearchView: View {
    
    @StateObject var viewModel = SearchViewModel()
    @State private var isFocused: Bool = false
    
    let tabItemList = [
        SearchViewTabItem(title: "통합", tab: .UNIFIED),
        SearchViewTabItem(title: "채널", tab: .CREATOR),
        SearchViewTabItem(title: "콘텐츠", tab: .CONTENT),
        SearchViewTabItem(title: "시리즈", tab: .SERIES)
    ]
    
    var body: some View {
        NavigationView {
            BaseView(isLoading: $viewModel.isLoading) {
                VStack(spacing: 0) {
                    HStack(spacing: 0) {
                        Button {
                            AppState.shared.back()
                        } label: {
                            Image("ic_back")
                                .resizable()
                                .frame(width: 20, height: 20)
                        }
                        .padding(13.3)
                        
                        HStack(spacing: 0) {
                            Image("ic_title_search_black")
                            
                            FocusedTextField(
                                text: $viewModel.keyword,
                                isFirstResponder: isFocused
                            )
                            .padding(.horizontal, 13.3)
                            .onAppear {
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                                    isFocused = true
                                }
                            }
                        }
                        .frame(height: 50)
                        .padding(.horizontal, 21.3)
                        .frame(maxWidth: .infinity)
                        .background(Color.gray22)
                        .clipShape(RoundedRectangle(cornerRadius: 6.7))
                        .overlay(
                            RoundedRectangle(cornerRadius: 6.7)
                                .strokeBorder(lineWidth: 1)
                                .foregroundColor(Color.graybb)
                        )
                    }
                    .padding(.trailing, 13.3)
                    
                    if !viewModel.searchUnifiedCreatorList.isEmpty ||
                        !viewModel.searchUnifiedContentList.isEmpty ||
                        !viewModel.searchUnifiedSeriesList.isEmpty {
                        ScrollView(.horizontal, showsIndicators: false) {
                            HStack(spacing: 8) {
                                ForEach(0..<tabItemList.count, id: \.self) { index in
                                    let tabItem = tabItemList[index]
                                    
                                    Text(tabItem.title)
                                        .font(.custom(Font.medium.rawValue,size: 16))
                                        .foregroundColor(
                                            viewModel.currentTab == tabItem.tab ?
                                                .button :
                                                    .graybb
                                        )
                                        .padding(.horizontal, 12)
                                        .onTapGesture {
                                            if viewModel.currentTab != tabItem.tab {
                                                viewModel.currentTab = tabItem.tab
                                            }
                                        }
                                }
                            }
                            .padding(.vertical, 15)
                            .padding(.horizontal, 13.3)
                        }
                        .padding(.bottom, 13.3)
                        
                        switch viewModel.currentTab {
                        case .UNIFIED:
                            SearchUnifiedView(
                                creatorList: viewModel.searchUnifiedCreatorList,
                                contentList: viewModel.searchUnifiedContentList,
                                searchList: viewModel.searchUnifiedSeriesList,
                                onTapMoreCreator: {
                                    viewModel.currentTab = .CREATOR
                                },
                                onTapMoreContent: {
                                    viewModel.currentTab = .CONTENT
                                },
                                onTapMoreSeries: {
                                    viewModel.currentTab = .SERIES
                                }
                            )
                            
                        case .CREATOR:
                            SearchCreatorListView(itemsList: viewModel.searchCreatorItemList)
                            
                        case .CONTENT:
                            SearchContentListView(itemsList: viewModel.searchContentItemList)
                            
                        case .SERIES:
                            SearchSeriesListView(itemsList: viewModel.searchSeriesItemList)
                        }
                    }
                    
                    if viewModel.searchUnifiedCreatorList.isEmpty &&
                        viewModel.searchUnifiedContentList.isEmpty &&
                        viewModel.searchUnifiedSeriesList.isEmpty &&
                        viewModel.keyword.count > 2 {
                        Text("검색 결과가 없습니다.")
                            .font(.custom(Font.medium.rawValue, size: 18.3))
                            .foregroundColor(.white)
                            .padding(.top, 20)
                    }
                    
                    Spacer()
                }
                .popup(isPresented: $viewModel.isShowPopup, type: .toast, position: .top, autohideIn: 2) {
                    GeometryReader { geo in
                        HStack {
                            Spacer()
                            Text(viewModel.errorMessage)
                                .padding(.vertical, 13.3)
                                .frame(width: geo.size.width - 66.7, alignment: .center)
                                .font(.custom(Font.medium.rawValue, size: 12))
                                .background(Color.button)
                                .foregroundColor(Color.white)
                                .multilineTextAlignment(.center)
                                .cornerRadius(20)
                                .padding(.top, 66.7)
                            Spacer()
                        }
                    }
                }
                .onAppear {
                    if viewModel.keyword.isEmpty {
                        viewModel.keyword = UserDefaults.string(forKey: .searchChannel)
                    }
                }
                .onTapGesture {
                    hideKeyboard()
                }
            }
        }
    }
}

#Preview {
    SearchView()
}