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/models/lookup.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/models/delivery_line_model.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/asset_delivery_line_card_view.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/attachment_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/end_user_acceptance/end_user_cost_center_list_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/technical_inpection/update_technical_inspection_lines_view.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.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/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/service_request_providers/last_situation_provider.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import '../../../../new_views/common_widgets/app_filled_button.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';

class TechnicalInspectionLinesListView extends StatefulWidget {
  final AssetDeliveryTableModel deliveryTableModel;
  final AssetDeliveryDataModel? requestModel;

  TechnicalInspectionLinesListView({
    Key? key,
    required this.deliveryTableModel,
    this.requestModel,
  }) : super(key: key);

  @override
  State<TechnicalInspectionLinesListView> createState() => _TechnicalInspectionLinesListViewState();
}

class _TechnicalInspectionLinesListViewState extends State<TechnicalInspectionLinesListView> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool viewOnly = false;
  bool isLoading = false;
  AssetDeliveryProvider? assetDeliveryProvider;
  List<DeliveryLineModel> technicalInspectionLinesList = [];

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
    super.initState();
  }

  void getInitialData() async {
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
    viewOnly = widget.deliveryTableModel.status?.value != 3;
    isLoading = true;
    setState(() {});
    technicalInspectionLinesList = await assetDeliveryProvider!.getTechnicalInspectionLinesListById(
      //TODO uncommit this after testing @waseem
      itemId: widget.deliveryTableModel.id,
      // itemId: 2,
    );
    isLoading = false;
    setState(() {});
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      // appBar: DefaultAppBar(
      //   title: 'Technical Inspection'.addTranslation,
      //   titleStyle: AppTextStyles.heading3.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
      // ),
      body: Form(
        key: _formKey,
        child: (isLoading)
            ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
            : (technicalInspectionLinesList.isEmpty)
                ? const NoDataFound().center
                : Column(
                    children: [
                      SingleChildScrollView(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          children: [
                            ListView.separated(
                              padding: const EdgeInsets.all(0),
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                              itemCount: technicalInspectionLinesList.length + 1,
                              // +1 for the header
                              separatorBuilder: (_, __) => 8.height,
                              itemBuilder: (context, index) {
                                if (index == 0) {
                                  return Text(
                                    "Lines",
                                    style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
                                  );
                                }

                                final DeliveryLineModel model = technicalInspectionLinesList[index - 1];
                                return AssetDeliveryLineCard(
                                  deliveryLineModel: model,
                                  isViewOnly: viewOnly,
                                  isTechnical: true,
                                  editPress: () {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => UpdateTechnicalInspectionLinesView(
                                          requestModel: widget.requestModel,
                                          deliveryTableModel: widget.deliveryTableModel,
                                          deliveryLineModel: model,
                                        ),
                                      ),
                                    );
                                  },
                                );
                              },
                            )
                          ],
                        ),
                      ).expanded,
                      FooterActionButton.footerContainer(
                        context: context,
                        child: !viewOnly
                            ? Column(
                                children: [
                                  AppFilledButton(buttonColor: AppColor.primary10, label: 'Attachments'.addTranslation, maxWidth: true, onPressed: _attachmentTap),
                                  16.height,
                                  Row(
                                    children: [
                                      AppFilledButton(
                                        label: 'Cancel'.addTranslation,
                                        maxWidth: true,
                                        buttonColor: AppColor.background(context),
                                        // textColor: context.isDark ? AppColor.neutral30 : Colors.white,
                                        textColor: AppColor.red30,
                                        showBorder: true,
                                        onPressed: _cancelTap,
                                      ).expanded,
                                      12.width,
                                      AppFilledButton(buttonColor: AppColor.green70, label: 'Change Status'.addTranslation, maxWidth: true, onPressed: _changeStatusTap).expanded,
                                    ],
                                  ),
                                ],
                              )
                            : Row(
                                children: [
                                  AppFilledButton(
                                      buttonColor: AppColor.white60,
                                      label: 'Attachments'.addTranslation,
                                      maxWidth: true,
                                      textColor: AppColor.black10,
                                      onPressed: () {
                                        HelperFunction.attachmentTap(
                                            context: context, viewOnly: true, assetDeliveryProvider: assetDeliveryProvider!, deliveryTableItemId: widget.deliveryTableModel.id);
                                      }).expanded,
                                  8.width,
                                  AppFilledButton(buttonColor: AppColor.primary10, label: 'Next'.addTranslation, maxWidth: true, onPressed: _nextTap).expanded,
                                ],
                              ),
                      ),
                    ],
                  ),
      ),
    );
  }

//May be need to show data.
  Widget inspectionDetails() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Inspected by'.addTranslation,
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
        ),
        8.height,
        Text(
          'Mahmoud Shrouf'.addTranslation,
          style: AppTextStyles.bodyText2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral120),
        ),
        8.height,
        Text(
          'Approved by'.addTranslation,
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
        ),
        8.height,
        Text(
          'Mahmoud Shrouf'.addTranslation,
          style: AppTextStyles.bodyText2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral120),
        ),
        8.height,
        Text(
          'Inspected Date/Time From'.addTranslation,
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
        ),
        8.height,
        Text(
          '19 August, 2025'.addTranslation,
          style: AppTextStyles.bodyText2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral120),
        ),
        8.height,
        Text(
          'Inspected Date/Time To'.addTranslation,
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
        ),
        8.height,
        Text(
          '19 August, 2025'.addTranslation,
          style: AppTextStyles.bodyText2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral120),
        ),
      ],
    );
  }

  void _changeStatusTap() async {
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    await assetDeliveryProvider?.changeDeliveryStatus(itemId: widget.deliveryTableModel.id).then((status) async {
      Navigator.pop(context);
      if (status) {
        Navigator.pop(context);
        await assetDeliveryProvider?.getAssetDeliveryTableListById(requestId: widget.requestModel?.id);
      }
    });
  }

  void _attachmentTap() async {
    HelperFunction.attachmentTap(context: context, assetDeliveryProvider: assetDeliveryProvider!, deliveryTableItemId: widget.deliveryTableModel.id);
    // Navigator.push(
    //     context,
    //     MaterialPageRoute(
    //         builder: (context) => AssetDeliveryAttachmentView(
    //               tableItemId: widget.deliveryTableModel.id,
    //             )));
  }

  void _cancelTap() async {
    HelperFunction.cancelRequest(context: context, itemId: widget.deliveryTableModel.id!, requestId: widget.requestModel?.id);
    // showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    // await assetDeliveryProvider?.changeDeliveryStatusToCancel(itemId: widget.deliveryTableModel.id).then((status) async {
    //   Navigator.pop(context);
    //   if (status) {
    //     Navigator.pop(context);
    //     await assetDeliveryProvider?.getAssetDeliveryTableListById(requestId: widget.requestModel?.id);
    //   }
    // });
  }

  void _nextTap() async {
    // Navigator.push(
    //     context,
    //     MaterialPageRoute(
    //         builder: (context) => EndUserCostCenterLIstView(
    //               requestModel: widget.requestModel,
    //               deliveryTableModel: widget.deliveryTableModel,
    //             )));

    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => AssetDeliveryStageTabPage(
                  title: 'End-User Acceptance'.addTranslation,
                  detailWidget: EndUserCostCenterLIstView(
                    deliveryTableModel: widget.deliveryTableModel,
                    requestModel: widget.requestModel,
                  ),
                  tableId: widget.deliveryTableModel.id,
                )));
  }
}
