//
//  WidgetListView.swift
//  Toolboxes
//
//  Created by 研发2组 on 2024/9/24.
//



import SwiftUI
import ActivityKit

struct WidgetListView: View {
    
    @State var data: [ String:String] = ["latitude":"\(0)","longitude":"\(0)","altitude":"\(0)"]
    @Environment(\.presentationMode) var presentationMode

    @State private var showBottomSheet = false
    
    var body: some View {
        GeometryReader { geometry in
            let totalWidth = geometry.size.width
            let spacing: CGFloat = 15
            let smallWidgetWidth = (totalWidth - spacing * 3) * 0.32
            let mediumWidgetWidth = totalWidth - smallWidgetWidth - spacing * 3
            
            VStack(spacing: 20.0) {
                
                HStack{
                    Button(action: {
                               presentationMode.wrappedValue.dismiss()
                           }) {
                               Image("nav_back")
                                   .foregroundColor(.black)
                           }
                    Spacer()
                    Text(L("Widgets List"))
                        .font(.system(size: 16, weight: .bold))
                        .foregroundColor(.black)
                    
                    Spacer()
                    
                }
                .padding(.horizontal,15.0)
                
                LazyVGrid(columns: [
                    GridItem(.fixed(smallWidgetWidth), spacing: spacing),
                    GridItem(.fixed(mediumWidgetWidth), spacing: spacing)
                ], spacing: spacing) {
                    VStack {
                        Button(
                            action: {
                                showBottomSheet.toggle()
                            }
                        ){
                            SquareWidgetView(title: "Widgets List", width: smallWidgetWidth, height: smallWidgetWidth) {
                                AltitudeSmallView(data: self.data)
                            }
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                    
                    VStack {
                        Button(
                            action: {
                                showBottomSheet.toggle()
                            }
                        ){
                            SquareWidgetView(title: "Widgets List", width: mediumWidgetWidth, height: smallWidgetWidth) {
                                AltitudeMediumView(data: self.data)
                            }
                        }
                    }
                }
                
                Spacer()
            }.overlay(
                Group {
                    if   showBottomSheet                      {
                        BottomSheetView(show: $showBottomSheet)
                            .frame(maxWidth: .infinity,maxHeight: .infinity)
                            .background(Color.black.opacity(0.3).edgesIgnoringSafeArea(.all))
                            .transition(.move(edge: .bottom))
                    }
                }
            )
        }
        .onAppear(){
            let appGroupDefaults = UserDefaults(suiteName: "group.com.yhgc.Toolboxes.identifier")
            let latitude = appGroupDefaults?.double(forKey: "latitude") ?? 0
            let longitude = appGroupDefaults?.double(forKey: "longitude") ?? 0
            let altitude = appGroupDefaults?.double(forKey: "altitude") ?? 0
            self.data = ["latitude":"\(latitude)","longitude":"\(longitude)","altitude":"\(altitude)"]
        }
        .edgesIgnoringSafeArea(.bottom)
        .navigationBarBackButtonHidden(true)
        .gradientBackground()
        
    }
}

struct SquareWidgetView<Content: View>: View {
    var title: String
    var width: CGFloat? = nil
    var height: CGFloat? = nil
    var content: Content
    
    
    init(title: String, width: CGFloat? = nil, height: CGFloat? = nil, @ViewBuilder content: () -> Content) {
        self.title = title
        self.width = width
        self.height = height
        // self.showBottomSheet = showBottomSheet
        self.content = content()
    }
    
    var body: some View {
        
        content
            .frame(width: width, height: height)
            .cornerRadius(20)
            .shadow(color: Color.black.opacity(0.1), radius: 10, x: 0, y: 2)
        
    }
}

struct MediumWidgetView<Content: View>: View {
    var title: String
    var width: CGFloat? = nil
    var height: CGFloat? = nil
    var content: Content
    @State private var showBottomSheet = false
    init(title: String, width: CGFloat? = nil, height: CGFloat? = nil, @ViewBuilder content: () -> Content) {
        self.title = title
        self.width = width
        self.height = height
        self.content = content()
    }
    
    var body: some View {
        content
            .frame(width: width, height: height)
            .cornerRadius(20)
            .shadow(color: Color.black.opacity(0.1), radius: 10, x: 0, y: 2)
    }
}



struct WidgetListView_Previews: PreviewProvider {
    static var previews: some View {
        WidgetListView(data: ["latitude":"222","longitude":"333333","altitude":"60"])
    }
}

struct BottomSheetView: View {
    @Binding var show: Bool
    var body: some View {
        VStack{
            Button(action: {
                //            withAnimation {
                show = false
                //            }
            }){
                
                ZStack{
                    
                } .frame(maxWidth: .infinity,maxHeight: .infinity)
            }
            //            .background(Color.red.opacity(0.5))
            //            .buttonStyle(StaticButtonStyle())
            .frame(maxWidth: .infinity,maxHeight: .infinity)
            
            VStack (spacing: 10){
                Spacer().frame(height: 10)
                //                Capsule()
                //                    .fill(Color.customBlack)
                //                    .frame(width: 50, height: 5)
                
                Spacer().frame(height: 10)
                ScrollView(.horizontal,showsIndicators: false){
                    HStack(alignment: .center, spacing: 20){
                        Spacer().frame(width: 20)
                        InstructionStepHView(step: "First step", image: "one", description: L("返回桌面\n长按桌面空白处"))
                        
                        
                        InstructionStepHView(step: "Second step", image: "two", description: L("点击右上角 + 号\n搜索“指南针”"))
                   
                        
                        InstructionStepHView(step: "Third step", image: "three", description: L("选择对应的尺寸\n点击“添加小组件”") )
                        
                        Spacer().frame(width: 15)
                    }
                }
                Spacer()
                Button(action: sendToBackground) {
                    Text("Setup widget")
                        .font(.headline)
                        .padding()
                        .frame(maxWidth: .infinity)
                        .background(Color.customdeepblue)
                        .foregroundColor(.white)
                        .cornerRadius(10)
                        .padding(.horizontal)
                }
                Spacer().frame(height: 30)
                
            }.frame(height: 480)
                .background(Color.customWhite)
                .cornerRadius(20)
            //                .gesture(
            //                                DragGesture(minimumDistance: 30)
            //                                    .onChanged { _ in
            //                                        // 当滑动改变时执行
            //                                        print("正在向下划")
            //                                    }
            //                                    .onEnded { _ in
            //                                        // 当滑动结束时执行
            //                                        print("向下划手势结束")
            ////                                                withAnimation {
            //                                            show = false
            ////                                                }
            //                                    }
            //                            )
            //                .allowsHitTesting(true)
            
        }.frame(maxWidth: .infinity,maxHeight: .infinity)
        
    }
    
    func sendToBackground() {
        show = false
        UIApplication.shared.perform(#selector(NSXPCConnection.suspend))
    }
}


struct InstructionStepHView: View {
    var step: String
    var image: String
    var description: String
    var imageSize: CGSize = CGSize(width: 120, height: 225)
    
    var body: some View {
        HStack(alignment: .center, spacing: 20){
            
            
            VStack(alignment: .center, spacing: 15) {
                Text(L(step))
                    .font(.system(size: 18, weight: .bold))
                    .foregroundColor(.customRed)
                    .multilineTextAlignment(.center)
                
                Text(description)
                    .font(.system(size: 15))
                    .foregroundColor(.customBlack)
                    .multilineTextAlignment(.center)
                
                Image(image)
                    .resizable()
                    .scaledToFit()
                    .frame(width: imageSize.width, height: imageSize.height)
            }.frame(maxWidth: .infinity, alignment: .center)
        }.frame(maxWidth: .infinity, alignment: .center)
        
    }
}


struct StaticButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .background(configuration.isPressed ? Color.black.opacity(0.3) : Color.clear)
            .foregroundColor(.white)
            .cornerRadius(10)
            .scaleEffect(configuration.isPressed ? 1.0 : 1.0)  // Maintain same scale
    }
}
