import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/widgets/custom_error_screen.dart';
import 'package:niogu_app/core/router/app_route.dart';
import 'package:niogu_app/core/widgets/custom_empty_screen.dart';
import 'package:niogu_app/core/widgets/custom_selectable_item.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/features/goods/raw_materials/domain/entities/raw_material.dart';
import 'package:niogu_app/features/goods/raw_materials/presentation/providers/raw_material_provider.dart';
import 'package:niogu_app/features/outlets/presentation/providers/outlet_provider.dart';
import 'package:sizer/sizer.dart';

class RawMaterialChoiceScreen extends ConsumerStatefulWidget {
  const RawMaterialChoiceScreen({super.key});

  @override
  ConsumerState<RawMaterialChoiceScreen> createState() =>
      _RawMaterialChoiceScreenState();
}

class _RawMaterialChoiceScreenState
    extends ConsumerState<RawMaterialChoiceScreen>
    with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  String? _selectedItem;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final filteredRawMaterialState = ref.watch(
      filteredRawMaterialChoiceProvider,
    );

    final rawMaterialEmptyState = ref.watch(rawMaterialChoiceEmptyProvider);

    return filteredRawMaterialState.when(
      data: (rawMaterials) {
        switch (rawMaterialEmptyState) {
          case RawMaterialChoiceEmpty.loading:
            return const SizedBox();
          case RawMaterialChoiceEmpty.empty_database:
            return CustomEmptyScreen(
              title: "Tidak Ada Bahan Baku",
              body: "Belum ada bahan baku yang tersedia",
            );
          case RawMaterialChoiceEmpty.empty_search_result:
            return const CustomEmptyScreen(body: "Bahan Baku Tidak Ditemukan");
          case RawMaterialChoiceEmpty.has_data:
            return Stack(
              children: [
                ListView.builder(
                  padding: EdgeInsets.all(4.w),
                  itemCount: rawMaterials.length,
                  itemBuilder: (context, index) {
                    final rawMaterial = rawMaterials[index];

                    return CustomSelectableItem(
                      id: rawMaterial.id,
                      title: rawMaterial.name,
                      subtitle:
                          "Jumlah Produk : ${rawMaterial.countProductUsage}",
                      isSelected: _selectedItem == rawMaterial.id,
                      onTap: () {
                        setState(() {
                          _selectedItem = rawMaterial.id;
                        });
                      },
                    );
                  },
                ),

                Positioned(
                  bottom: 10.h,
                  right: 4.w,
                  width: 12.5.w,
                  height: 12.5.w,
                  child: FloatingActionButton(
                    heroTag: "btn_edit_raw_material",
                    onPressed: _selectedItem == null
                        ? null
                        : () async {
                            FocusScope.of(context).unfocus();

                            final alreadyProduct = await ref
                                .read(rawMaterialRepositoryProvider)
                                .checkAlreadyRawMaterialByOutlet(
                                  _selectedItem!,
                                );

                            if (alreadyProduct) {
                              CustomSnackbar.showWarning(
                                context,
                                "Bahan baku ini telah tersedia di outlet ini",
                              );
                              return;
                            }

                            final isMainOutlet = await ref
                                .read(outletRepositoryProvider)
                                .fetchIsMainOutlet();

                            await Future.delayed(
                              const Duration(milliseconds: 400),
                            );

                            context.pushNamed(
                              AppRoute.editRawMaterialScreen,
                              pathParameters: {"id": _selectedItem!},
                              extra: {
                                "is_main_outlet": isMainOutlet,
                                "is_editing": false,
                              },
                            );
                          },
                    backgroundColor: _selectedItem == null
                        ? Colors.grey.shade300
                        : AppColor.primaryColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(2.5.w),
                    ),
                    elevation: 0,
                    child: Icon(
                      Icons.keyboard_arrow_right,
                      color: Colors.white,
                      size: 8.w,
                    ),
                  ),
                ),
              ],
            );
        }
      },
      error: (error, stackTrace) =>
          CustomErrorScreen(message: "Ups, terjadi kesalahan", onRefresh: () {}),
      loading: () => const SizedBox(),
    );
  }
}
