import 'dart:developer';

import 'package:flutter/gestures.dart';
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/models/generic_attachment_model.dart';
import 'package:test_sa/modules/cm_module/cm_detail_page.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/incident_module/incident_attachment_model.dart';
import 'package:test_sa/modules/incident_module/incident_data_model.dart';
import 'package:test_sa/modules/incident_module/incident_provider.dart';
import 'package:test_sa/new_views/app_style/app_color.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 IncidentDetailPage extends StatelessWidget {
  static const String id = "/incident-detail-page";
  final int incidentId;

  IncidentDetailPage({Key? key, required this.incidentId}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const DefaultAppBar(title: "Request Details"),
        body: FutureBuilder<IncidentDataModel?>(
            future: Provider.of<IncidentProvider>(context, listen: false).getIncidentById(incidentId),
            builder: (BuildContext context, AsyncSnapshot<IncidentDataModel?> snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(color: AppColor.loadingColor(context)).center;
              if (snapshot.data == null) return const NoDataFound().center;

              List<GenericAttachmentModel> allAttachments = (snapshot.data!.incidentAttachments ?? []).whereType<GenericAttachmentModel>().toList();

              return SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        StatusLabel(
                          label: snapshot.data!.incidentStatusName!,
                          textColor: AppColor.getRequestStatusTextColorByName(context, snapshot.data!.incidentStatusName!),
                          backgroundColor: AppColor.getRequestStatusColorByName(context, snapshot.data!.incidentStatusName!),
                        ),
                        1.width.expanded,
                        InfoDateWidget(snapshot.data!.createdDate?.toString() ?? ""),
                      ],
                    ),
                    // 12.height,
                    ...requesterDetails(context, snapshot.data!),
                    const Divider().defaultStyle(context),
                    ...requestDetails(context, snapshot.data!),
                    if (snapshot.data!.ovrTicketNumber?.isNotEmpty ?? false) ovrInformation(context, snapshot.data!.ovrTicketNumber!),
                    const Divider().defaultStyle(context),
                    ...assetDetails(context, snapshot.data!),
                    const Divider().defaultStyle(context),
                    ...personInvolvedDetails(context, snapshot.data!),
                    if (allAttachments.isNotEmpty) ...[
                      const Divider().defaultStyle(context),
                      InfoHeader16Widget("Attachments".addTranslation),
                      FilesList(images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []),
                    ],
                  ],
                ).toShadowContainer(context),
              );
            }));
  }

  List<Widget> requestDetails(BuildContext context, IncidentDataModel incidentData) {
    return [
      InfoHeader16Widget("Request Details"),
      InfoTextWidget(label: 'Incident No', value: incidentData.reqCode ?? "-", copyValue: true),
      InfoTextWidget(label: 'Incident Type', value: incidentData.incidentClassificationName ?? "-"),
      InfoTextWidget(label: 'Incident Title', value: incidentData.incidentTitle ?? "-"),
      InfoTextWidget(label: 'Incident Description', value: incidentData.incidentDescription ?? "-"),
      InfoTextWidget(label: 'Exist OVR', value: incidentData.existingOvrTicketName ?? "-"),
      InfoTextWidget(label: 'Site', value: incidentData.siteName ?? "-"),
      InfoTextWidget(label: 'Building', value: incidentData.buildingName ?? "-"),
      InfoTextWidget(label: 'Floor', value: incidentData.floorName ?? "-"),
      InfoTextWidget(label: 'Department', value: incidentData.departmentName ?? "-"),
      InfoTextWidget(label: 'Occurrence Date', value: incidentData.occurrenceDate?.toServiceRequestDetailsFormat ?? "-"),
      if (incidentData.workOrderId != null)
        RichText(
          text: TextSpan(text: "Work Order: ", style: AppTextStyles.bodyText2.copyWith(color: AppColor.lightTextColor(context)), children: [
            TextSpan(
                text: "${incidentData.workOrderNo}",
                style: AppTextStyles.bodyText.copyWith(color: AppColor.primary10, decoration: TextDecoration.underline),
                recognizer: TapGestureRecognizer()
                  ..onTap = () async {
                    await Navigator.of(context).push(MaterialPageRoute(builder: (_) => CMDetailPage(requestId: incidentData.workOrderId!, moduleId: 3)));
                  }),
          ]),
        ),
      InfoTextWidget(label: 'Root Cause', value: incidentData.rootCauseName ?? "-"),
      if (incidentData.rootCauseValue == 5) InfoTextWidget(label: 'Root reason', value: incidentData.otherRootCause ?? "-"),
      InfoTextWidget(label: 'Comments', value: incidentData.comments ?? "-"),
    ];
  }

  Widget ovrInformation(BuildContext context, String ovrNumber) {
    return FutureBuilder<Map<String, dynamic>?>(
        future: Provider.of<IncidentProvider>(context, listen: false).getOvrTicketDetails(ovrNumber),
        builder: (BuildContext context, AsyncSnapshot<Map<String, dynamic>?> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(color: AppColor.loadingColor(context)).center;
          if (snapshot.data == null) return const NoDataFound().center;

          Map<String, dynamic>? data = snapshot.data;
          if (data == null) return const SizedBox();
          List<String> keysList = data.keys.toList();
          return Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Divider().defaultStyle(context),
              InfoHeader16Widget("OVR Ticket Information"),
              InfoTextWidget(label: 'OVR Ticket Number', value: ovrNumber),
              for (int i = 0; i < keysList.length; i++) InfoTextWidget(label: keysList[i], value: data[keysList[i]]?.toString() ?? "-"),
            ],
          );
        });
  }

  List<Widget> personInvolvedDetails(BuildContext context, IncidentDataModel incidentData) {
    return [
      InfoHeader16Widget("Person Involved Information"),
      InfoTextWidget(label: 'Person Involved', value: incidentData.personInvolvedName ?? "-"),
      InfoTextWidget(label: 'Gender', value: incidentData.genderName ?? "-"),
      InfoTextWidget(label: 'Person Involved ID', value: incidentData.personInvolvedEmployeeId?.toString() ?? "-"),
      InfoTextWidget(label: 'Person Involved Name', value: incidentData.personInvolvedEmployeeName ?? "-"),
    ];
  }

  List<Widget> assetDetails(BuildContext context, IncidentDataModel loanData) {
    return [
      InfoHeader16Widget("Asset Information"),
      InfoTextWidget(label: context.translation.assetName, value: loanData.assetOrigin ?? "-"),
      InfoTextWidget(label: context.translation.assetNo, value: loanData.assetNumber ?? "-"),
      // '${context.translation.serialNumber}: ${loanData.assetSerialNumber ?? "-"}'.bodyText(context),
      InfoTextWidget(label: context.translation.manufacture, value: loanData.manufacturer ?? "-"),
      InfoTextWidget(label: context.translation.model, value: loanData.model ?? "-"),
    ];
  }

  List<Widget> requesterDetails(BuildContext context, IncidentDataModel incidentData) {
    return [
      InfoHeader16Widget("Requester Information"),
      InfoTextWidget(label: 'Name', value: incidentData.requesterEmployeeName ?? "-"),
      InfoTextWidget(label: 'Email', value: incidentData.requesterEmployeeEmail ?? "-"),
      InfoTextWidget(label: 'Contact', value: incidentData.requesterContactNo ?? "-"),
      InfoTextWidget(label: 'Extension', value: incidentData.requesterExtensionNo ?? "-"),
      InfoTextWidget(label: 'Site', value: incidentData.requestorSiteName ?? "-"),
      InfoTextWidget(label: 'Department', value: incidentData.requestorFlowDepartmentName ?? "-"),
    ];
  }

  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(BuildContext context, {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),
      ],
    );
  }
}
