import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.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/enums/user_types.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/modules/traf_module/traf_request_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/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.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 '../../controllers/api_routes/urls.dart';
import 'asset_analytics_model.dart';
import 'traf_request_model.dart';

class TrafRequestDetailPage extends StatefulWidget {
  static const String id = "/details-TRAF";

  final int trafId;

  TrafRequestDetailPage({Key? key, required this.trafId}) : super(key: key);

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

class _TrafRequestDetailPageState extends State<TrafRequestDetailPage> {
  List<File> _attachments = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<TrafRequestProvider>(context, listen: false).getTRAFById(widget.trafId);
    });
  }

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

  @override
  Widget build(BuildContext context) {
    bool isEngineer = (Provider.of<UserProvider>(context, listen: false).user?.type) == UsersTypes.engineer;
    return Scaffold(
        appBar: const DefaultAppBar(title: "Assessment of Need & Technology"),
        body: Selector<TrafRequestProvider, bool>(
          selector: (_, myModel) => myModel.isLoading, // Selects only the userName
          builder: (_, isLoading, __) {
            if (isLoading) return const ALoading();
            TrafRequestProvider trafProvider = Provider.of<TrafRequestProvider>(context, listen: false);
            if (trafProvider.trafRequestDataModel?.attachments != null) {
              _attachments = trafProvider.trafRequestDataModel!.attachments!.whereType<GenericAttachmentModel>().map((e) => File(URLs.getFileUrl(e.name ?? '') ?? '')).toList();
            }
            return trafProvider.trafRequestDataModel == null
                ? const NoDataFound().center
                : Column(
                    children: [
                      ListView(
                        padding: const EdgeInsets.all(16),
                        children: [
                          requesterInformation(trafProvider.trafRequestDataModel!),
                          12.height,
                          requestInformation(trafProvider.trafRequestDataModel!),
                          12.height,
                          assetInformation(trafProvider.trafRequestDataModel!),
                        ],
                      ).expanded,
                      // // if (isEngineer)
                      // FooterActionButton.footerContainer(
                      //   context: context,
                      //   child: AppFilledButton(
                      //       buttonColor: AppColor.primary10,
                      //       label: "Update",
                      //       onPressed: () {
                      //         Navigator.pushNamed(context, UpdateTrafRequestPage.id);
                      //       }),
                      // ),
                    ],
                  );
          },
        ));
  }

  Widget requesterInformation(TrafRequestDataModel data) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("Requester Information".addTranslation),
        InfoTextWidget(label: context.translation.employeeId, value: data.employeeIdForDisplay ?? '-'),
        InfoTextWidget(label: context.translation.name, value: data.employeeName ?? '-'),
        InfoTextWidget(label: context.translation.email, value: data.employeeEmail ?? '-'),
        InfoTextWidget(label: 'Position'.addTranslation, value: data.positionName ?? '-'),
        InfoTextWidget(label: context.translation.site, value: data.siteName ?? '-'),
        InfoTextWidget(label: context.translation.department, value: data.departmentName ?? '-'),
        InfoTextWidget(label: 'Number/Contact Information'.addTranslation, value: data.requesterContactNumber ?? '-'),
        InfoTextWidget(label: 'Extension'.addTranslation, value: data.requesterExtensionNumber ?? '-'),
      ],
    ).toShadowContainer(context);
  }

  Widget requestInformation(TrafRequestDataModel data) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("Request Information"),
        InfoTextWidget(label: 'Request No', value: data.reqCode ?? '-', copyValue: true),
        InfoTextWidget(label: 'Request type', value: data.requestTypeName ?? '-'),
        if (data.requestTypeValue == 1) ...[
          4.height,
          'Requested Quantity: ${data.qty ?? '-'}'.bodyText(context), //todo @waseem replace with infotext
        ],
        InfoTextWidget(label: 'How would the requested technology solve the current situation and/or serve the purpose?', value: "\n${data.purposeAnswer ?? '-'}"),
        InfoTextWidget(label: 'What is the current practice?', value: "\n${data.currentPractise ?? '-'}"),
        InfoTextWidget(label: 'Census Q1', value: data.censusQ1 ?? '-'),
        InfoTextWidget(label: 'Census Q2', value: data.censusQ2 ?? '-'),
        InfoTextWidget(label: 'Census Q3', value: data.censusQ3 ?? '-'),
        InfoTextWidget(label: 'Census Q4', value: data.censusQ4 ?? '-'),
        InfoTextWidget(
            label: 'List down names & contact information of users going to use the technology & specify if they are part-time or full time?',
            value: "\n${data.trafContacts?.map((item) => item.name).toList().toString() ?? '-'}"),
        InfoTextWidget(label: 'Is the requesting department going to use the technology solely or shared with other departments?', value: "\n${data.usingSolelyOrSharedName ?? '-'}"),
        if ((data.departments ?? []).isNotEmpty) ...[
          InfoTextWidget(label: 'Technology used with other departments', value: "\n${data.departments?.map((item) => item.departmentName).toList().toString() ?? '-'}"),
        ],
        InfoTextWidget(label: 'Would other services be effected by acquiring the new equipment?', value: "\n${data.isEffectedName ?? '-'}"),
        if ((data.effectedServices ?? "").isNotEmpty) ...[
          InfoTextWidget(label: 'List of services would it be effected', value: "\n${data.effectedServices ?? '-'}"),
        ],
        InfoTextWidget(label: 'Is the equipment going to be used with combination of other equipment to accomplish a specific procedure?', value: "\n${data.isCombinationName ?? '-'}"),
        if ((data.usedWithCombination ?? "").isNotEmpty) ...[
          InfoTextWidget(label: 'Equipment going to be used with combination of other equipments', value: "\n${data.usedWithCombination ?? '-'}"),
        ],
        if (_attachments.isNotEmpty) ...[
          4.height,
          Text(
            // todo @waseem conver to header
            "Attachments".addTranslation,
            style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
          ),
          // 8.height,
          FilesList(images: _attachments.map((e) => URLs.getFileUrl(e.path ?? '') ?? '').toList() ?? []),
        ],
      ],
    ).toShadowContainer(context);
  }

  Widget assetInformation(TrafRequestDataModel data) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("Asset Information"),
        InfoTextWidget(label: context.translation.assetName, value: data.assetName ?? '-'),
        InfoTextWidget(label: context.translation.model, value: data.modelName ?? '-'),
        InfoTextWidget(label: context.translation.manufacture, value: data.manufacturerName ?? '-'),
        if (data.requestTypeId == 733) ...[
          FutureBuilder<AssetAnalytics?>(
              future: Provider.of<TrafRequestProvider>(context, listen: false).getAssetAnalytics(data.assetId!),
              builder: (cxt, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const SizedBox.square(dimension: 24, child: CircularProgressIndicator()).center;
                }
                if (snapshot.hasData) {
                  return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                    InfoTextWidget(label: 'Last price', value: snapshot.data?.lastPrice?.toString() ?? '-'),
                    InfoTextWidget(label: 'PO', value: snapshot.data?.lastPONo ?? '-'),
                    InfoTextWidget(label: 'The quantity of the same asset', value: snapshot.data?.sameAssetQuantity?.toString() ?? '-'),
                    InfoTextWidget(label: 'Existing asset under SLA', value: snapshot.data?.slaStatus ?? '-'),
                    InfoTextWidget(label: 'Age of the asset', value: snapshot.data?.assetAgeDescription ?? '-'),
                    InfoTextWidget(label: 'Total Maintenance Cost (TMC)', value: snapshot.data?.totalMaintenanceCost?.toString() ?? '-'),
                    InfoTextWidget(label: 'Net Book Value (NBV)', value: snapshot.data?.netBookValue?.toString() ?? '-'),
                    InfoTextWidget(label: 'Mean Time Between Failure (MTBF)', value: snapshot.data?.mtbfDescription ?? '-'),
                    InfoTextWidget(label: 'Down Time (DT)', value: snapshot.data?.downTimeDescription ?? '-'),
                    InfoTextWidget(label: 'Up Time (UT)', value: snapshot.data?.upTimeDescription ?? '-'),
                    InfoTextWidget(label: 'Purchased Price', value: snapshot.data?.purchasedPrice?.toString() ?? '-'),
                  ]);
                }
                return const SizedBox();
              })
        ],
      ],
    ).toShadowContainer(context);
  }
}
