import 'package:didvan/models/enums.dart';
import 'package:didvan/providers/core.dart';
import 'package:didvan/views/widgets/state_handlers/empty_connection.dart';
import 'package:flutter/material.dart';

class SliverStateHandler<T extends CoreProvier> extends SliverList {
  final T state;
  final Widget Function(BuildContext context, T state, int index) builder;
  final int childCount;
  final VoidCallback onRetry;
  final bool enableEmptyState;
  final Widget? emptyState;
  final Widget? placeholder;
  final EdgeInsets? itemPadding;
  final bool centerEmptyState;
  final bool hasConstraints;
  final int placeholderCount;
  final double? paddingEmptyState;
  SliverStateHandler({
    Key? key,
    required this.state,
    required this.builder,
    required this.childCount,
    required this.onRetry,
    this.itemPadding,
    this.placeholder,
    this.emptyState,
    this.enableEmptyState = false,
    this.centerEmptyState = true,
    this.hasConstraints = false,
    this.placeholderCount = 3,
    this.paddingEmptyState,
  }) : super(
          key: key,
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              final deviceHight = MediaQuery.of(context).size.height;
              if (state.appState == AppState.failed) {
                return Padding(
                  padding: EdgeInsets.only(
                    top: centerEmptyState ? deviceHight / 4 : deviceHight / 8,
                    bottom: 20,
                  ),
                  child: EmptyConnection(onRetry: onRetry),
                );
              }
              if (enableEmptyState && state.appState == AppState.idle) {
                return Padding(
                  padding: EdgeInsets.only(
                    top: paddingEmptyState ??
                        (centerEmptyState ? deviceHight / 4 : deviceHight / 8),
                    bottom: 20,
                  ),
                  child: emptyState,
                );
              }
              if (state.appState == AppState.busy) {
                return Padding(
                  padding: itemPadding ?? const EdgeInsets.all(0),
                  child: placeholder,
                );
              }
              return Padding(
                padding: itemPadding ?? const EdgeInsets.all(0),
                child: builder(context, state, index),
              );
            },
            childCount: state.appState == AppState.idle
                ? enableEmptyState
                    ? 1
                    : childCount
                : state.appState == AppState.busy
                    ? placeholderCount
                    : 1,
          ),
        );
}
