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_snackbar.dart';
import 'package:niogu_app/features/goods/products/domain/entities/product.dart';
import 'package:niogu_app/features/goods/products/presentation/providers/product_provider.dart';
import 'package:niogu_app/core/widgets/custom_selectable_item.dart';
import 'package:niogu_app/features/outlets/presentation/providers/outlet_provider.dart';
import 'package:sizer/sizer.dart';

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

  @override
  ConsumerState<ProductChoiceScreen> createState() =>
      _ProductChoiceScreenState();
}

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

  String? _selectedItem;

  @override
  Widget build(BuildContext context) {
    super.build(context);

    final filteredProductState = ref.watch(filteredProductChoiceProvider);

    final productEmptyState = ref.watch(productChoiceEmptyProvider);

    return filteredProductState.when(
      data: (products) {
        switch (productEmptyState) {
          case ProductChoiceEmpty.loading:
            return const SizedBox();
          case ProductChoiceEmpty.empty_database:
            return CustomEmptyScreen(
              title: "Tidak Ada Produk",
              body: "Belum ada produk yang tersedia",
            );
          case ProductChoiceEmpty.empty_search_result:
            return const CustomEmptyScreen(body: "Produk Tidak Ditemukan");
          case ProductChoiceEmpty.has_data:
            return Stack(
              children: [
                ListView.builder(
                  padding: EdgeInsets.all(4.w),
                  itemCount: products.length,
                  itemBuilder: (context, index) {
                    final product = products[index];

                    final hasVariant = product.hasVariant;

                    return CustomSelectableItem(
                      id: product.id,
                      title: product.name,
                      subtitle: hasVariant
                          ? "Produk memiliki varian"
                          : "Produk tanpa varian",
                      imagePath: product.imagePath,
                      isSelected: _selectedItem == product.id,
                      onTap: () {
                        setState(() {
                          _selectedItem = product.id;
                        });
                      },
                    );
                  },
                ),

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

                            final alreadyProduct = await ref
                                .read(productRepositoryProvider)
                                .checkAlreadyProductByOutlet(_selectedItem!);

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

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

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

                            context.pushNamed(
                              AppRoute.editProductScreen,
                              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(),
    );
  }
}
