import 'package:didvan/config/design_config.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/models/view/radar_category.dart';
import 'package:didvan/views/home/radar/radar_state.dart';
import 'package:didvan/views/widgets/animated_visibility.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class CategoriesList extends StatefulWidget {
  const CategoriesList({Key? key}) : super(key: key);

  @override
  State<CategoriesList> createState() => _CategoriesListState();
}

class _CategoriesListState extends State<CategoriesList> {
  final _scrollController = ScrollController();

  int _lastSelectedCategoryId = 0;

  @override
  void didUpdateWidget(covariant CategoriesList oldWidget) {
    final RadarState state = context.read<RadarState>();
    if (state.selectedCats.isNotEmpty &&
        _lastSelectedCategoryId != state.selectedCats.first.id) {
      _lastSelectedCategoryId = state.selectedCats.first.id;
      _scrollController.animateTo(
        state.selectedCats.first.id * 100,
        duration: DesignConfig.lowAnimationDuration,
        curve: Curves.easeIn,
      );
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    final MediaQueryData d = MediaQuery.of(context);
    final state = context.read<RadarState>();
    final isColapsed = state.isColapsed || state.searching || state.filtering;
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: AnimatedCrossFade(
        crossFadeState:
            isColapsed ? CrossFadeState.showSecond : CrossFadeState.showFirst,
        duration: DesignConfig.mediumAnimationDuration,
        reverseDuration: DesignConfig.lowAnimationDuration,
        sizeCurve: Curves.easeIn,
        firstChild: const SizedBox(),
        secondChild: Container(
          height: 60 + d.padding.top,
          decoration: BoxDecoration(
            color: Theme.of(context).colorScheme.surface,
            boxShadow: DesignConfig.defaultShadow,
          ),
          child: AnimatedVisibility(
            isVisible: isColapsed,
            duration: DesignConfig.mediumAnimationDuration,
            child: SingleChildScrollView(
              controller: _scrollController,
              // physics: const BouncingScrollPhysics(),
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.only(
                top: d.padding.top + 12,
                bottom: 12,
                right: 12,
              ),
              child: Row(
                children: [
                  _itemBuilder(
                    RadarCategory(title: 'همه', asset: '', id: 0),
                    context,
                  ),
                  for (var i = 0; i < state.categories.length; i++)
                    _itemBuilder(state.categories[i], context),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _itemBuilder(RadarCategory category, BuildContext context) {
    final state = context.read<RadarState>();
    return GestureDetector(
      onTap: () async {
        if (state.selectedCats.isNotEmpty &&
            state.selectedCats.first.id == category.id) return;
        state.selectedCats.clear();
        if (category.id != 0) state.selectedCats.add(category);
        await _scrollController.animateTo(
          category.id * 100,
          duration: DesignConfig.lowAnimationDuration,
          curve: Curves.easeIn,
        );
        state.getRadars(page: 1);
      },
      child: Container(
        margin: const EdgeInsets.only(left: 12),
        width: 100,
        padding: const EdgeInsets.all(4),
        alignment: Alignment.center,
        child: FittedBox(
          fit: BoxFit.scaleDown,
          child: DidvanText(
            category.title,
            fontWeight: FontWeight.w600,
            color: Theme.of(context).colorScheme.focusedBorder,
          ),
        ),
        decoration: BoxDecoration(
          color: state.selectedCats.length == 1 &&
                      state.selectedCats.contains(category) ||
                  category.id == 0 && state.selectedCats.isEmpty
              ? Theme.of(context).colorScheme.focused
              : null,
          border: Border.all(
            color: Theme.of(context).colorScheme.focusedBorder,
          ),
          borderRadius: DesignConfig.lowBorderRadius,
        ),
      ),
    );
  }
}
