import 'dart:async';
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/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_check/domain/entities/selected_checked_item.dart';
import 'package:niogu_app/features/stock_check/presentation/providers/stock_check_provider.dart';
import 'package:niogu_app/features/stock_check/presentation/widgets/stock_check_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:sizer/sizer.dart';

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

  @override
  ConsumerState<ProductStockCheckScreen> createState() =>
      ProductStockCheckScreenState();
}

class ProductStockCheckScreenState
    extends ConsumerState<ProductStockCheckScreen>
    with AutomaticKeepAliveClientMixin {
  final Map<String, TextEditingController> _physicalControllers = {};

  final Map<String, TextEditingController> _noteControllers = {};

  final Map<String, Color> _statusColors = {};

  final Map<String, String> _statusTexts = {};

  Timer? _debounce;

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

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

  @override
  void dispose() {
    // TODO: implement dispose
    for (final controller in _physicalControllers.values) {
      controller.dispose();
    }

    for (final controller in _noteControllers.values) {
      controller.dispose();
    }
    _debounce?.cancel();
    super.dispose();
  }

  TextEditingController _physicalController(String id) {
    return _physicalControllers.putIfAbsent(id, () => TextEditingController());
  }

  TextEditingController _noteController(String id) {
    return _noteControllers.putIfAbsent(id, () => TextEditingController());
  }

  void _calculateDifference(String value, DisplayItem product) {
    if (_debounce?.isActive ?? false) _debounce?.cancel();

    DifferenceType differenceType = DifferenceType.suitable;

    double quantity = 0.0;

    _debounce = Timer(const Duration(milliseconds: 400), () {
      setState(() {
        if (value.isEmpty ||
            (value.isNotEmpty &&
                (double.tryParse(value) == null || double.parse(value) < 0))) {
          _statusColors[product.id] = Colors.grey;
          _statusTexts[product.id] = "Belum Dicek";
          return;
        }
        final double physicalStock = double.parse(value);

        if (physicalStock == product.remainingStock) {
          _statusColors[product.id] = Colors.green;
          _statusTexts[product.id] = "Sesuai";
          quantity = product.remainingStock;
          differenceType = DifferenceType.suitable;
        } else if (physicalStock < product.remainingStock) {
          _statusColors[product.id] = Colors.red;
          _statusTexts[product.id] =
              "Kurang ${(physicalStock - product.remainingStock).abs().toStringWithoutTrailingZero()} dari stok di sistem";
          quantity = (physicalStock - product.remainingStock);
          differenceType = DifferenceType.less;
        } else {
          _statusColors[product.id] = Colors.blue;
          _statusTexts[product.id] =
              "Lebih ${(physicalStock - product.remainingStock).toStringWithoutTrailingZero()} dari stok di sistem";
          quantity = (physicalStock - product.remainingStock);
          differenceType = DifferenceType.more;
        }
      });

      final selectedItemState = ref.read(selectedCheckedItemProvider);

      final selectedItemNotifier = ref.read(
        selectedCheckedItemProvider.notifier,
      );

      if (value.isNotEmpty &&
          double.tryParse(value.trim()) != null &&
          double.parse(value.trim()) >= 0) {
        if (selectedItemState.containsKey(product.id)) {
          final selectedItem = selectedItemState[product.id];

          selectedItemNotifier.state = {
            ...selectedItemState,
            product.id: selectedItem!.copyWith(quantity: quantity),
          };
        } else {
          selectedItemNotifier.state = {
            ...selectedItemState,
            product.id: SelectedCheckedItem(
              id: product.id,
              itemType: ItemType.product_variant,
              itemId: product.itemId,
              differenceType: differenceType,
              costPrice: product.costPrice,
              purchasePrice: 0.0,
              remainingStock: product.remainingStock,
              quantity: quantity,
            ),
          };
        }
      } else {
        selectedItemNotifier.state = {...selectedItemState}..remove(product.id);
      }
    });
  }

  void clear() {
    for (final controller in _physicalControllers.values) {
      controller.clear();
    }

    for (final controller in _noteControllers.values) {
      controller.clear();
    }

    _statusColors.clear();

    _statusTexts.clear();
  }

  @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),
    );

    return productState.when(
      data: (products) {
        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 ListView.builder(
              padding: EdgeInsets.all(4.w),
              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();

                String? difference;

                String? symbol;

                Color? symbolColor;

                if (double.tryParse(
                      _physicalController(product.id).text.trim(),
                    ) !=
                    null) {
                  final double physicalStock = double.parse(
                    _physicalController(product.id).text.trim(),
                  );

                  difference = (physicalStock - product.remainingStock)
                      .abs()
                      .toStringWithoutTrailingZero();
                  if (physicalStock > product.remainingStock) {
                    symbol = "+";
                    symbolColor = Colors.green;
                  } else if (physicalStock < product.remainingStock) {
                    symbol = "-";
                    symbolColor = Colors.red;
                  }
                }

                return Container(
                  margin: EdgeInsets.only(bottom: 1.5.h),
                  padding: EdgeInsets.all(4.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(2.5.w),
                    border: Border.all(color: Colors.grey.shade200),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.02),
                        blurRadius: 5,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          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,
                                  ),
                                ),
                                if (product.variantName != null) ...[
                                  SizedBox(height: 0.5.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.5.h),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Container(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 2.w,
                                        vertical: 0.5.w,
                                      ),
                                      decoration: BoxDecoration(
                                        color: Colors.grey[100],
                                        borderRadius: BorderRadius.circular(
                                          1.w,
                                        ),
                                      ),
                                      child: Text(
                                        "Sistem: ${product.remainingStock.toStringWithoutTrailingZero()} ${product.unit}",
                                        style: TextStyle(
                                          fontSize: isTablet
                                              ? (AppFontSize.medium - 1.25).sp
                                              : (AppFontSize.small - 1.25).sp,
                                          color: Colors.black87,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ),

                                    if (symbol != null &&
                                        symbolColor != null &&
                                        difference != null)
                                      Text(
                                        "$symbol $difference ${product.unit}",
                                        style: TextStyle(
                                          fontSize: isTablet
                                              ? (AppFontSize.medium - 1.25).sp
                                              : (AppFontSize.small - 1.25).sp,
                                          color: symbolColor,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),

                      Divider(height: 2.5.h, color: Colors.grey[100]),

                      Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Expanded(
                            flex: 3,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "Stok Fisik",
                                  style: TextStyle(
                                    fontSize: isTablet
                                        ? (AppFontSize.medium - 1.25).sp
                                        : (AppFontSize.small - 1.25).sp,
                                    color: Colors.grey[600],
                                  ),
                                ),
                                SizedBox(height: 0.8.h),
                                SizedBox(
                                  height: 5.5.h,
                                  child: TextFormField(
                                    controller: _physicalController(product.id),
                                    keyboardType:
                                        const TextInputType.numberWithOptions(
                                          decimal: true,
                                        ),
                                    onChanged: (value) =>
                                        _calculateDifference(value, product),
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: isTablet
                                          ? (AppFontSize.medium - 1.25).sp
                                          : (AppFontSize.small - 1.25).sp,
                                    ),
                                    decoration: InputDecoration(
                                      contentPadding: EdgeInsets.symmetric(
                                        horizontal: 3.w,
                                      ),
                                      border: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                          2.w,
                                        ),
                                      ),
                                      enabledBorder: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                          2.5.w,
                                        ),
                                        borderSide: BorderSide(
                                          color: Colors.grey.shade300,
                                        ),
                                      ),
                                      focusedBorder: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(
                                          2.w,
                                        ),
                                        borderSide: BorderSide(
                                          color: AppColor.primaryColor,
                                          width: 1.5,
                                        ),
                                      ),
                                      suffixText: product.unit,
                                      suffixStyle: TextStyle(
                                        fontSize: isTablet
                                            ? (AppFontSize.medium - 1.25).sp
                                            : (AppFontSize.small - 1.25).sp,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),

                          SizedBox(width: 4.w),

                          Expanded(
                            flex: 6,
                            child: Container(
                              height: 5.5.h,
                              padding: EdgeInsets.symmetric(horizontal: 2.w),
                              decoration: BoxDecoration(
                                color:
                                    (_statusColors[product.id] ?? Colors.grey)
                                        .withOpacity(0.1),
                                borderRadius: BorderRadius.circular(2.5.w),
                                border: Border.all(
                                  color:
                                      (_statusColors[product.id] ?? Colors.grey)
                                          .withOpacity(0.3),
                                ),
                              ),
                              alignment: Alignment.centerLeft,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    "Selisih",
                                    style: TextStyle(
                                      fontSize: isTablet
                                          ? (AppFontSize.medium - 1.25).sp
                                          : (AppFontSize.small - 1.25).sp,
                                      color:
                                          (_statusColors[product.id] ??
                                                  Colors.grey)
                                              .withOpacity(0.8),
                                    ),
                                  ),
                                  Text(
                                    _statusTexts[product.id] ?? "Belum Dicek",
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      fontSize: isTablet
                                          ? (AppFontSize.medium - 1.25).sp
                                          : (AppFontSize.small - 1.25).sp,
                                      fontWeight: FontWeight.bold,
                                      color:
                                          (_statusColors[product.id] ??
                                          Colors.grey),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),

                      SizedBox(height: 1.5.h),
                      TextField(
                        controller: _noteController(product.id),
                        onChanged: (value) {
                          final selectedItemState = ref.read(
                            selectedCheckedItemProvider,
                          );

                          final selectedItemNotifier = ref.read(
                            selectedCheckedItemProvider.notifier,
                          );

                          if (selectedItemState.containsKey(product.id)) {
                            selectedItemNotifier.state = {
                              ...selectedItemState,
                              product.id: selectedItemState[product.id]!
                                  .copyWith(note: value),
                            };
                          }
                        },
                        style: TextStyle(
                          fontSize: isTablet
                              ? (AppFontSize.medium - 1.25).sp
                              : (AppFontSize.small - 1.25).sp,
                        ),
                        decoration: InputDecoration(
                          hintText: "Catatan (Opsional) - cth: Barang rusak",
                          hintStyle: TextStyle(
                            fontSize: isTablet
                                ? (AppFontSize.medium - 1.25).sp
                                : (AppFontSize.small - 1.25).sp,
                            color: Colors.grey[400],
                          ),
                          isDense: true,
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 3.w,
                            vertical: 1.2.h,
                          ),
                          filled: true,
                          fillColor: Colors.grey[50],
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(2.5.w),
                            borderSide: BorderSide.none,
                          ),
                          prefixIcon: Icon(
                            Icons.edit_note,
                            size: 4.5.w,
                            color: Colors.grey[400],
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              },
            );
        }
      },
      error: (error, stackTrace) {
        return CustomErrorScreen(message: "Ups, terjadi kesalahan", onRefresh: () {});
      },
      loading: () => const StockCheckShimmer(),
    );
  }
}
