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/loan_module/provider/loan_provider.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/loan_module/models/loan_attachment_model.dart';
import 'package:test_sa/modules/loan_module/pages/installation_form_view.dart';
import 'package:test_sa/modules/loan_module/pages/pullout_detail_page.dart';
import 'package:test_sa/modules/loan_module/provider/loan_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/app_text_form_field.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';

import '../models/loan_request_model.dart';

class LoanEquipmentDetailPage extends StatefulWidget {
  static const String id = "/loan-equipment-detail-page";
  final int loanId;

  LoanEquipmentDetailPage({Key? key, required this.loanId}) : super(key: key);

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

class _LoanEquipmentDetailPageState extends State<LoanEquipmentDetailPage> {
  @override
  void initState() {
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const DefaultAppBar(title: "Request Details"),
        body: SafeArea(
          child: FutureBuilder<LoanRequestModel?>(
              future: Provider.of<LoanProvider>(context, listen: false).getLoanById(widget.loanId),
              builder: (BuildContext context, AsyncSnapshot<LoanRequestModel?> 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!.loanAttachments ?? []).whereType<GenericAttachmentModel>().toList();

                return Column(children: [
                  ListView(
                    padding: const EdgeInsets.all(16),
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              StatusLabel(
                                label: snapshot.data!.loanStatusName!,
                                textColor: AppColor.getRequestStatusTextColorByName(context, snapshot.data!.loanStatusName!),
                                backgroundColor: AppColor.getRequestStatusColorByName(context, snapshot.data!.loanStatusName!),
                              ),
                              1.width.expanded,
                              InfoDateWidget(snapshot.data!.createdDate?.toString() ?? ""),
                            ],
                          ),
                          8.height,
                          ...requesterDetails(context, snapshot.data!),
                          const Divider().defaultStyle(context),
                          ...requestDetails(context, snapshot.data!),
                          const Divider().defaultStyle(context),
                          ...assetDetails(context, snapshot.data!),
                          const Divider().defaultStyle(context),
                          ...installationDetails(context, snapshot.data!),
                          const Divider().defaultStyle(context),
                          ...doctorDetails(context, snapshot.data!),
                          const Divider().defaultStyle(context),
                          ...vendorDetails(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)
                    ],
                  ).expanded,
                  // @todo ask backend to add loanTypeValue, so we can show or hide the buttons
                  if (snapshot.data?.loanTypeName == "Standard" &&
                      context.userProvider.isEngineer &&
                      (snapshot.data?.loanStatusValue == 4 || snapshot.data?.loanStatusValue == 5 || snapshot.data?.loanStatusValue == 8))
                    FooterActionButton.footerContainer(
                      context: context,
                      child: AppFilledButton(
                        onPressed: () async {
                          if (snapshot.data?.loanStatusValue == 4) {
                            String comment = "";
                            context.showBottomSheet(
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    'Estimated Date: ${snapshot.data?.installationEDD?.toAssetDetailsFormat ?? "-"}'.bodyText(context),
                                    16.height,
                                    AppTextFormField(
                                      labelText: context.translation.comments,
                                      showSpeechToText: true,
                                      textInputType: TextInputType.multiline,
                                      labelStyle: AppTextStyles.textFieldLabelStyle,
                                      showWithoutDecoration: true,
                                      backgroundColor: context.isDarkNotListen ? AppColor.neutral20 : AppColor.neutral100,
                                      alignLabelWithHint: true,
                                      onChange: (text) {
                                        comment = text;
                                      },
                                    ),
                                    16.height,
                                    AppFilledButton(
                                        onPressed: () async {
                                          Utils.showLoading(context);
                                          LoanProvider loanProvider = Provider.of<LoanProvider>(context, listen: false);
                                          bool isSuccess = await loanProvider.loanWorkflowAction({
                                            "userId": context.userProvider.user!.userID,
                                            "isFromMobile": true,
                                            "commentsFromMobile": comment,
                                            'loanId': snapshot.data?.id,
                                            'loanStatusId': snapshot.data?.loanStatusValue,
                                          });
                                          Utils.hideLoading(context);
                                          if (isSuccess) {
                                            Navigator.pop(context, true);
                                            setState(() {});
                                          }
                                        },
                                        label: "Delivered"),
                                  ],
                                ),
                                title: "EDD & Comments",
                                showCancelButton: true);
                            return;
                          }
                          if (snapshot.data?.loanStatusValue == 5) {
                            bool isSuccess = await Navigator.push(context, MaterialPageRoute(builder: (context) => InstallationFormView(loanData: snapshot.data))) ?? false;
                            if (isSuccess) {
                              setState(() {});
                            }
                            return;
                          }
                          bool isSuccess = await Navigator.push(context, MaterialPageRoute(builder: (context) => PullOutDetailsPage(loanData: snapshot.data))) ?? false;
                          if (isSuccess) {
                            setState(() {});
                          }
                        },
                        label: snapshot.data?.loanStatusValue == 4
                            ? "Delivered"
                            : snapshot.data?.loanStatusValue == 5
                                ? 'Installation Report'
                                : 'PullOut Report',
                      ),
                    )
                ]);
                // }),
              }),
        ));
  }

  List<Widget> requestDetails(BuildContext context, LoanRequestModel loanData) {
    return [
      InfoHeader16Widget("Request Details"),
      InfoTextWidget(label: 'Loan Type', value: loanData.loanTypeName ?? "-"),
      InfoTextWidget(label: 'Loan No', value: loanData.reqCode ?? "-", copyValue: true),
      InfoTextWidget(label: 'Loan Period', value: loanData.loanPeriodName ?? "-"),
      InfoTextWidget(label: context.translation.site, value: loanData.siteName ?? "-"),
      InfoTextWidget(label: context.translation.department, value: loanData.departmentName ?? "-"),
      InfoTextWidget(label: 'Item Description', value: loanData.itemDescription ?? "-"),
      InfoTextWidget(label: 'Request Description', value: loanData.requestDescription ?? "-"),
    ];
  }

  List<Widget> vendorDetails(BuildContext context, LoanRequestModel loanData) {
    return [
      InfoHeader16Widget("Vendor Information"),
      InfoTextWidget(label: 'Name', value: loanData.vendorName ?? "-"),
      InfoTextWidget(label: 'Representative Name', value: loanData.vendorRepName ?? "-"),
      InfoTextWidget(label: 'Contact', value: loanData.vendorContact ?? "-"),
      InfoTextWidget(label: 'Email', value: loanData.vendorEmail ?? "-"),
    ];
  }

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

  List<Widget> installationDetails(BuildContext context, LoanRequestModel loanData) {
    return [
      InfoHeader16Widget("Installation & Pullout Information"),
      InfoTextWidget(label: 'Installation EDD', value: loanData.installationEDD?.toServiceRequestDetailsFormat ?? "-"),
      InfoTextWidget(label: 'Installation Date', value: loanData.installationEDD?.toAssetDetailsFormat ?? "-"),
      InfoTextWidget(label: 'Pullout EDD', value: loanData.pulloutEDD?.toServiceRequestDetailsFormat ?? "-"),
      InfoTextWidget(label: 'Pullout Date', value: loanData.pulloutDate?.toAssetDetailsFormat ?? "-"),
    ];
  }

  List<Widget> doctorDetails(BuildContext context, LoanRequestModel loanData) {
    return [
      InfoHeader16Widget("Doctor Information"),
      InfoTextWidget(label: 'Name', value: loanData.doctorName ?? "-"),
      InfoTextWidget(label: 'Contact', value: loanData.doctorContact ?? "-"),
      InfoTextWidget(label: 'Email', value: loanData.doctorEmail ?? "-"),
    ];
  }

  List<Widget> requesterDetails(BuildContext context, LoanRequestModel loanData) {
    return [
      InfoHeader16Widget("Requester Information"),
      InfoTextWidget(label: 'Name', value: loanData.requestorUserIdForDisplay ?? "-"),
      InfoTextWidget(label: 'Email', value: loanData.requestorUserEmail ?? "-"),
      InfoTextWidget(label: 'Contact', value: loanData.requestorUserMobileNumber ?? "-"),
      InfoTextWidget(label: 'Extension', value: loanData.requesterExtensionNo ?? "-"),
    ];
  }

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