//
//  Screen.swift
//  Pods
//
//  Created by sophia on 5/2/25.
//

import SwiftUI

public struct Screen<Content: View>: View {
    // MARK: - Properties
    
    var backgroundColor: Color?
    var headerTransparent: Bool = false
    var fullScreenContent: Bool = false
    var tintColor: Color? = Colors.black17
    var isBack: Bool
    var headerType: HeaderType
    var verticalAlignment: VerticalAlignment
    var horizontalAlignment: HorizontalAlignment
    var title: String
    var titlePosition: TitlePosition
    var goBack: (() -> Void)?
    var scrollable: Bool
    var onContentLayout: ((CGRect) -> Void)?
    var useAvoidKeyboard: Bool
    var footer: (() -> AnyView)?
    var headerRight: (()->any View)? = {HeaderRight()}
    var animatedHeader: AnimatedHeader? = nil
    var layoutOffset: CGFloat
    var inputSearchProps: InputSearchProps?
    var fabProps: FabProps?
    var content: () -> Content
    
    public init(
        backgroundColor: Color? = nil,
        headerTransparent: Bool = false,
        fullScreenContent: Bool = false,
        tintColor: Color = Colors.black17,
        isBack: Bool = true,
        headerType: HeaderType = .default,
        verticalAlignment: VerticalAlignment = .top,
        horizontalAlignment: HorizontalAlignment = .leading,
        title: String = "Stack",
        titlePosition: TitlePosition = .left,
        goBack: (() -> Void)? = nil,
        scrollable: Bool = true,
        onContentLayout: ((CGRect) -> Void)? = nil,
        useAvoidKeyboard: Bool = true,
        footer: (() -> AnyView)? = nil,
        headerRight:  (()->any View)? = {HeaderRight()},
        animatedHeader: AnimatedHeader? = nil,
        layoutOffset: CGFloat = 56,
        inputSearchProps: InputSearchProps? = nil,
        fabProps: FabProps? = nil,
        @ViewBuilder content: @escaping () -> Content
    ) {
        self.backgroundColor = backgroundColor
        self.headerTransparent = headerTransparent
        self.fullScreenContent = fullScreenContent
        self.tintColor = tintColor
        self.isBack = isBack
        self.headerType = headerType
        self.verticalAlignment = verticalAlignment
        self.horizontalAlignment = horizontalAlignment
        self.title = title
        self.titlePosition = titlePosition
        self.goBack = goBack
        self.scrollable = scrollable
        self.onContentLayout = onContentLayout
        self.useAvoidKeyboard = useAvoidKeyboard
        self.footer = footer
        self.headerRight = headerRight
        self.animatedHeader = animatedHeader
        self.layoutOffset = layoutOffset
        self.inputSearchProps = inputSearchProps
        self.fabProps = fabProps
        self.content = content
    }
    
    @State private var scrollOffset: CGFloat = 0
    @State private var keyboardHeight: CGFloat = 0
    
    // MARK: - Body
    
