import 'dart:io';

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/internal_audit_module/models/equipment_internal_audit_data_model.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_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/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';

class EquipmentInternalAuditDetailPage extends StatefulWidget {
  static const String id = "/details-internal-audit";

  final int auditId;

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

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

class _EquipmentInternalAuditDetailPageState extends State<EquipmentInternalAuditDetailPage> {
  bool isWoType = true;
  EquipmentInternalAuditDataModel? 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.getEquipmentInternalAuditById(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();
            if (model == null) return NoDataFound(message: context.translation.noDataFound).center;
            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,
                            ),
                            // textColor: AppColor.green15,
                            // backgroundColor: AppColor.greenStatus(context),
                          ),
                          Text(
                            model!.createdDate!.toString().toServiceRequestCardFormat,
                            textAlign: TextAlign.end,
                            style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                          )
                        ],
                      ),
                      8.height,
                      assetDetails(),
                      8.height,
                      requestDetails(),
                      8.height,
                      if (model?.remarks?.isNotEmpty ?? false) ...[
                        const Divider().defaultStyle(context),
                        InfoHeader16Widget("Remarks"),
                        Text(model!.remarks??'',style: AppTextStyles.bodyText2.copyWith(color: AppColor.lightTextColor(context)),),
                        8.height,
                      ],
                      if (allAttachments.isNotEmpty) ...[
                        const Divider().defaultStyle(context),
                        Text(
                          "Attachments".addTranslation,
                          style: AppTextStyles.heading4.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                        ),
                        8.height,
                        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: (_) => UpdateEquipmentInternalAuditPage(model: model),
                            ),
                          );
                          if (result == true) {
                            await getAuditData();
                            setState(() {}); // refresh UI with new model
                          }
                          // Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateEquipmentInternalAuditPage(model: model)));
                        }),
                  ),
              ],
            );
          },
        ));
  }

  Widget workOrderInformation() {
    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,
        '${context.translation.woNumber}: ${'-'}'.bodyText(context),
        '${'WO Type'.addTranslation}: ${'-'}'.bodyText(context),
        '${context.translation.site}: ${'-'}'.bodyText(context),
        '${context.translation.assetName}: ${'-'}'.bodyText(context),
        '${context.translation.manufacture}: ${'-'}'.bodyText(context),
        '${context.translation.model}: ${'-'}'.bodyText(context),
      ],
    );
  }

  Widget requestDetails() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("Request Details"),
        InfoTextWidget(label: context.translation.requestNo, value: model?.requestNo ?? '-', copyValue: true),
        if (model != null && model!.equipmentsFindings != null && model!.equipmentsFindings!.isNotEmpty)
          ...model!.equipmentsFindings!.map((item) {
            final findingName = item.finding?.name ?? 'Unknown';
            return checklistWidget(value: findingName.addTranslation);
          }).toList()
        else
          Text('No findings available'.addTranslation),
      ],
    );
  }

  Widget assetDetails() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("Asset Information"),
        InfoTextWidget(label: context.translation.assetName, value: model?.asset?.assetName ?? '-'),
        InfoTextWidget(label: context.translation.assetNo, value: model?.asset?.assetNumber ?? '-', copyValue: true),
        InfoTextWidget(label: context.translation.serialNumber, value: model?.asset?.assetNumber ?? '-'),
        InfoTextWidget(label: context.translation.manufacture, value: model?.asset?.manufacturerName ?? '-'),
        InfoTextWidget(label: context.translation.model, value: model?.asset?.modelName ?? '-'),
        InfoTextWidget(label: context.translation.site, value: model?.asset?.siteName ?? '-'),
        InfoTextWidget(label: context.translation.department, value: model?.asset?.departmentName ?? '-'),
      ],
    );
  }

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