// Vertical pager layout adapted from VTabView by Lorenzo Fiamingo:
// https://github.com/lorenzofiamingo/swiftui-vertical-tab-view/blob/main/Sources/VTabView/VTabView.swift

import SwiftUI
@_spi(Advanced) import SwiftUIIntrospect
#if SWIFT_PACKAGE
import react_native_pager_view
#endif

struct PagerView: View {
  @ObservedObject var props: PagerViewProps
  @State private var scrollDelegate: PagerScrollDelegate = {
    if #available(iOS 16, *) {
      return PagerScrollDelegate()
    }
    // iOS 15 only, see PagerViewIOS15Compat.swift (delete together with the iOS 15 support).
    return PagerScrollDelegateIOS15()
  }()
  @State private var gestureObserver = PagerGestureObserver()
  @State private var didEmitInitialPageSelection = false
  weak var delegate: PagerViewProviderDelegate?

  @Weak var collectionView: UICollectionView?

  private var isVertical: Bool {
    props.orientation == .vertical
  }

  private func applyScrollEnabled(_ scrollEnabled: Bool) {
    collectionView?.isScrollEnabled = scrollEnabled
    // iOS 15 only, see PagerViewIOS15Compat.swift (delete together with the iOS 15 support).
    PagerViewIOS15Compat.applyScrollEnabled(scrollEnabled, to: collectionView)
  }

  private func applyOverdrag(_ overdrag: Bool) {
    collectionView?.bounces = overdrag
    // iOS 15 only, see PagerViewIOS15Compat.swift (delete together with the iOS 15 support).
    PagerViewIOS15Compat.applyOverdrag(overdrag, to: collectionView)
  }

  /// A direct slide moves the page it leaves into its passing page, see
  /// `PagerViewProvider.slideDirectly(to:after:)`.
  private func pageView(at index: Int, child: IdentifiablePlatformView) -> UIView? {
    guard let transition = props.pageTransition else {
      return child.view
    }
    if index == transition.passingPage {
      return transition.leftPage
    }
    return child.view === transition.leftPage ? nil : child.view
  }

  /// Animates to the target once TabView has shown the jump to the passing page,
  /// which an animation in the same update would scroll through instead.
  private func slide(_ transition: PageTransition) {
    DispatchQueue.main.async { [props] in
      guard props.pageTransition?.id == transition.id else {
        return
      }
      // React can remove the target before the slide starts.
      guard props.children.indices.contains(transition.targetPage) else {
        props.pageTransition = nil
        delegate?.onPageSelected(position: props.currentPage)
        return
      }
      props.pageTransition?.isSliding = true
      withAnimation {
        props.currentPage = transition.targetPage
      }
    }
  }

  var body: some View {
    GeometryReader { proxy in
      TabView(selection: $props.currentPage) {
        ForEach(Array(props.children.enumerated()), id: \.element.id) { index, child in
          RepresentableView(view: pageView(at: index, child: child))
            .frame(width: proxy.size.width, height: proxy.size.height)
            .rotationEffect(isVertical ? .degrees(-90) : .zero)
            .tag(index)
        }
      }
      .id(props.children.count)
      .background(.clear)
      .tabViewStyle(.page(indexDisplayMode: .never))
      .frame(
        width: isVertical ? proxy.size.height : proxy.size.width,
        height: isVertical ? proxy.size.width : proxy.size.height
      )
      .rotationEffect(isVertical ? .degrees(90) : .zero, anchor: .topLeading)
      .offset(x: isVertical ? proxy.size.width : 0)
      .ignoresSafeArea()
      .environment(\.layoutDirection, props.layoutDirection.converted)
      .introspect(.tabView(style: .page), on: .iOS(.v14...)) { collectionView in
        self.collectionView = collectionView
        props.collectionView = collectionView
        applyOverdrag(props.overdrag)
        applyScrollEnabled(props.scrollEnabled)
        collectionView.keyboardDismissMode = props.keyboardDismissMode
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false

        if #available(iOS 26.0, *) {
          // The top edge effect can obscure pages beneath transparent headers.
          collectionView.topEdgeEffect.isHidden = true

          // The vertical pager rotates this horizontal scroll view by 90 degrees.
          // Native edge effects would rotate with it and cover the page sideways.
          if isVertical {
            collectionView.bottomEdgeEffect.isHidden = true
            collectionView.leftEdgeEffect.isHidden = true
            collectionView.rightEdgeEffect.isHidden = true
          }
        }

        // Install once per collection view. This closure re-runs on every
        // layout pass, and `originalDelegate == nil` cannot tell "not installed
        // yet" from "installed, but the weak reference died" - so once it died
        // we re-adopted `collectionView.delegate`, which by then is this object
        // (or a proxy forwarding back to it). Either way the delegate chain
        // becomes a cycle and recurses until the stack overflows.
        if scrollDelegate.installedCollectionView !== collectionView {
          scrollDelegate.originalDelegate = collectionView.delegate
          scrollDelegate.delegate = delegate
          scrollDelegate.installedCollectionView = collectionView
          scrollDelegate.selectedPage = { [props] in
            props.mirroredPage(props.clampedCurrentPage)
          }
          scrollDelegate.onRest = { [props] restedPage in
            // The page is physical. Read it here, before a change to the
            // pages can shift what it mirrors to.
            let page = props.mirroredPage(restedPage)
            // The jump to the passing page rests too, before the slide starts.
            if props.pageTransition?.isSliding == true {
              props.pageTransition = nil
            }
            // Read the selection on the next pass, once TabView has applied it.
            DispatchQueue.main.async {
              // A page the pager is only passing through is not a rest.
              guard page == props.clampedCurrentPage else {
                return
              }
              props.resignFirstResponder(outsidePage: page)
            }
          }
          collectionView.delegate = scrollDelegate
        }

        gestureObserver.attach(to: collectionView)
        // iOS 15 only, see PagerViewIOS15Compat.swift (delete together with the iOS 15 support).
        PagerViewIOS15Compat.attachGestureObserver(gestureObserver, to: collectionView)
        gestureObserver.currentPage = props.currentPage
        gestureObserver.layoutDirection = props.layoutDirection
        gestureObserver.orientation = props.orientation
      }
    }
    // GeometryReader is the root since the vertical layout; without this it
    // honours the keyboard region and pages get framed to the shrunk proxy.
    .ignoresSafeArea()
    .onAppear {
      // Apply initial prop values that .onChange won't catch
      // (.onChange only fires on changes, not on initial values)
      DispatchQueue.main.async {
        applyScrollEnabled(props.scrollEnabled)
        applyOverdrag(props.overdrag)
        // iOS 15 only: the embedded scroll views may not exist yet when introspected.
        PagerViewIOS15Compat.attachGestureObserver(gestureObserver, to: collectionView)
      }

      // `onChange` does not fire for the initial `currentPage` value. Emit the
      // initial selection once so React Native receives `onPageSelected` for
      // `initialPage`, just as it does for subsequent page changes.
      if !didEmitInitialPageSelection && props.currentPage >= 0 {
        didEmitInitialPageSelection = true
        delegate?.onPageSelected(position: props.currentPage)
      }
    }
    .onChange(of: props.children) { newValue in
      if props.currentPage >= newValue.count && !newValue.isEmpty {
        props.currentPage = newValue.count - 1
      }
    }
    .onChange(of: props.currentPage) { newValue in
      gestureObserver.currentPage = newValue
      if let transition = props.pageTransition,
         !transition.isSliding,
         transition.passingPage == newValue {
        slide(transition)
        return
      }
      delegate?.onPageSelected(position: newValue)
    }
    .onChange(of: props.scrollEnabled) { newValue in
      applyScrollEnabled(newValue)
    }
    .onChange(of: props.overdrag) { newValue in
      applyOverdrag(newValue)
    }
    .onChange(of: props.keyboardDismissMode) { newValue in
      collectionView?.keyboardDismissMode = newValue
    }
  }
}
