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

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

  @override
  ConsumerState<ProductScreen> createState() => _ProductScreenState();
}

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

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @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 productState = ref.watch(filteredProductProvider);

    final productEmptyState = ref.watch(productEmptyProvider);

    return productState.when(
      data: (products) {
        switch (productEmptyState) {
          case ProductEmpty.loading:
            return const SizedBox();
          case ProductEmpty.empty_database:
            return CustomEmptyScreen(
              title: "Tidak Ada Produk",
              body: "Kamu belum memiliki produk",
              textButton: "Buat Produk Pertamamu",
              onPressed: () async {
                final currentUserRole = ref.read(currentUserRoleProvider);

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

                if (currentUserRole == UserRole.owner && isMainOutlet) {
                  context.pushNamed(AppRoute.addProductScreen);
                } else {
                  context.pushNamed(AppRoute.productChoiceScreen);
                }
              },
            );
          case ProductEmpty.empty_search_result:
            return const CustomEmptyScreen(body: "Produk Tidak Ditemukan");
          case ProductEmpty.has_data:
            return Stack(
              children: [
                ListView.builder(
                  padding: EdgeInsets.all(4.w),
                  itemCount: products.length,
                  itemBuilder: (context, index) {
                    final product = products[index];

                    final bool imagePathAvailable =
                        product.productImages != null &&
                        product.productImages!.isNotEmpty &&
                        product.productImages!.last.isNotEmpty;

                    final File imageFile = File(
                      imagePathAvailable
                          ? product.productImages!.last
                          : "image not found",
                    );

                    final bool imageFileExists = imageFile.existsSync();

                    return RepaintBoundary(
                      child: Card(
                        elevation: 0,
                        color: Colors.white,
                        shape: RoundedRectangleBorder(
                          side: BorderSide(color: Colors.grey.shade300),
                          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),
                                );

                                context.pushNamed(
                                  AppRoute.editProductScreen,
                                  pathParameters: {"id": product.id},
                                  extra: {
                                    "is_main_outlet": isMainOutlet,
                                    "has_new_variant":
                                        product.newVariantCount > 0,
                                    "new_variant_count":
                                        product.newVariantCount,
                                  },
                                );
                              },
                              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),

                                  Container(
                                    height: 17.w,
                                    width: 17.w,
                                    decoration: BoxDecoration(
                                      border: Border.all(
                                        color: Colors.grey.shade400,
                                      ),
                                      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 Icon(
                                                      Icons.error,
                                                      color: Colors.grey[400],
                                                      size: 8.w,
                                                    );
                                                  },
                                            ),
                                          )
                                        : Icon(
                                            Icons.image_outlined,
                                            size: 8.w,
                                            color: Colors.grey[400],
                                          ),
                                  ),

                                  SizedBox(width: 3.w),

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

                                        if (product.hasVariant)
                                          CustomItemDetail(
                                            label: "Jumlah Varian",
                                            value: ": ${product.variantCount}",
                                          ),

                                        CustomItemDetail(
                                          label: "Jenis Stok",
                                          value:
                                              ": ${product.stockType == 'fixed' ? 'Tetap' : 'Selalu Ada'}",
                                        ),

                                        if (product.stockType == 'fixed')
                                          CustomItemDetail(
                                            label: "Sisa Stok",
                                            value:
                                                ": ${product.remainingStock}",
                                          ),

                                        CustomItemDetail(
                                          label: "Harga Jual",
                                          value:
                                              ": ${product.displaySellingPrice}",
                                        ),
                                        if (product.newVariantCount > 0) ...[
                                          SizedBox(height: 1.h),
                                          Container(
                                            padding: EdgeInsets.symmetric(
                                              horizontal: 2.5.w,
                                              vertical: 0.5.h,
                                            ),
                                            decoration: BoxDecoration(
                                              color: AppColor.primaryColor
                                                  .withOpacity(0.1),
                                              borderRadius:
                                                  BorderRadius.circular(1.5.w),
                                              border: Border.all(
                                                color: AppColor.primaryColor
                                                    .withOpacity(0.2),
                                                width: 0.5,
                                              ),
                                            ),
                                            child: Row(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                Icon(
                                                  Icons.auto_awesome_rounded,
                                                  size: 5.w,
                                                  color: AppColor.primaryColor,
                                                ),
                                                SizedBox(width: 1.5.w),
                                                Text(
                                                  "${product.newVariantCount} Varian Baru Tersedia",
                                                  style: TextStyle(
                                                    fontSize: isTablet
                                                        ? AppFontSize.medium.sp
                                                        : AppFontSize.small.sp,
                                                    fontWeight: FontWeight.bold,
                                                    color:
                                                        AppColor.primaryColor,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ],
                                    ),
                                  ),

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

                                      final productRepository = ref.read(
                                        productRepositoryProvider,
                                      );

                                      final productSnapshot =
                                          await productRepository
                                              .fetchDeleteProductSnapshotById(
                                                id,
                                              );

                                      FocusScope.of(context).unfocus();

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

                                      showDialog(
                                        context: context,
                                        builder: (context) =>
                                            DeleteProductScreen(
                                              productSnapshot: productSnapshot,
                                            ),
                                      );
                                    },
                                    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_product",
                    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.addProductScreen);
                      } else {
                        context.pushNamed(AppRoute.productChoiceScreen);
                      }
                    },
                    elevation: 0,
                    backgroundColor: AppColor.primaryColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(2.5.w),
                    ),
                    child: Icon(Icons.add, color: Colors.white, size: 8.w),
                  ),
                ),
              ],
            );
        }
      },
      error: (error, stackTrace) {
        return CustomErrorScreen(
          message: "Ups, terjadi kesalahan",
          onRefresh: () {},
        );
      },
      loading: () => const ProductListShimmer(),
    );
  }
}