    public var body: some View {
        GeometryReader { geometry in
            let topInset = geometry.safeAreaInsets.top
            let keyboardSize: CGFloat = useAvoidKeyboard ? max(keyboardHeight, 0) : 0
            let height = geometry.size.height
            let bottomInset = geometry.safeAreaInsets.bottom
            let screenHeight = height + topInset + bottomInset
            
            ZStack(alignment: .top) {
                // Background color
                (backgroundColor ?? Color.white)
                    .edgesIgnoringSafeArea(.all)
                
                VStack(spacing: 0) {
                    ZStack(alignment: fabProps?.position == .center ? .bottom : .bottomTrailing) {
                        VStack(alignment: horizontalAlignment, spacing: 0) {
                            if animatedHeader != nil || (headerTransparent && fullScreenContent) {
                                ZStack(alignment: .top) {
                                    // MARK: - Header
                                    Header(
                                        headerType: headerType,
                                        titlePosition: titlePosition,
                                        title: title,
                                        headerRight: headerRight,
                                        goBack: goBack,
                                        opacity: min(scrollOffset / 114, 1),
                                        animatedHeader: animatedHeader,
                                        scrollState: scrollOffset,
                                        inputSearchProps: inputSearchProps,
                                        tintColor: tintColor
                                    )
                                    
                                    .background(
                                        HeaderBackground(
                                            headerType: headerType,
                                            scrollState: scrollOffset,
                                            headerTransparent: headerTransparent,
                                            fullScreenContent: fullScreenContent
                                            
                                        )
                                        .overlay(animatedHeader?.composable(scrollOffset)
                                            .frame(maxWidth: .infinity)
                                            .aspectRatio(animatedHeader?.aspectRatio.value, contentMode: .fill)
                                        )
                                    ).zIndex(100)
                                    
                                    VStack {
                                        if scrollable {
                                            ScrollView(.vertical, showsIndicators: false) {
                                                VStack {
                                                    content()
                                                }
                                                .background(GeometryReader { geo -> Color in
                                                    DispatchQueue.main.async {
                                                        self.scrollOffset = -geo.frame(in: .global).origin.y
                                                    }
                                                    return Color.clear
                                                })
                                            }
                                        } else {
                                            content()
                                        }
                                    }
                                    .edgesIgnoringSafeArea(.all)
                                }
                            } else {
                                // MARK: - Header
                                Header(
                                    headerType: headerType,
                                    titlePosition: titlePosition,
                                    title: title,
                                    headerRight: headerRight,
                                    goBack: goBack,
                                    opacity: min(scrollOffset / 114, 1),
                                    animatedHeader: animatedHeader,
                                    scrollState: scrollOffset,
                                    inputSearchProps: inputSearchProps,
                                    tintColor: tintColor
                                )
                                .background(
                                    HeaderBackground(
                                        headerType: headerType,
                                        scrollState: scrollOffset,
                                        headerTransparent: headerTransparent,
                                        fullScreenContent: fullScreenContent
                                    )
                                    .edgesIgnoringSafeArea(.top)
                                )
                                
                                if scrollable {
                                    ScrollView(.vertical, showsIndicators: false) {
                                        VStack {
                                            content()
                                        }
                                        .background(GeometryReader { geo -> Color in
                                            DispatchQueue.main.async {
                                                self.scrollOffset = -geo.frame(in: .global).origin.y
                                            }
                                            return Color.clear
                                        })
                                    }
                                } else {
                                    content()
                                }
                            }
                        }
                        
                        if let fabProps = fabProps {
                            FloatingButton(
                                props: fabProps,
                                keyboardOffset: useAvoidKeyboard ? keyboardSize : 0,
                                scrollOffset: scrollOffset
                            )
                            .padding(.horizontal, Spacing.M)
                        }
                    }
                    
                    
                    // MARK: - Footer
                    if let footerView = footer?() {
                        Footer(footerView: footerView, keyboardSize: keyboardSize)
                    }
                }
            }
        }
    }
    
    // MARK: - Keyboard Handling
    
    private func observeKeyboard() {
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: .main) { notification in
            if useAvoidKeyboard,
               let endFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
                withAnimation(.easeOut(duration: 0.25)) {
                    keyboardHeight = UIScreen.main.bounds.height - endFrame.origin.y
                }
            }
        }
    }
}

// MARK: - Footer

struct Footer: View {
    var footerView: AnyView
    var keyboardSize: CGFloat

    var body: some View {
        VStack {
            footerView
        }
        .padding(.vertical, Spacing.S)
        .padding(.horizontal, Spacing.M)
        .padding(.bottom, keyboardSize)
        .background(Colors.black01)
        .overlay(
            Rectangle()
                .fill(Colors.black20.opacity(0.1))
                .frame(height: 4)
                .shadow(color: Colors.black20.opacity(0.2), radius: 10, y: -2),
            alignment: .top
        )
    }
}
