import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/urls.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/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/medical_gas_inspection/create_medical_gas_request_page.dart';
import 'package:test_sa/modules/medical_gas_inspection/models/medical_gas_data_model.dart';
import 'package:test_sa/modules/medical_gas_inspection/providers/medical_gas_inspection_provider.dart';
import 'package:test_sa/modules/medical_gas_inspection/update_delivery_notes_page.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/images/files_list.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';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';

class MedicalGasInspectionDetailPage extends StatefulWidget {
  static const String id = "/medical-gas-inspection-detail-page";
  final int inspectionId;
  final String? prority;

  MedicalGasInspectionDetailPage({Key? key, required this.inspectionId, this.prority}) : super(key: key);

  @override
  State<MedicalGasInspectionDetailPage> createState() => _MedicalGasInspectionDetailPageState();
}

class _MedicalGasInspectionDetailPageState extends State<MedicalGasInspectionDetailPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadData();
    });
  }

  MedicalGasDataModel? model;
  bool _isLoading = true;

  Future<void> _loadData() async {
    final result = await context.read<MedicalGasInspectionProvider>().getMedicalGasById(requestId: widget.inspectionId);
    setState(() {
      model = result;
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const DefaultAppBar(title: "Request Details"),
        body: _isLoading
            ? SizedBox.expand(child: CircularProgressIndicator(color: AppColor.loadingColor(context)).center)
            : model == null
                ? const NoDataFound().center
                : Column(
                    children: [
                      ListView(
                        padding: const EdgeInsets.all(16),
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              //Need to return the status form api backend
                              Row(
                                children: [
                                  if (widget.prority != null) ...[
                                    StatusLabel(
                                      label: widget.prority,
                                      textColor: AppColor.getRequestStatusTextColorByName(context, widget.prority),
                                      backgroundColor: AppColor.getRequestStatusColorByName(context, widget.prority),
                                    ),
                                    8.width,
                                  ],
                                  StatusLabel(
                                    label: model?.requestStatus?.name,
                                    textColor: AppColor.getHistoryLogStatusTextColorByName(context, model?.requestStatus?.name ?? ''),
                                    backgroundColor: AppColor.getHistoryLogStatusColorByName(context, model?.requestStatus?.name ?? ''),
                                  ),
                                  1.width.expanded,
                                  InfoDateWidget(model!.requestedDate?.toString() ?? ""),
                                ],
                              ),
                              8.height,
                              InfoHeader16Widget("Request Details"),
                              InfoTextWidget(label: context.translation.requestNo, value: model?.requestNumber ?? '-', copyValue: true),
                              InfoTextWidget(label: 'Requested by', value: model?.requestedBy ?? '-'),
                              if (model?.lastModifiedBy != null)
                                InfoTextWidget(label: 'Last Modified by', value: model?.lastModifiedBy ?? '-'),
                              InfoTextWidget(label: 'Order Type', value: model?.requestOrderType ?? '-'),
                              InfoTextWidget(label: 'Item Type', value: model?.itemType ?? '-'),
                              InfoTextWidget(label: 'Site', value: model?.site ?? '-'),
                              InfoTextWidget(label: 'Supplier Name', value: model?.supplier ?? '-'),
                              InfoTextWidget(label: 'Supplier Contact', value: model?.contact ?? '-'),
                              InfoTextWidget(label: 'Supplier Email', value: model?.email ?? '-'),
                              if (model!.deliveryNoteAttachmentDto.isNotEmpty) ...[
                                const Divider().defaultStyle(context),
                                InfoHeader16Widget("Attachments".addTranslation),
                                FilesList(images: model!.deliveryNoteAttachmentDto.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []),
                              ],
                            ],
                          ).toShadowContainer(context,),
                        ],
                      ).expanded,
                      if (model?.requestStatus?.value != null && model!.requestStatus!.value! < 3)
                        FooterActionButton.footerContainer(
                          context: context,
                          child: AppFilledButton(
                              buttonColor: AppColor.primary10,
                              label: model?.isSubmitted == true ? "Upload Delivery Note" : 'Update',
                              onPressed: () async {
                                if (model?.isSubmitted == true) {
                                  bool? isRefresh = await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateDeliveryNotes(dataModel: model)));
                                  if (isRefresh == true) {
                                    _loadData();
                                  }
                                  return;
                                }
                                bool? isRefresh = await Navigator.of(context).push(MaterialPageRoute(builder: (_) => CreateMedicalGasRequestPage(dataModel: model)));
                                if (isRefresh == true) {
                                  _loadData();
                                }
                              }),
                        ),
                    ],
                  ));
  }

  Widget labelValueText(BuildContext context, String label, String? value) {
    if (value == null || value.isEmpty) return const SizedBox.shrink();

    return Padding(
      padding: const EdgeInsets.only(bottom: 4),
      child: Text(
        '$label: $value',
        style: AppTextStyles.bodyText.copyWith(
          color: context.isDark ? AppColor.neutral30 : AppColor.neutral120,
        ),
      ),
    );
  }
}
