import 'dart:developer';

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/models/generic_attachment_model.dart';
import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_data_model.dart';
import 'package:test_sa/modules/internal_audit_module/pages/system_internal_audit/update_system_internal_audit_page.dart';
import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.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/app_loading.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';

class SystemInternalAuditDetailPage extends StatefulWidget {
  static const String id = "/details-system-internal-audit";
  final int auditId;

  SystemInternalAuditDetailPage({Key? key, required this.auditId}) : super(key: key);

  @override
  _SystemInternalAuditDetailPageState createState() {
    return _SystemInternalAuditDetailPageState();
  }
}

class _SystemInternalAuditDetailPageState extends State<SystemInternalAuditDetailPage> {
  bool isWoType = true;
  SystemInternalAuditDataModel? model;
  late InternalAuditProvider _internalAuditProvider;
  List<GenericAttachmentModel> allAttachments = [];

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

  Future<void> getAuditData() async {
    model = await _internalAuditProvider.getInternalSystemAuditById(widget.auditId);
    allAttachments.clear();
    allAttachments = [
      ...(model?.attachments?.whereType<GenericAttachmentModel>() ?? []),
      ...(model?.engineerData?.attachments?.whereType<GenericAttachmentModel>() ?? []),
    ];
  }

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

  @override
  Widget build(BuildContext context) {
    //TODO need to check when implementing provider needed or not .
    return Scaffold(
        appBar: const DefaultAppBar(title: "Request Details"),
        body: Selector<InternalAuditProvider, bool>(
          selector: (_, provider) => provider.isLoading,
          builder: (_, isLoading, __) {
            if (isLoading) return const ALoading();
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          StatusLabel(
                            label: model!.status!.name,
                            id: model!.status!.value,
                            radius: 4,
                            textColor: AppColor.getRequestStatusTextColorByName(
                              context,
                              model!.status!.name,
                            ),
                            backgroundColor: AppColor.getRequestStatusColorByName(
                              context,
                              model!.status!.name,
                            ),
                          ),
                          InfoDateWidget(model!.createdDate?.toString() ?? ""),
                        ],
                      ),
                      8.height,
                      workOrderInfo(),
                      const Divider().defaultStyle(context),
                      assetInfo(),
                      if (model?.findingDescription?.isNotEmpty ?? false) ...[
                        const Divider().defaultStyle(context),
                        InfoHeader16Widget("Remarks"),
                        8.height,
                        Text(
                          model!.findingDescription ?? '',
                          style: AppTextStyles.bodyText2.copyWith(color: AppColor.lightTextColor(context)),
                        ),
                      ],
                      if (allAttachments.isNotEmpty) ...[
                        const Divider().defaultStyle(context),
                        InfoHeader16Widget("Attachments".addTranslation),
                        FilesList(images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []),
                      ],
                    ],
                  ).paddingAll(0).toShadowContainer(context),
                ).expanded,
                if (context.userProvider.isEngineer && model?.status?.value != 3)
                  FooterActionButton.footerContainer(
                    context: context,
                    child: AppFilledButton(
                        buttonColor: AppColor.primary10,
                        label: "Update",
                        onPressed: () async {
                          final result = await Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (_) => UpdateSystemInternalAuditPage(model: model),
                            ),
                          );
                          if (result == true) {
                            await getAuditData();
                            setState(() {}); // refresh UI with new model
                          }
                        }),
                  ),
              ],
            );
          },
        ));
  }

  Widget workOrderInformation() {
    final details = model?.workOrderDetails;
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Divider().defaultStyle(context),
        Text(
          "WO Info",
          style: AppTextStyles.heading4.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
        ),
        6.height,
        labelValueText(context, context.translation.woNumber, details?.workOrderNo),
        labelValueText(context, 'WO Type'.addTranslation, model?.workOrderType?.name),
        labelValueText(context, context.translation.assetName, details?.woAssetName),
        labelValueText(context, context.translation.assetNo, details?.woAssetNo),
        labelValueText(context, context.translation.manufacture, details?.woManufacturer),
        labelValueText(context, context.translation.serialNumber, details?.wosn),
        labelValueText(context, context.translation.model, details?.woModel),
        labelValueText(context, context.translation.site, details?.woSite),
        labelValueText(context, context.translation.department, details?.woDepartment),
      ],
    );
  }

  Widget workOrderInfo() {
    final details = model?.workOrderDetails;
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("WO Info"),
        InfoTextWidget(label: context.translation.requestNo, value: model?.requestNo ?? '-'),
        InfoTextWidget(label: 'WO Type'.addTranslation, value: model?.workOrderType?.name ?? '-'),
        InfoTextWidget(label: context.translation.woNumber, value: details?.workOrderNo ?? '-'),
        InfoTextWidget(label: "Finding Type", value: model?.findingType?.name ?? '-'),
        InfoTextWidget(label: "Assigned Engineer", value: model?.workOrderDetails?.woAssignedEngineer ?? '-'),
      ],
    );
  }

  Widget requestDetails() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Divider().defaultStyle(context),
        InfoHeader16Widget("Request Details"),
        checklistWidget(value: 'Asset Tag'.addTranslation),
        checklistWidget(value: 'Expired PM Tag'.addTranslation),
      ],
    );
  }

  Widget assetInformation() {
    final details = model?.workOrderDetails;
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("Asset Details"),
        InfoTextWidget(label: context.translation.assetName, value: details?.woAssetName ?? '-'),
        InfoTextWidget(label: context.translation.assetNo, value: details?.woAssetNo ?? '-'),
        InfoTextWidget(label: context.translation.manufacture, value: details?.woManufacturer ?? '-'),
        InfoTextWidget(label: context.translation.model, value: details?.woModel ?? '-'),
      ],
    );
  }

  Widget assetInfo() {
    final details = model?.workOrderDetails;
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("Asset Details"),
        InfoTextWidget(label: context.translation.assetName, value: details?.woAssetName ?? '-'),
        InfoTextWidget(label: context.translation.assetNo, value: details?.woAssetNo ?? '-'),
        InfoTextWidget(label: context.translation.manufacture, value: details?.woManufacturer ?? '-'),
        InfoTextWidget(label: context.translation.serialNumber, value: details?.wosn ?? '-'),
        InfoTextWidget(label: context.translation.model, value: details?.woModel ?? '-'),
        InfoTextWidget(label: context.translation.site, value: details?.woSite ?? '-'),
        InfoTextWidget(label: context.translation.department, value: details?.woDepartment ?? '-'),
      ],
    );
  }

  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,
        ),
      ),
    );
  }

  Widget checklistWidget({required String value}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Checkbox(
          value: true,
          activeColor: AppColor.neutral120,
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          visualDensity: const VisualDensity(horizontal: -4, vertical: -3),
          onChanged: (value) {},
        ),
        value.bodyText(context),
      ],
    );
  }
}
