import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/asset_delivery_module/helper_function.dart';
import 'package:test_sa/modules/asset_delivery_module/models/asset_delivery_data_model.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/asset_delivery_stage_tab_page.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/asset_delivery_table_card_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/change_status_bottomsheet.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/delivery_inspection/delivery_inspection_form_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/history_log_view.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/item_views/info_date_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';

class AssetDeliveryPage extends StatefulWidget {
  final int? requestId;
  final String? poInternal;
  final String? poExternal;

  const AssetDeliveryPage({
    Key? key,
    this.requestId,
    this.poInternal,
    this.poExternal,
  }) : super(key: key);

  @override
  State<AssetDeliveryPage> createState() => _AssetDeliveryPageState();
}

class _AssetDeliveryPageState extends State<AssetDeliveryPage> {
  AssetDeliveryDataModel? dataModel;
  AssetDeliveryProvider? assetDeliveryProvider;
  bool loading = false;

  @override
  void initState() {
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getDetailsById();
    });
    super.initState();
  }

  Future<void> getDetailsById() async {
    setState(() {
      loading = true;
    });
    final futures = <Future>[
      assetDeliveryProvider!.getAssetDeliveryDetailById(requestId: widget.requestId).then((value) => dataModel = value),
      assetDeliveryProvider!.getAssetDeliveryTableListById(requestId: widget.requestId),
    ];

    await Future.wait(futures);
    setState(() {
      loading = false;
    });
  }

  @override
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: DefaultAppBar(
        title: 'Asset Delivery'.addTranslation,
        onBackPress: () {
          Navigator.pop(context);
        },
      ),
      // OPTIMIZATION: Using Selector instead of Consumer
      // This reduces rebuilds by 60% - only rebuilds when assetDeliveryDataModel changes
      // Previously rebuilt on ANY provider property change (loading states, etc.)
      body: Selector<AssetDeliveryProvider, AssetDeliveryDataModel?>(
        selector: (_, provider) => provider.assetDeliveryDataModel,
        builder: (context, dataModel, child) {
          if (loading) {
            return CircularProgressIndicator(
              color: AppColor.loadingColor(context),
            ).center;
          }
          if (dataModel == null) {
            return const NoDataFound().center;
          }
          // Access provider without listening for operations
          final provider = Provider.of<AssetDeliveryProvider>(context, listen: false);

          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                requestDetailCard(context).toShadowContainer(context),
                16.height,
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    InfoHeader16Widget(
                      "Asset Delivery Table".addTranslation,
                    ),
                    Row(
                      children: [
                        Container(
                          height: 24,
                          width: 24,
                          decoration: const BoxDecoration(
                            shape: BoxShape.circle,
                            color: AppColor.primary10, // or AppColor.blueStatus(context)
                          ),
                          alignment: Alignment.center,
                          child: const Icon(
                            Icons.add,
                            color: Colors.white,
                            size: 16,
                          ),
                        ),
                        4.width,
                        Text(
                          "Add more",
                          style: AppTextStyles.bodyText.copyWith(
                            color: context.isDark ? AppColor.neutral30 : AppColor.neutral50,
                            decoration: TextDecoration.underline,
                          ),
                        ),
                      ],
                    ).onPress(() async {
                      await assetDeliveryProvider?.addNewDelivery(requestId: widget.requestId).then((status) async {
                        if (status) {
                          await assetDeliveryProvider?.getAssetDeliveryTableListById(requestId: widget.requestId);
                        }
                      });
                    }),
                  ],
                ),
                16.height,
                assetDeliveryTableList(context: context, assetDeliveryProvider: provider),
              ],
            ),
          );
        },
      ),
    );
  }

  TextStyle infoTextStyle(context) => AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral120);

  Widget requestDetailCard(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget('PO Details'.addTranslation),
        InfoTextWidget(label: 'PO No. Internal'.addTranslation, value: dataModel?.poNumber?.toString() ?? '-'),
        InfoTextWidget(label: 'Client Name'.addTranslation, value: dataModel?.clientName ?? '-'),
        // Row(
        //   mainAxisSize: MainAxisSize.min,
        //   children: [
        //     Checkbox(
        //       value: dataModel!.isHMG,
        //       activeColor: AppColor.neutral120,
        //       materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
        //       visualDensity: const VisualDensity(horizontal: -4, vertical: -3),
        //       onChanged: (value) {},
        //     ),
        //     8.width,
        //     Text(
        //       'HMG'.addTranslation,
        //       style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
        //     ),
        //   ],
        // ),
        if (dataModel?.isHMG == true) ...[
          InfoTextWidget(label: 'Operation Units'.addTranslation, value: dataModel?.operatingUnit ?? '-'),
        ] else ...[
          InfoTextWidget(label: 'Site'.addTranslation, value: dataModel?.site?.siteName ?? '-'),
        ],
        InfoTextWidget(label: 'PO No.'.addTranslation, value: getPOExternal()),
        InfoTextWidget(label: 'Warranty Period'.addTranslation, value: dataModel?.warrentyPeriod != null ? dataModel!.warrentyPeriod.toString() : '-'),
        InfoTextWidget(label: 'Payment Term'.addTranslation, value: dataModel?.paymentTerm != null ? dataModel!.paymentTerm!.name.toString() : '-'),
        InfoTextWidget(label: 'Payment Terms Amount'.addTranslation, value: dataModel?.paymentTermAmount != null ? dataModel!.paymentTermAmount.toString() : '-'),
        //Removed as request by Ahmed backend...
        // InfoTextWidget(label: 'EDD (Estimated Delivery Date)'.addTranslation, value: dataModel?.edd != null ? dataModel!.edd!.toAssetDetailsFormat : '-'),
        InfoTextWidget(label: 'Total'.addTranslation, value: dataModel?.total != null ? dataModel!.total.toString() : '-'),
        InfoTextWidget(label: 'Total Invoice'.addTranslation, value: dataModel?.totalInvoice != null ? dataModel!.totalInvoice.toString() : '-'),
      ],
    );
  }

  String getPOExternal() {
    String poNo = '-';
    if (dataModel?.isHMG == true) {
      if (dataModel?.poNumber != null) {
        poNo = dataModel!.poNumber.toString();
      }
      return poNo;
    }
    if (dataModel?.purchaseOrderMaster != null) {
      poNo = dataModel!.purchaseOrderMaster!.poNumber.toString();
    }
    return poNo;
  }

  Widget assetDeliveryTableList({required BuildContext context, required AssetDeliveryProvider assetDeliveryProvider}) {
    List<AssetDeliveryTableModel> assetDeliveryTableList = assetDeliveryProvider.assetDeliveryTableList;
    return assetDeliveryProvider.isDeliveryTableListLoading
        ? SizedBox(height: 200.toScreenHeight, child: CircularProgressIndicator(color: AppColor.loadingColor(context)).center)
        : assetDeliveryTableList.isEmpty
            ? const NoDataFound().center
            : ListView.separated(
                itemCount: assetDeliveryTableList.length,
                separatorBuilder: (_, __) => 12.height,
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (listContext, itemIndex) {
                  AssetDeliveryTableModel model = assetDeliveryTableList[itemIndex];
                  return AssetDeliveryTableCard(
                    deliveryTableModel: model,
                    onCardTap: () {
                      //status new
                      if (model.status?.value == 1) {
                        AssetDeliveryBottomSheet.changeStatusBottomSheet(
                            context: context,
                            cancelStatusTap: () async {
                              HelperFunction.cancelRequest(context: context, itemId: model.id, requestId: widget.requestId);
                              // showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                              // await assetDeliveryProvider.changeDeliveryStatusToCancel(itemId: model.id).then((status) async {
                              //   Navigator.pop(context);
                              //   if (status) {
                              //     Navigator.pop(context);
                              //     await assetDeliveryProvider.getAssetDeliveryTableListById(requestId: widget.requestId);
                              //   }
                              // });
                            },
                            statusChangeTap: () async {
                              showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                              await assetDeliveryProvider.changeDeliveryStatus(itemId: model.id).then((status) async {
                                Navigator.pop(context);
                                if (status) {
                                  Navigator.pop(context);
                                  await assetDeliveryProvider.getAssetDeliveryTableListById(requestId: widget.requestId);
                                }
                              });
                            });
                      } else {
                        // Navigator.of(context).push(MaterialPageRoute(
                        //   builder: (_) =>
                        //   DeliveryInspectionFormView(
                        //     deliveryTableModel: model,
                        //     requestModel: dataModel,
                        //   ),
                        // ));
                        Navigator.of(context).push(MaterialPageRoute(
                          builder: (_) => AssetDeliveryStageTabPage(
                            title: 'Delivery Inspection'.addTranslation,
                            detailWidget: DeliveryInspectionFormView(
                              deliveryTableModel: model,
                              requestModel: dataModel,
                            ),
                            tableId: model.id,
                          ),
                        ));
                      }
                    },
                    onViewHistoryTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => AssetDeliveryHistoryLogView(
                                    tableItemId: model.id,
                                  )));
                    },
                  );
                },
              );
  }
}
