import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';

import '../../../models/lookup.dart';
import '../../../new_views/app_style/app_color.dart';
import '../../../providers/service_request_providers/commissioning_status_provider.dart';

class AssetStatusButtons extends StatefulWidget {
  final Function(Lookup?)? onSelect;
  final Lookup? initialValue;

  const AssetStatusButtons({Key? key, this.onSelect, this.initialValue}) : super(key: key);

  @override
  State<AssetStatusButtons> createState() => _AssetStatusButtonsState();
}

class _AssetStatusButtonsState extends State<AssetStatusButtons> {
  int _selectedIndex = 0;

  @override
  void initState() {
    super.initState();
    WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((timeStamp) {
      final provider = Provider.of<CommissioningStatusProvider>(context, listen: false);
      provider.getData().then((value) {
        if (widget.initialValue != null) {
          // Find matching item by id or value, not by object identity
          _selectedIndex = provider.items.indexWhere((item) =>
            (item.id != null && item.id == widget.initialValue!.id) ||
            (item.value != null && item.value == widget.initialValue!.value)
          );
          if (_selectedIndex == -1) _selectedIndex = 0;
          // Adjust for "All Assets" option at index 0
          _selectedIndex += 1;
        }
        setState(() {});
      });
    });
  }

  @override
  void didUpdateWidget(covariant AssetStatusButtons oldWidget) {
    if (widget.initialValue != oldWidget.initialValue) {
      final provider = Provider.of<CommissioningStatusProvider>(context, listen: false);
      if (widget.initialValue != null) {
        // Find matching item by id or value, not by object identity
        _selectedIndex = provider.items.indexWhere((item) =>
          (item.id != null && item.id == widget.initialValue!.id) ||
          (item.value != null && item.value == widget.initialValue!.value)
        );
        if (_selectedIndex == -1) {
          _selectedIndex = 0;
        } else {
          // Adjust for "All Assets" option at index 0
          _selectedIndex += 1;
        }
      } else {
        _selectedIndex = 0;
      }
      setState(() {});
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        context.translation.assetStatus.heading5(context).custom(color: AppColor.textStyleColor(context)),
        8.height,
        Consumer<CommissioningStatusProvider>(
          builder: (context, snapshot, _) {
            return snapshot.loading
                ? Shimmer(
                    gradient: const LinearGradient(colors: [AppColor.primary40, AppColor.primary50, AppColor.primary60]),
                    child: Row(
                      children: [
                        const _Skelton().expanded,
                        8.width,
                        const _Skelton().expanded,
                        8.width,
                        const _Skelton().expanded,
                      ],
                    ),
                  )
                : SizedBox(
                    height: 36.toScreenHeight,
                    child: ListView.separated(
                      itemCount: snapshot.items.length + 1,
                      scrollDirection: Axis.horizontal,
                      shrinkWrap: true,
                      padding: EdgeInsetsDirectional.only(start: 0.toScreenWidth),
                      separatorBuilder: (cxt, index) => 8.width,
                      itemBuilder: (context, index) => Container(
                        margin: EdgeInsets.symmetric(horizontal: 0.toScreenWidth),
                        padding: EdgeInsets.symmetric(vertical: 8.toScreenHeight, horizontal: 12.toScreenWidth),
                        alignment: Alignment.center,
                        // foregroundDecoration: _selectedIndex != index
                        //     ? null
                        //     : ShapeDecoration(
                        //         color: (context.isDark ? AppColor.neutral30 : AppColor.neutral50).withOpacity(0.1),
                        //         shape: RoundedRectangleBorder(
                        //           side: BorderSide(width: 1, color: AppColor.blueStatus(context)),
                        //           borderRadius: BorderRadius.circular(7),
                        //         ),
                        //       ),
                        decoration: ShapeDecoration(
                          color: AppColor.background(context),
                          shape: RoundedRectangleBorder(
                            side: BorderSide(width: 1, color: _selectedIndex == index ? AppColor.primary10 : AppColor.border2Color(context)),
                            // side: _selectedIndex == index ? BorderSide(width: 1, color: AppColor.blueStatus(context)) : BorderSide.none,
                            borderRadius: BorderRadius.circular(6),
                          ),
                          shadows: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 14, offset: const Offset(0, 0), spreadRadius: 0)],
                        ),
                        child: (index == 0 ? "All Assets" : snapshot.items[index - 1].name)!.tinyFont(context).custom(

                            // color: AppColor.filterButtonTextColor(context)

                            color: _selectedIndex == index ? AppColor.primary10 : AppColor.filterButtonTextColor(context)),
                      ).onPress(() {
                        setState(() {
                          _selectedIndex = index;
                        });
                        widget.onSelect!(index == 0 ? null : snapshot.items[index - 1]);
                      }),
                    ),
                  );
          },
        ),
      ],
    );
  }
}

class _Skelton extends StatelessWidget {
  const _Skelton({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColor.neutral50.withOpacity(0.05),
        borderRadius: BorderRadius.circular(7),
      ),
    );
  }
}
