import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/core/utils/currency_format.dart';
import 'package:niogu_app/core/utils/image_service.dart';
import 'package:niogu_app/core/enums/user_role.dart';
import 'package:niogu_app/core/widgets/pop_up_notification.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/screens/stock_in_production_screen.dart';
import 'package:niogu_app/features/stock_in/presentation/provider/stock_in_purchase_provider.dart';
import 'package:niogu_app/features/stock_in/presentation/screens/stock_in_purchase_screen.dart';
import 'package:niogu_app/features/stock_in/presentation/screens/stock_in_transfer_screen.dart';
import 'package:sizer/sizer.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';

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

  @override
  ConsumerState<StockInScreen> createState() => _StockInScreenState();
}

class _StockInScreenState extends ConsumerState<StockInScreen>
    with SingleTickerProviderStateMixin {
  final GlobalKey<StockInProductionScreenState> _productionKey = GlobalKey();
  final GlobalKey<StockInTransferScreenState> _transferKey = GlobalKey();
  final GlobalKey<StockInPurchaseScreenState> _purchaseKey = GlobalKey();

  late TabController _tabController;

  int _tabIndex = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);

    _tabController.addListener(_handleTabSelection);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      Future.microtask(() {
        ref.invalidate(proofPaymentPurchaseTempProvider);
      });
    });
  }

  @override
  void dispose() {
    _tabController.removeListener(_handleTabSelection);
    _tabController.dispose();
    super.dispose();
  }

  void _handleTabSelection() {
    if (_tabController.index != _tabIndex) {
      setState(() {
        _tabIndex = _tabController.index;
      });
    }
  }

  Future<void> _cleanUpImages() async {
    final paths = ref.read(proofPaymentPurchaseTempProvider);

    for (final path in paths) {
      if (path != null) {
        await ImageService.deleteLocalImage(path);
      }
    }

    ref.invalidate(proofPaymentPurchaseTempProvider);
  }

  Future<void> _updateStockItem() async {
    if (_tabIndex == 0) {
      await _productionKey.currentState?.updateStockItem();
    } else if (_tabIndex == 1) {
      await _transferKey.currentState?.updateStockItem();
    } else if (_tabIndex == 2) {
      await _purchaseKey.currentState?.updateStockItem();
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final messageActivity = ref.watch(messageActivityProvider);

        final currentUserRole = ref.watch(currentUserRoleProvider);

        final selectedItemProductionState = ref.watch(
          selectedItemProvider(SelectedItemType.production),
        );

        final selectedItemTransferState = ref.watch(
          selectedItemProvider(SelectedItemType.transfer_in),
        );

        final selectedItemPurchaseState = ref.watch(
          selectedItemProvider(SelectedItemType.purchase),
        );

        final selectedItemProductions = selectedItemProductionState.values
            .where((item) {
              return item.type == SelectedItemType.production;
            })
            .toList();

        final selectedItemTransfer = selectedItemTransferState.values.where((
          item,
        ) {
          return item.type == SelectedItemType.transfer_in;
        }).toList();

        final selectedItemPurchase = selectedItemPurchaseState.values.where((
          item,
        ) {
          return item.type == SelectedItemType.purchase;
        }).toList();

        final double totalPurchaseAmount = ref.watch(
          totalPurchaseAmountProvider,
        );

        final stockInControllerState = ref.watch(stockInControllerProvider);

        return PopScope(
          canPop: false,
          onPopInvokedWithResult: (didPop, result) async {
            if (didPop) return;

            await _cleanUpImages();

            context.pop();
          },
          child: SafeArea(
            top: false,
            bottom: true,
            right: false,
            left: false,
            child: Stack(
              children: [
                Scaffold(
                  backgroundColor: const Color(0xFFF9FAFB),
                  appBar: AppBar(
                    backgroundColor: Colors.white,
                    surfaceTintColor: Colors.white,
                    elevation: 0,
                    toolbarHeight: 10.h,
                    centerTitle: true,
                    leading: Center(
                      child: Material(
                        color: Colors.transparent,
                        type: MaterialType.canvas,
                        child: InkWell(
                          onTap: () async {
                            await _cleanUpImages();

                            context.pop();
                          },
                          borderRadius: BorderRadius.circular(2.5.w),
                          child: Container(
                            width: 10.w,
                            height: 10.w,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              border: Border.all(color: Colors.grey.shade200),
                              borderRadius: BorderRadius.circular(2.5.w),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.05),
                                  blurRadius: 5,
                                  offset: const Offset(0, 2),
                                ),
                              ],
                            ),
                            child: Icon(
                              Icons.arrow_back_ios_new_rounded,
                              color: Colors.black87,
                              size: 5.w,
                            ),
                          ),
                        ),
                      ),
                    ),
                    leadingWidth: 18.w,
                    title: Text(
                      "Stok Masuk",
                      style: TextStyle(
                        color: Colors.black87,
                        fontWeight: FontWeight.bold,
                        fontSize: AppFontSize.medium.sp,
                      ),
                    ),
                    /**
                    actions: [
                      IconButton(
                        onPressed: () {},
                        icon: Icon(
                          Icons.help_outline_rounded,
                          color: Colors.grey[400],
                          size: 4.w,
                        ),
                      ),
                      SizedBox(width: 3.w),
                    ],
                    */
                    bottom: PreferredSize(
                      preferredSize: Size.fromHeight(8.h),
                      child: Container(
                        height: 6.h,
                        margin: EdgeInsets.fromLTRB(4.w, 0, 4.w, 1.5.h),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                          borderRadius: BorderRadius.circular(2.5.w),
                        ),
                        child: TabBar(
                          onTap: (value) {
                            setState(() {
                              _tabIndex = value;
                            });
                          },
                          controller: _tabController,
                          indicator: BoxDecoration(
                            color: AppColor.primaryColor,
                            borderRadius: BorderRadius.circular(2.05.w),
                            boxShadow: [
                              BoxShadow(
                                color: AppColor.primaryColor.withOpacity(0.3),
                                blurRadius: 4,
                                offset: const Offset(0, 2),
                              ),
                            ],
                          ),
                          indicatorSize: TabBarIndicatorSize.tab,
                          dividerColor: Colors.transparent,
                          labelColor: Colors.white,
                          unselectedLabelColor: Colors.grey[600],
                          labelStyle: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: (AppFontSize.medium - 1.5).sp,
                          ),
                          padding: EdgeInsets.all(1.w),
                          tabs: [
                            Tab(text: "Produksi", height: 10.h),
                            Tab(text: "Transfer", height: 10.h),
                            Tab(text: "Pembelian", height: 10.h),
                          ],
                        ),
                      ),
                    ),
                  ),
                  body: TabBarView(
                    controller: _tabController,
                    children: [
                      StockInProductionScreen(key: _productionKey),

                      StockInTransferScreen(key: _transferKey),

                      StockInPurchaseScreen(key: _purchaseKey),
                    ],
                  ),
                  bottomNavigationBar: Container(
                    padding: EdgeInsets.all(5.w),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.05),
                          blurRadius: 10,
                          offset: const Offset(0, -5),
                        ),
                      ],
                    ),
                    child: SizedBox(
                      width: double.infinity,
                      height: 6.5.h,
                      child: ElevatedButton(
                        onPressed: stockInControllerState.isLoading
                            ? null
                            : _tabIndex == 0 && selectedItemProductions.isEmpty
                            ? null
                            : _tabIndex == 1 && selectedItemTransfer.isEmpty
                            ? null
                            : _tabIndex == 2 && selectedItemPurchase.isEmpty
                            ? null
                            : _updateStockItem,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColor.primaryColor,
                          disabledBackgroundColor: Colors.grey[300],
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(2.5.w),
                          ),
                        ),
                        child: _tabIndex != 2
                            ? Text(
                                "Simpan & Tambah Stok",
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: AppFontSize.medium.sp,
                                  fontWeight: FontWeight.bold,
                                ),
                              )
                            : Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    "Total: ${CurrencyFormat.formatToIdr(totalPurchaseAmount, 0)}",
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: (AppFontSize.medium - 1.25).sp,
                                    ),
                                  ),
                                  Text(
                                    "Proses Pembelian",
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: (AppFontSize.medium - 1.25).sp,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                      ),
                    ),
                  ),
                ),

                if (messageActivity != null)
                  PopupNotification(
                    isOwner: currentUserRole == UserRole.owner,
                    messages: messageActivity.messages,
                    type: messageActivity.type,
                  ),
              ],
            ),
          ),
        );
      },
    );
  }
}
