import 'dart:io';

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 DisplayProductScreen extends ConsumerStatefulWidget {
  final SelectedItemType type;

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

  @override
  ConsumerState<DisplayProductScreen> createState() =>
      DisplayProductScreenState();
}

class DisplayProductScreenState extends ConsumerState<DisplayProductScreen>
    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> products) {
    final selectedItemState = ref.read(selectedItemProvider(widget.type));

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

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

    for (final product in products) {
      final selectedItem = SelectedItem(
        id: product.id,
        itemType: ItemType.product_variant,
        itemId: product.itemId,
        localImagePath: product.localImagePath,
        name: product.name,
        variantName: product.variantName,
        costPrice: product.costPrice,
        purchasePrice: 0.0,
        remainingStock: product.remainingStock,
        unit: product.unit,
        sellingPrice: product.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 productState = ref.watch(
      filteredItemProvider(ItemType.product_variant),
    );

    final productEmptyState = ref.watch(
      displayItemEmptyProvider(ItemType.product_variant),
    );

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

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

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

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

          case DisplayItemEmpty.empty_database:
            return CustomEmptyScreen(
              title: "Tidak Ada Produk",
              body: "Kamu belum memiliki produk",
              textButton: "Buat Produk Pertamamu",
              onPressed: () => context.pushNamed(AppRoute.addProductScreen),
            );
          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(
                      "Produk 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(products),
                  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 Produk",
                          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: products.length,
                    itemBuilder: (context, index) {
                      final product = products[index];

                      final String path =
                          product.localImagePath != null &&
                              product.localImagePath!.isNotEmpty
                          ? product.localImagePath!
                          : 'image not found';

                      final File imageFile = File(path);

                      final bool imageFileExists = imageFile.existsSync();

                      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: product.id,
                              itemType: ItemType.product_variant,
                              itemId: product.itemId,
                              localImagePath: product.localImagePath,
                              name: product.name,
                              variantName: product.variantName,
                              costPrice: product.costPrice,
                              purchasePrice: 0.0,
                              remainingStock: product.remainingStock,
                              unit: product.unit,
                              sellingPrice: product.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(
                                        product.id,
                                      ) &&
                                      selectedItemState[product.id]?.type ==
                                          widget.type,
                                ),

                                SizedBox(width: 4.w),

                                Container(
                                  height: 15.w,
                                  width: 15.w,
                                  decoration: BoxDecoration(
                                    border: Border.all(
                                      color: Colors.grey.shade200,
                                      width: 1.5,
                                    ),
                                    borderRadius: BorderRadius.circular(2.5.w),
                                  ),
                                  child: imageFileExists
                                      ? ClipRRect(
                                          borderRadius: BorderRadius.circular(
                                            2.5.w,
                                          ),
                                          child: Image.file(
                                            imageFile,
                                            fit: BoxFit.cover,
                                            width: double.infinity,
                                            height: double.infinity,
                                            errorBuilder:
                                                (context, error, stackTrace) {
                                                  return const Icon(
                                                    Icons.error,
                                                    color: Colors.grey,
                                                  );
                                                },
                                          ),
                                        )
                                      : Icon(
                                          Icons.image_outlined,
                                          size: 8.w,
                                          color: Colors.grey,
                                        ),
                                ),

                                SizedBox(width: 3.w),

                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        product.name,
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: isTablet
                                              ? AppFontSize.medium.sp
                                              : AppFontSize.small.sp,
                                          color: Colors.black87,
                                        ),
                                      ),
                                      if (product.variantName != null &&
                                          product.variantName!.isNotEmpty) ...[
                                        SizedBox(height: 0.75.h),
                                        Text(
                                          product.variantName!,
                                          style: TextStyle(
                                            color: Colors.grey[600],
                                            fontSize: isTablet
                                                ? (AppFontSize.medium - 1.25).sp
                                                : (AppFontSize.small - 1.25).sp,
                                          ),
                                        ),
                                      ],
                                      SizedBox(height: 0.75.h),
                                      Text(
                                        "Stok: ${product.remainingStock.toStringWithoutTrailingZero()} ${product.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(),
    );
  }
}
