import 'dart:convert';
import 'dart:developer';
import 'package:date_picker_timeline/extra/color.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/enum_extensions.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/helper/utils.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_inspection_form_model.dart';
import 'package:test_sa/modules/asset_delivery_module/models/delivery_line_model.dart';
import 'package:test_sa/modules/asset_delivery_module/models/inspection_person_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/delivery_inspection/cost_center_form_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/delivery_inspection/inpection_bottomsheet.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/technical_inspection_lines_list_view.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/attachment_type_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/default_app_bar.dart';
import 'package:test_sa/views/widgets/date_and_time/time_picker.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/new_views/swipe_module/dialoge/acknowledge_work_dialog.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.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';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import '../../../../new_views/common_widgets/app_filled_button.dart';

class DeliveryInspectionFormView extends StatefulWidget {
  static const String id = "/delivery-inspection-form";
  final AssetDeliveryTableModel deliveryTableModel;
  final AssetDeliveryDataModel? requestModel;

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

  @override
  State<DeliveryInspectionFormView> createState() => _DeliveryInspectionFormViewState();
}

class _DeliveryInspectionFormViewState extends State<DeliveryInspectionFormView> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool viewOnly = false;
  AssetDeliveryProvider? assetDeliveryProvider;
  DeliveryInspectionFormModel model = DeliveryInspectionFormModel();
  bool isLoading = false;

  @override
  void initState() {
    viewOnly = widget.deliveryTableModel.status?.value != 2;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
    super.initState();
  }

  void getInitialData() async {
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
    setState(() {
      isLoading = true;
    });
    final results = await Future.wait([
      assetDeliveryProvider!.getAssetDeliveryInspectionData(
        itemId: widget.deliveryTableModel.id,
      ),
      assetDeliveryProvider!.getDeliveryLinesListById(
        itemId: widget.deliveryTableModel.id,
      ),
    ]);
    model = results[0] as DeliveryInspectionFormModel;
    if (mounted) {
      setState(() {
        isLoading = false;
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      body: isLoading
          ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
          : Form(
              key: _formKey,
              child: Column(
                children: [
                  SingleChildScrollView(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        spacing: 12,
                        children: [
                          if (!viewOnly) ...[inspectionDetailsForm()] else ...[inspectionDetails()],
                          InfoHeader16Widget("Lines"),
                          linesList(context),
                        ],
                      )).expanded,
                  FooterActionButton.footerContainer(
                    context: context,
                    child: !viewOnly
                        ? Column(
                            children: [
                              Row(
                                children: [
                                  AppFilledButton(
                                      buttonColor: AppColor.primary10,
                                      label: 'Attachments'.addTranslation,
                                      maxWidth: true,
                                      onPressed: () {
                                        HelperFunction.attachmentTap(context: context, assetDeliveryProvider: assetDeliveryProvider!, deliveryTableItemId: widget.deliveryTableModel.id);
                                      }).expanded,
                                  12.width,
                                  AppFilledButton(buttonColor: AppColor.primary10, label: 'Save'.addTranslation, maxWidth: true, onPressed: _saveTap).expanded,
                                ],
                              ),
                              12.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,
                            ],
                          ),
                  ),
                ],
              ),
            ),
    );
  }

  Widget linesList(BuildContext context) {
    return Consumer<AssetDeliveryProvider>(builder: (context, provider, child) {
      List<DeliveryLineModel> linesList = provider.deliveryLinesList;
      return provider.isDeliveryLineListLoading
          ? SizedBox.expand(child: CircularProgressIndicator(color: AppColor.loadingColor(context)).center)
          : linesList.isEmpty
              ? const NoDataFound().center
              : ListView.separated(
                  itemCount: linesList.length,
                  separatorBuilder: (_, __) => 12.height,
                  padding: EdgeInsets.zero,
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemBuilder: (listContext, itemIndex) {
                    DeliveryLineModel model = linesList[itemIndex];
                    return AssetDeliveryLineCard(
                      deliveryLineModel: model,
                      isViewOnly: viewOnly,
                      editPress: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => CostCenterFormView(
                                      itemNo: model.itemNumber,
                                      lineId: model.id,
                                      isHmg: widget.requestModel?.isHMG,
                                      tableItemId: widget.deliveryTableModel.id,
                                      requestId: widget.requestModel?.id,
                                      itemDescription: model.itemDescription,
                                    )));
                      },
                    );
                  },
                );
    });
  }

  void calculateTotalTime() {
    final from = model.deliveryInspectionInspectedDateFrom;
    final to = model.deliveryInspectionInspectedDateTo;

    if (from == null || to == null) {
      model.totalTime = null;
      return;
    }

    final diffInSeconds = to.difference(from).inSeconds;

    if (diffInSeconds < 0) {
      model.totalTime = null;
      return;
    }

    final hours = diffInSeconds / 3600;
    model.totalTime = num.parse(hours.toStringAsFixed(3));
  }

  Widget inspectionDetailsForm() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 12,
      children: [
        _inspectionTile(
          title: 'Inspected by'.addTranslation,
          model: model.inspectedByModel,
          isHmg: widget.requestModel?.isHMG == true,
          onTap: () async {
            final result = await showInspectionBottomSheet(
              context,
              title: 'Inspected by'.addTranslation,
              isHmg: widget.requestModel?.isHMG == true,
              initialModel: model.inspectedByModel ?? InspectionPersonModel(),
            );
            if (result != null) {
              setState(() => model.inspectedByModel = result);
            }
          },
        ),
        _inspectionTile(
          title: 'Approved by'.addTranslation,
          model: model.approvedByModel,
          isHmg: widget.requestModel?.isHMG == true,
          onTap: () async {
            final result = await showInspectionBottomSheet(
              context,
              title: 'Approved by'.addTranslation,
              isHmg: widget.requestModel?.isHMG == true,
              initialModel: model.approvedByModel ?? InspectionPersonModel(),
            );
            if (result != null) {
              setState(() => model.approvedByModel = result);
            }
          },
        ),
        if (widget.requestModel?.paymentTerm?.value == 2) ...[
          _inspectionTile(
            title: 'ThirdApprover'.addTranslation,
            model: model.thirdApprovalModel,
            isHmg: widget.requestModel?.isHMG == true,
            onTap: () async {
              final result = await showInspectionBottomSheet(
                context,
                title: 'ThirdApprover'.addTranslation,
                isHmg: widget.requestModel?.isHMG == true,
                initialModel: model.thirdApprovalModel ?? InspectionPersonModel(),
              );
              if (result != null) {
                setState(() => model.thirdApprovalModel = result);
              }
            },
          ),
        ],
        ADatePicker(
          label: 'Inspected Date/Time From'.addTranslation,
          hideShadow: true,
          height: 56.toScreenHeight,
          backgroundColor: AppColor.fieldBgColor(context),
          date: model.deliveryInspectionInspectedDateFrom,
          from: DateTime(DateTime.now().year, 1, 1),
          formatDateWithTime: true,
          onDatePicker: (selectedDate) async {
            final selectedTime = await showThemedTimePicker(
              context: context,
              initialTime: TimeOfDay.now(),
            );
            if (selectedTime == null) return;

            final fromDateTime = DateTime(
              selectedDate.year,
              selectedDate.month,
              selectedDate.day,
              selectedTime.hour,
              selectedTime.minute,
            );

            if (!_validateInspectionDates(from: fromDateTime, to: model.deliveryInspectionInspectedDateTo)) {
              return; // invalid, do not assign
            }
            model.deliveryInspectionInspectedDateFrom = fromDateTime;
            setState(() {});
          },
        ),
        ADatePicker(
          label: 'Inspected Date/Time To'.addTranslation,
          hideShadow: true,
          height: 56.toScreenHeight,
          backgroundColor: AppColor.fieldBgColor(context),
          date: model.deliveryInspectionInspectedDateTo,
          from: model.deliveryInspectionInspectedDateFrom,
          formatDateWithTime: true,
          onDatePicker: (selectedDate) async {
            if (model.deliveryInspectionInspectedDateFrom == null) {
              "Please select time to first".showToast;
              return;
            }

            final selectedTime = await showThemedTimePicker(
              context: context,
              initialTime: TimeOfDay.now(),
            );
            if (selectedTime == null) return;

            final toDateTime = DateTime(
              selectedDate.year,
              selectedDate.month,
              selectedDate.day,
              selectedTime.hour,
              selectedTime.minute,
            );

            if (!_validateInspectionDates(from: model.deliveryInspectionInspectedDateFrom, to: toDateTime)) {
              return; // invalid, do not assign
            }

            model.deliveryInspectionInspectedDateTo = toDateTime;
            setState(() {});
          },
        ),
        InfoTextWidget(label: 'Total Time'.addTranslation, value: formatInspectionDuration(model.totalTime)),
      ],
    ).toShadowContainer(context, borderRadius: 20, padding: 12);
  }

  bool _validateInspectionDates({DateTime? from, DateTime? to}) {
    if (from == null && to == null) return true;
    if (from != null) {
      if (from.isAfter(DateTime.now())) {
        "Time From cannot be in the future".showToast;
        return false;
      }
      if (to != null && from.isAfter(to)) {
        "Time To cannot be after Time From".showToast;
        return false;
      }
    }
    if (to != null) {
      if (to.isAfter(DateTime.now())) {
        "Time To cannot be in the future".showToast;
        return false;
      }
      if (from != null && to.isBefore(from)) {
        "Timer To cannot be before from time".showToast;
        return false;
      }
    }

    if (from != null && to != null) {
      final diffInSeconds = to.difference(from).inSeconds;
      if (diffInSeconds < 0) {
        model.totalTime = null;
        return false;
      }
      final hours = diffInSeconds / 3600.0;
      model.totalTime = num.parse(hours.toStringAsFixed(3));
    } else {
      model.totalTime = null;
    }

    return true;
  }

  String formatInspectionDuration(num? hours) {
    if (hours == null) return '-';

    if (hours < 1) {
      final minutes = (hours * 60).round();
      return '$minutes minutes';
    }

    return '${hours.toStringAsFixed(2)} hours';
  }

  Widget inspectionDetails() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 4,
      children: [
        InfoTextWidget(label: "Inspected by", value: "\n${model.deliveryInspectionInspectedBy ?? '-'}"),
        InfoTextWidget(label: "Approved by", value: "\n${model.deliveryInspectionApprovedBy ?? '-'}"),
        InfoTextWidget(label: 'Inspected Date/Time From'.addTranslation, value: "\n${model.deliveryInspectionInspectedDateFrom?.toString().toServiceRequestDetailsFormat ?? '-'}"),
        InfoTextWidget(label: 'Inspected Date/Time To'.addTranslation, value: "\n${model.deliveryInspectionInspectedDateTo?.toString().toServiceRequestDetailsFormat ?? '-'}"),
        InfoTextWidget(label: 'Total Time'.addTranslation, value: "\n${formatInspectionDuration(model.totalTime) ?? '-'}"),
      ],
    ).toShadowContainer(context);
  }

  Widget _inspectionTile({
    required String title,
    InspectionPersonModel? model,
    required bool isHmg,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: AppColor.background(context),
          border: Border.all(color: AppColor.border2Color(context), width: 1),
          borderRadius: BorderRadius.circular(16),
        ),
        child: Row(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                InfoTextLabelWidget(label: title, textStyle: AppTextStyles.textFieldLabelStyle),
                4.height,
                InfoTextLabelWidget(label: model?.name?.isNotEmpty == true ? model!.name! : 'Tap to add'.addTranslation, textStyle: AppTextStyles.bodyText),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void _cancelTap() async {
    HelperFunction.cancelRequest(context: context, itemId: widget.deliveryTableModel.id!, requestId: widget.requestModel?.id);
    // showDialog(
    //   context: context,
    //   builder: (BuildContext cxt) => AcknowledgeWorkDialog(
    //     message: "Are you sure you want to mark this request as cancel ",
    //     confirmButtonText: 'Ok',
    //     cancelButtonText: 'Cancel',
    //     onSave: () async {
    //       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);
    //         }
    //       });
    //     },
    //     onDiscard: () {},
    //   ),
    // );
  }

  void _saveTap() async {
    _formKey.currentState!.save();
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    model.assetDeliveryExternalDeliveryId = widget.deliveryTableModel.id;
    await assetDeliveryProvider!.saveMasterInfoDeliveryInspection(requestPayload: model.toJson()).then((status) async {
      Navigator.pop(context);
      if (status) {
        Navigator.pop(context);
        await assetDeliveryProvider!.getAssetDeliveryTableListById(requestId: widget.requestModel?.id);
      }
    });
  }

  void _nextTap() {
    if (widget.deliveryTableModel.isContainsTechnicalInspection == true) {
      // Navigator.push(
      //     context,
      //     MaterialPageRoute(
      //         builder: (context) => TechnicalInspectionLinesListView(
      //               deliveryTableModel: widget.deliveryTableModel,
      //               requestModel: widget.requestModel,
      //             ))
      // );
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => AssetDeliveryStageTabPage(
                    title: 'Technical Inspection'.addTranslation,
                    detailWidget: TechnicalInspectionLinesListView(
                      deliveryTableModel: widget.deliveryTableModel,
                      requestModel: widget.requestModel,
                    ),
                    tableId: widget.deliveryTableModel.id,
                  )));
    } else {
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => AssetDeliveryStageTabPage(
                    title: 'End-User Acceptance'.addTranslation,
                    detailWidget: EndUserCostCenterLIstView(
                      deliveryTableModel: widget.deliveryTableModel,
                      requestModel: widget.requestModel,
                    ),
                    tableId: widget.deliveryTableModel.id,
                  )));
      // Navigator.push(
      //     context,
      //     MaterialPageRoute(
      //         builder: (context) => EndUserCostCenterLIstView(
      //               deliveryTableModel: widget.deliveryTableModel,
      //               requestModel: widget.requestModel,
      //             )));
    }
  }

  void _changeStatusTap() async {
    _formKey.currentState!.save();
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    // await assetDeliveryProvider!.changeDeliveryStatus(requestPayload: model.toJson()).then((status) async {
    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);
      }
    });
  }

  Future<InspectionPersonModel?> showInspectionBottomSheet(
    BuildContext context, {
    required String title,
    required bool isHmg,
    required InspectionPersonModel initialModel,
  }) {
    return showModalBottomSheet<InspectionPersonModel>(
      context: context,
      isScrollControlled: true,
      backgroundColor: AppColor.bottomSheetColor(context),
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (_) {
        if (initialModel.localSignature == null && initialModel.signature != null) {
          initialModel.localSignature = signatureFromString(initialModel.signature);
        }
        return InspectionPersonBottomSheet(
          title: title,
          isHmg: isHmg,
          tableId: widget.deliveryTableModel.id,
          model: InspectionPersonModel(
            name: initialModel.name,
            email: initialModel.email,
            signature: initialModel.signature,
            localSignature: initialModel.localSignature,
          ),
        );
      },
    );
  }

  Uint8List? signatureFromString(String? value) {
    if (value == null || !value.contains('|')) return null;
    final base64Part = value.split('|').last;
    return base64Decode(base64Part);
  }
}
