import 'dart:async';
import 'package:didvan/views/home/new_statistic/statistics_details/stat_cats_general_state.dart';
import 'package:didvan/views/home/new_statistic/widgets/general_stat_card.dart';
import 'package:didvan/views/widgets/didvan/card.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/search_field.dart';
import 'package:didvan/views/widgets/shimmer_placeholder.dart';
import 'package:didvan/views/widgets/state_handlers/empty_result.dart';
import 'package:didvan/views/widgets/state_handlers/state_handler.dart';
import 'package:flutter/material.dart';
import 'package:persian_number_utility/persian_number_utility.dart';
import 'package:provider/provider.dart';

class StatGeneralScreen extends StatefulWidget {
  final Map pageData;

  const StatGeneralScreen({super.key, required this.pageData});

  @override
  State<StatGeneralScreen> createState() => _StatGeneralScreenState();
}

class _StatGeneralScreenState extends State<StatGeneralScreen> {
  final ScrollController _scrollController = ScrollController();
  int pageNumber = 1;
  Timer? _timer;
  final _focusNode = FocusNode();

  @override
  void initState() {
    Future.delayed(Duration.zero, () {
      final state = context.read<StatGeneralScreenState>();
      state.getGeneralStatContent(page: 1, id: widget.pageData['id']);
      state.cat = widget.pageData['id'];
    });

    _scrollController.addListener(_onScroll);
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent) {
      pageNumber++;
      if (context.read<StatGeneralScreenState>().lastPage >= pageNumber) {
        context
            .read<StatGeneralScreenState>()
            .getGeneralStatContent(page: pageNumber, id: widget.pageData['id']);
      }
    }
  }

  void _onChanged(String value) {
    final state = context.read<StatGeneralScreenState>();
    if (value.length < 3 && value.isNotEmpty || state.lastSearch == value) {
      return;
    }
    _timer?.cancel();
    _timer = Timer(const Duration(seconds: 1), () {
      state.search = value;
      state.getGeneralStatContent(page: 1, id: widget.pageData['id']);
    });
  }

  @override
  Widget build(BuildContext context) {
    var time = context.read<StatGeneralScreenState>().time;
    var source = context.read<StatGeneralScreenState>().source;

    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        scrolledUnderElevation: 0.0,
        backgroundColor: Theme.of(context).colorScheme.surface,
        title: DidvanText(
          widget.pageData['title'],
          style: Theme.of(context).textTheme.bodyLarge,
          fontSize: 20,
        ),
      ),
      body: Column(
        children: [
          Container(
            height: 80,
            color: Theme.of(context).colorScheme.surface,
            padding:
                const EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0),
            child: SearchField(
              title: widget.pageData['title'],
              onChanged: _onChanged,
              focusNode: _focusNode,
              value: context.watch<StatGeneralScreenState>().lastSearch,
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(
                left: 8.0, top: 12.0, bottom: 8.0, right: 8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                DidvanText(widget.pageData["id"] == 1 ? "منبع: $source" : ""),
                if (time != null)
                  DidvanText(
                    DateTime.parse(time).toPersianDate(
                        showTime: true, changeDirectionShowTimw: false),
                  ),
              ],
            ),
          ),
          StateHandler<StatGeneralScreenState>(
            onRetry: context.read<StatGeneralScreenState>().init,
            state: context.watch<StatGeneralScreenState>(),
            emptyState: EmptyResult(
              onNewSearch: () => _focusNode.requestFocus(),
            ),
            enableEmptyState:
                context.watch<StatGeneralScreenState>().contents.isEmpty,
            topPadding: 16,
            placeholder: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                placeHolder,
                const SizedBox(
                  height: 8,
                ),
                placeHolder,
                const SizedBox(
                  height: 8,
                ),
              ],
            ),
            builder: (context, state) => Expanded(
              child: ListView.builder(
                controller: _scrollController,
                physics: const ClampingScrollPhysics(),
                itemCount: state.contents.length,
                itemBuilder: (context, index) => NewStatisticOverviewCard(
                  statistic: state.contents[index],
                  onMarkChanged: state.changeMark,
                  isMarked: state.contents[index].marked,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  static Widget get placeHolder => const Column(
        children: [
          DidvanCard(
            child: Column(
              children: [
                SizedBox(height: 4),
                Row(
                  children: [
                    ShimmerPlaceholder(width: 80, height: 16),
                    Spacer(),
                    ShimmerPlaceholder(width: 50, height: 14),
                    SizedBox(width: 8),
                    ShimmerPlaceholder(width: 50, height: 16),
                  ],
                ),
                SizedBox(height: 16),
                Row(
                  children: [
                    ShimmerPlaceholder(width: 150, height: 12),
                    Spacer(),
                    ShimmerPlaceholder(width: 80, height: 12),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 20),
          DidvanCard(
            child: Column(
              children: [
                SizedBox(height: 4),
                Row(
                  children: [
                    ShimmerPlaceholder(width: 80, height: 16),
                    Spacer(),
                    ShimmerPlaceholder(width: 50, height: 14),
                    SizedBox(width: 8),
                    ShimmerPlaceholder(width: 50, height: 16),
                  ],
                ),
                SizedBox(height: 16),
                Row(
                  children: [
                    ShimmerPlaceholder(width: 150, height: 12),
                    Spacer(),
                    ShimmerPlaceholder(width: 80, height: 12),
                  ],
                ),
              ],
            ),
          ),
        ],
      );
}
