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/constants/app_font_size.dart';
import 'package:niogu_app/core/widgets/custom_error_screen.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/core/router/app_route.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/enums/user_role.dart';
import 'package:niogu_app/core/widgets/custom_empty_screen.dart';
import 'package:niogu_app/core/widgets/custom_not_login.dart';
import 'package:niogu_app/features/goods/presentation/widgets/custom_item_detail.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/goods/raw_materials/presentation/screens/delete_raw_material_screen.dart';
import 'package:niogu_app/features/goods/raw_materials/presentation/widgets/raw_material_list_shimmer.dart';
import 'package:niogu_app/features/outlets/presentation/providers/outlet_provider.dart';
import 'package:sizer/sizer.dart';

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

  @override
  ConsumerState<RawMaterialScreen> createState() => _RawMaterialScreenState();
}

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

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

    final bool isTablet = 100.w >= 600;

    final isLoggedIn = ref.watch(currentStatusLoginProvider);

    if (!isLoggedIn) {
      return const CustomNotLogin();
    }

    final rawMaterialState = ref.watch(filteredRawMaterialProvider);

    final rawMaterialEmptyState = ref.watch(rawMaterialEmptyProvider);

    return rawMaterialState.when(
      data: (rawMaterials) {
        switch (rawMaterialEmptyState) {
          case RawMaterialEmpty.loading:
            return const SizedBox();

          case RawMaterialEmpty.empty_database:
            return CustomEmptyScreen(
              title: "Tidak Ada Bahan Baku",
              body: "Kamu belum memmiliki bahan baku",
              textButton: "Tambah Bahan Baku",
              onPressed: () async {
                final currentUserRole = ref.read(currentUserRoleProvider);

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

                if (currentUserRole == UserRole.owner && isMainOutlet) {
                  context.pushNamed(AppRoute.addRawMaterialScreen);
                } else {
                  context.pushNamed(AppRoute.rawMaterialChoiceScreen);
                }
              },
            );

          case RawMaterialEmpty.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 RawMaterialEmpty.has_data:
            return Stack(
              children: [
                ListView.builder(
                  padding: EdgeInsets.all(4.w),
                  itemCount: rawMaterials.length,
                  itemBuilder: (context, index) {
                    final rawMaterial = rawMaterials[index];
                    return Card(
                      elevation: 0,
                      color: Colors.white,
                      shape: RoundedRectangleBorder(
                        side: BorderSide(color: Colors.grey.shade200),
                        borderRadius: BorderRadius.circular(2.5.w),
                      ),
                      margin: EdgeInsets.only(bottom: 2.h),
                      child: Padding(
                        padding: EdgeInsets.symmetric(
                          vertical: 2.h,
                          horizontal: 2.w,
                        ),
                        child: Material(
                          color: Colors.white,
                          clipBehavior: Clip.hardEdge,
                          child: InkWell(
                            onTap: () async {
                              FocusScope.of(context).unfocus();

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

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

                              final currentUserRole = ref.read(
                                currentUserRoleProvider,
                              );

                              final isEditing =
                                  (currentUserRole == UserRole.owner &&
                                      isMainOutlet) ||
                                  currentUserRole == UserRole.admin;

                              context.pushNamed(
                                AppRoute.editRawMaterialScreen,
                                pathParameters: {"id": rawMaterial.id},
                                extra: {
                                  "is_main_outlet": isMainOutlet,
                                  "is_editing": isEditing,
                                },
                              );
                            },
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "${index + 1}.",
                                  style: TextStyle(
                                    fontSize: isTablet
                                        ? AppFontSize.medium.sp
                                        : AppFontSize.small.sp,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                SizedBox(width: 3.w),

                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        rawMaterial.name,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontSize: isTablet
                                              ? AppFontSize.medium.sp
                                              : AppFontSize.small.sp,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      SizedBox(height: 0.5.h),

                                      CustomItemDetail(
                                        label: "Jumlah Produk",
                                        value:
                                            ": ${rawMaterial.countProductUsage}",
                                      ),

                                      CustomItemDetail(
                                        label: "Sisa Stok",
                                        value:
                                            ": ${rawMaterial.remainingStock}",
                                      ),
                                      CustomItemDetail(
                                        label: "Harga Beli",
                                        value:
                                            ": ${rawMaterial.displayPurchasePrice}",
                                      ),
                                    ],
                                  ),
                                ),

                                IconButton(
                                  onPressed: () async {
                                    final String id = rawMaterial.id;

                                    final rawMaterialRepository = ref.read(
                                      rawMaterialRepositoryProvider,
                                    );

                                    final rawMaterialSnapshot =
                                        await rawMaterialRepository
                                            .fetchDeleteRawMaterialSnapshotById(
                                              id,
                                            );

                                    FocusScope.of(context).unfocus();

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

                                    showDialog(
                                      context: context,
                                      builder: (context) =>
                                          DeleteRawMaterialScreen(
                                            rawMaterialSnapshot:
                                                rawMaterialSnapshot,
                                          ),
                                    );
                                  },
                                  icon: Icon(
                                    Icons.delete,
                                    color: Colors.red,
                                    size: 6.w,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    );
                  },
                ),
                Positioned(
                  bottom: 10.h,
                  right: 4.w,
                  width: 12.5.w,
                  height: 12.5.w,
                  child: FloatingActionButton(
                    heroTag: "btn_add_raw_material",
                    onPressed: () async {
                      FocusScope.of(context).unfocus();

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

                      final currentUserRole = ref.read(currentUserRoleProvider);

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

                      if (currentUserRole == UserRole.owner && isMainOutlet) {
                        context.pushNamed(AppRoute.addRawMaterialScreen);
                      } else {
                        context.pushNamed(AppRoute.rawMaterialChoiceScreen);
                      }
                    },
                    backgroundColor: AppColor.primaryColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(2.5.w),
                    ),
                    child: Icon(Icons.add, color: Colors.white, size: 8.w),
                  ),
                ),
              ],
            );
        }
      },
      error: (error, stackTrace) {
        LogMessage.log.e(
          error.toString(),
          error: error,
          stackTrace: stackTrace,
        );
        return CustomErrorScreen(
          message: "Ups, terjadi kesalahan",
          onRefresh: () {},
        );
      },
      loading: () => const RawMaterialListShimmer(),
    );
  }
}
