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_font_size.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/utils/extension_format.dart';
import 'package:niogu_app/core/enums/item_type.dart';
import 'package:niogu_app/core/widgets/custom_empty_screen.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/select_item_shimmer.dart';
import 'package:niogu_app/features/stock_in/domain/entities/stock_in.dart';
import 'package:niogu_app/features/stock_in/presentation/provider/stock_in_provider.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/checkbox_button.dart';
import 'package:sizer/sizer.dart';

class DisplayRawMaterialScreen extends ConsumerStatefulWidget {
  final SelectedItemType type;

  DisplayRawMaterialScreen({super.key, required this.type});

  @override
  ConsumerState<DisplayRawMaterialScreen> createState() =>
      DisplayRawMaterialScreenState();
}

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

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  void _toggleSelectAll(List<DisplayItem> rawMaterials) {
    final selectedItemState = ref.read(selectedItemProvider(widget.type));

    final selectedItems = selectedItemState.values.where((item) {
      return item.itemType == ItemType.raw_material && item.type == widget.type;
    }).toList();

    if (selectedItems.isNotEmpty &&
        (rawMaterials.length == selectedItems.length)) {
      ref
          .read(selectedItemProvider(widget.type).notifier)
          .clear(ItemType.raw_material);
      return;
    }

    for (final rawMaterial in rawMaterials) {
      final selectedItem = SelectedItem(
        id: rawMaterial.id,
        itemType: ItemType.raw_material,
        itemId: rawMaterial.itemId,
        localImagePath: rawMaterial.localImagePath,
        name: rawMaterial.name,
        variantName: rawMaterial.variantName,
        costPrice: 0.0,
        purchasePrice: rawMaterial.purchasePrice,
        remainingStock: rawMaterial.remainingStock,
        unit: rawMaterial.unit,
        sellingPrice: rawMaterial.sellingPrice,
        type: widget.type,
      );

      ref
          .read(selectedItemProvider(widget.type).notifier)
          .toggleSelectAll(selectedItem);
    }
  }

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

    final bool isTablet = 100.w > 600;

    final rawMaterialState = ref.watch(
      filteredItemProvider(ItemType.raw_material),
    );

    final rawMaterialEmptyState = ref.watch(
      displayItemEmptyProvider(ItemType.raw_material),
    );

    final selectedItemState = ref.watch(selectedItemProvider(widget.type));

    final selectedItems = selectedItemState.values.where((item) {
      return item.itemType == ItemType.raw_material && item.type == widget.type;
    }).toList();

    return rawMaterialState.when(
      data: (rawMaterials) {
        final bool isAllSelected =
            selectedItems.isNotEmpty &&
            (rawMaterials.length == selectedItems.length);

        switch (rawMaterialEmptyState) {
          case DisplayItemEmpty.loading:
            return const SizedBox();

          case DisplayItemEmpty.empty_database:
            return CustomEmptyScreen(
              title: "Tidak Ada Bahan Baku",
              body: "Kamu belum memmiliki bahan baku",
              textButton: "Tambah Bahan Baku",
              onPressed: () => context.pushNamed(AppRoute.addRawMaterialScreen),
            );
          case DisplayItemEmpty.empty_search_result:
            return SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              padding: EdgeInsets.symmetric(vertical: 3.h),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "Bahan Baku Tidak Ditemukan",
                      style: TextStyle(
                        fontSize: AppFontSize.large.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.black,
                      ),
                    ),

                    SizedBox(height: 1.5.h),

                    Icon(
                      Icons.search_off_rounded,
                      size: 15.h,
                      color: Colors.grey.shade300,
                    ),
                  ],
                ),
              ),
            );
          case DisplayItemEmpty.has_data:
            return Column(
              children: [
                InkWell(
                  onTap: () => _toggleSelectAll(rawMaterials),
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 5.w,
                      vertical: 1.5.h,
                    ),
                    color: Colors.blue[50]!.withOpacity(0.5),
                    child: Row(
                      children: [
                        CheckboxButton(isSelected: isAllSelected),
                        SizedBox(width: 4.w),
                        Text(
                          "Pilih Semua Bahan Baku",
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: isTablet
                                ? AppFontSize.medium.sp
                                : AppFontSize.small.sp,
                            color: Colors.blue[800],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                Expanded(
                  child: ListView.builder(
                    padding: EdgeInsets.fromLTRB(4.w, 1.h, 4.w, 5.h),
                    itemCount: rawMaterials.length,
                    itemBuilder: (context, index) {
                      final rawMaterial = rawMaterials[index];

                      return Container(
                        margin: EdgeInsets.only(bottom: 1.5.h),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(2.5.w),
                          border: Border.all(
                            color: Colors.grey.shade200,
                            width: 1,
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.02),
                              blurRadius: 4,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: InkWell(
                          onTap: () {
                            final selectedItem = SelectedItem(
                              id: rawMaterial.id,
                              itemType: ItemType.raw_material,
                              itemId: rawMaterial.itemId,
                              localImagePath: rawMaterial.localImagePath,
                              name: rawMaterial.name,
                              variantName: rawMaterial.variantName,
                              costPrice: 0.0,
                              purchasePrice: rawMaterial.purchasePrice,
                              remainingStock: rawMaterial.remainingStock,
                              unit: rawMaterial.unit,
                              sellingPrice: rawMaterial.sellingPrice,
                              type: widget.type,
                            );

                            ref
                                .read(
                                  selectedItemProvider(widget.type).notifier,
                                )
                                .toggle(selectedItem);
                          },
                          borderRadius: BorderRadius.circular(2.5.w),
                          child: Padding(
                            padding: EdgeInsets.all(3.w),
                            child: Row(
                              children: [
                                CheckboxButton(
                                  isSelected:
                                      selectedItemState.containsKey(
                                        rawMaterial.id,
                                      ) &&
                                      selectedItemState[rawMaterial.id]?.type ==
                                          widget.type,
                                ),

                                SizedBox(width: 4.w),

                                Container(
                                  width: 15.w,
                                  height: 15.w,
                                  decoration: BoxDecoration(
                                    color: Colors.grey[100],
                                    borderRadius: BorderRadius.circular(2.w),
                                  ),
                                  child: Icon(
                                    Icons.inventory_2_rounded,
                                    color: Colors.grey[400],
                                    size: 5.w,
                                  ),
                                ),

                                SizedBox(width: 3.w),

                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        rawMaterial.name,
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: isTablet
                                              ? AppFontSize.medium.sp
                                              : AppFontSize.small.sp,
                                          color: Colors.black87,
                                        ),
                                      ),
                                      SizedBox(height: 0.75.h),
                                      Text(
                                        "Stok: ${rawMaterial.remainingStock.toStringWithoutTrailingZero()} ${rawMaterial.unit}",
                                        style: TextStyle(
                                          color: Colors.grey[600],
                                          fontSize: isTablet
                                              ? (AppFontSize.medium - 1.25).sp
                                              : (AppFontSize.small - 1.25).sp,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ],
            );
        }
      },
      error: (error, stackTrace) {
        return CustomErrorScreen(message: "Ups, terjadi kesalahan", onRefresh: () {});
      },
      loading: () => const SelectItemShimmer(),
    );
  }
}
