import 'package:flutter/material.dart';
import 'package:rasadyar_core/core.dart';

class BasePage extends GetView<BaseLogic> {
  const BasePage({
    super.key,
    this.routes,
    this.routesWidget,
    this.child,
    this.floatingActionButtonLocation,
    this.floatingActionButton,
    this.appBar,
    this.backGroundDecoration,
    this.onPopScopTaped,
    this.backId,
    this.onSearchChanged,
    this.onRefresh,
  });

  final List<String>? routes;
  final Widget? routesWidget;
  final Widget? child;
  final RAppBar? appBar;
  final BoxDecoration? backGroundDecoration;
  final FloatingActionButtonLocation? floatingActionButtonLocation;
  final Widget? floatingActionButton;
  final VoidCallback? onPopScopTaped;
  final int? backId;
  final void Function(String?)? onSearchChanged;
  final RefreshCallback? onRefresh;

  Widget _buildHeader() {
    if (appBar?.hasSearch == true) {
      controller.setSearchCallback(onSearchChanged);
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        routesWidget ?? ContainerBreadcrumb(routes: routes!),
        SearchWidget(),
      ],
    );
  }

  Widget _buildBody() {
    final content = [
      if (routes != null || routesWidget != null) _buildHeader(),
      if (child != null) Expanded(child: child!),
    ];

    if (onRefresh == null) {
      return Container(
        decoration: backGroundDecoration,
        child: Column(mainAxisAlignment: MainAxisAlignment.start, children: content),
      );
    } else {
      return RefreshIndicator.adaptive(
        triggerMode: RefreshIndicatorTriggerMode.anywhere,
        edgeOffset: 16.h,
        onRefresh: onRefresh ?? () async {},
        child: CustomScrollView(
          slivers: [
            SliverFillRemaining(
              child: Container(
                decoration: backGroundDecoration,
                child: Column(mainAxisAlignment: MainAxisAlignment.start, children: content),
              ),
            ),
          ],
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return _pageBuilder();
  }

  Widget _pageBuilder() {
    if (onPopScopTaped != null) {
      return PopScope(
        canPop: false,
        onPopInvokedWithResult: (didPop, result) {
          tLog("PopScope Tapped ==> $didPop");

          if (!didPop) {
            onPopScopTaped!();
          }
        },
        child: Scaffold(
          backgroundColor: AppColor.bgLight,
          appBar: appBar,
          body: _buildBody(),
          floatingActionButtonLocation: floatingActionButtonLocation,
          floatingActionButton: floatingActionButton,
        ),
      );
    } else {
      return Scaffold(
        backgroundColor: AppColor.bgLight,
        appBar: appBar,
        body: _buildBody(),
        floatingActionButtonLocation: floatingActionButtonLocation,
        floatingActionButton: floatingActionButton,
      );
    }
  }
}
