import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/localization/localization.dart';
import 'package:test_sa/controllers/providers/api/service_requests_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_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/translation_keys.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/service_request/service_request.dart';
import 'package:test_sa/models/subtitle.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/app_style/colors.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/pages/user/requests/create_request.dart';
import 'package:test_sa/views/pages/user/requests/report/create_service_report.dart';
import 'package:test_sa/views/widgets/buttons/app_back_button.dart';
import 'package:test_sa/views/widgets/buttons/app_button.dart';
import 'package:test_sa/views/widgets/buttons/app_icon_button.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/views/widgets/images/images_list.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/image_loader.dart';
import 'package:test_sa/views/widgets/requests/info_row.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';
import 'package:test_sa/views/widgets/sound/sound_player.dart';
import 'package:test_sa/views/widgets/titles/app_sub_title.dart';

import '../../../../models/service_request/search_work_order.dart';
import 'report/future_service_report.dart';

class RequestDetailsPage extends StatelessWidget {
  static const String id = "/call-details";
  ServiceRequest serviceRequest;

  RequestDetailsPage({Key key, this.serviceRequest}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    UserProvider _userProvider = Provider.of<UserProvider>(context);
    SettingProvider _settingProvider = Provider.of<SettingProvider>(context);
    List<SearchWorkOrder> workOrders = [];
    ServiceRequestsProvider _serviceRequestsProvider = Provider.of<ServiceRequestsProvider>(context);
    _serviceRequestsProvider.getServiceRequestObjectById(requestId: serviceRequest.id);

    Widget informationCard() {
      return Container(
        decoration: ShapeDecoration(
          color: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          shadows: const [BoxShadow(color: Color(0x07000000), blurRadius: 14, offset: Offset(0, 0), spreadRadius: 0)],
        ),
        child: Column(
          children: [
            Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    StatusLabel(
                        label: serviceRequest.priority.name,
                        id: serviceRequest.priority.id,
                        textColor: AColors.getPriorityStatusTextColor(serviceRequest.priority.id),
                        backgroundColor: AColors.getPriorityStatusColor(serviceRequest.priority.id)),
                    8.width,
                    StatusLabel(
                        label: serviceRequest.statusLabel,
                        textColor: AColors.getRequestStatusTextColor(serviceRequest.statusValue),
                        backgroundColor: AColors.getRequestStatusColor(serviceRequest.statusValue)),
                    1.width.expanded,
                    Text(serviceRequest.date.toServiceRequestCardFormat, textAlign: TextAlign.end, style: AppTextStyles.tinyFont.copyWith(color: const Color(0xFF3B3D4A))),
                  ],
                ),
                8.height,
                Text(serviceRequest.deviceEnName, style: AppTextStyles.heading5.copyWith(color: const Color(0xFF3B3D4A))),
                Text(
                  '${context.translation.assetNumber}:  ${serviceRequest.device.number}',
                  style: AppTextStyles.bodyText.copyWith(color: Color(0xFF757575)),
                ),
                Text(
                  'Request Type: ${serviceRequest.type.name}',
                  style: AppTextStyles.bodyText.copyWith(color: Color(0xFF757575)),
                ),
                Text(
                  'Request No: ${serviceRequest.requestCode}',
                  style: AppTextStyles.bodyText.copyWith(color: Color(0xFF757575)),
                ),
                8.height,
                const Divider(color: Color(0xFFEAF1F4), height: 1, thickness: 1),
                8.height,
                Text(
                  'Manufacture: ${serviceRequest.device.modelDefinition.manufacturerName}',
                  style: AppTextStyles.bodyText.copyWith(color: Color(0xFF757575)),
                ),
                Text(
                  'Model: ${serviceRequest.device.modelDefinition.modelName}',
                  style: AppTextStyles.bodyText.copyWith(color: Color(0xFF757575)),
                ),
                8.height,
                const Divider(color: Color(0xFFEAF1F4), height: 1, thickness: 1),
                8.height,
                if ((serviceRequest.callComments ?? "").isNotEmpty) ...[
                  Text(
                    serviceRequest.callComments,
                    style: AppTextStyles.bodyText.copyWith(color: Color(0xFF757575)),
                  ),
                  8.height,
                  const Divider(color: Color(0xFFEAF1F4), height: 1, thickness: 1),
                ],
                if (serviceRequest.devicePhotos.isNotEmpty) ...[
                  FilesList(images: serviceRequest.devicePhotos),
                  const Divider(color: Color(0xFFEAF1F4), height: 1, thickness: 1),
                ],
                if (serviceRequest.audio?.isNotEmpty == true) ...[
                  16.height,
                  ASoundPlayer(
                    audio: serviceRequest.audio,
                  ),
                  16.height,
                  const Divider(color: Color(0xFFEAF1F4), height: 1, thickness: 1),
                ],
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      'View Comments',
                      style: AppTextStyles.bodyText.copyWith(color: const Color(0xFF4A8DB7)),
                    ),
                    4.width,
                    const Icon(
                      Icons.arrow_forward,
                      color: Color(0xFF4A8DB7),
                      size: 14,
                    )
                  ],
                ),
              ],
            ).paddingAll(16),
          ],
        ),
      );
    }

    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar:  DefaultAppBar(title: context.translation.serviceRequest),
        backgroundColor: const Color(0xfff8f9fb),
        body: SafeArea(
          child: FutureBuilder(
              future: _serviceRequestsProvider.getServiceRequestObjectById(requestId: serviceRequest.id),
              builder: (context, snap) {
                if (snap.connectionState == ConnectionState.waiting) {
                  return const ALoading();
                } else if (snap.hasData) {
                  serviceRequest = snap.data;
                  return Column(
                    children: [
                      Container(
                        color: AColors.primaryColor,
                        padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 4),
                        child: Row(
                          children: [
                            ABackButton(),
                            Expanded(
                              child: Center(
                                child: Text(
                                  context.translation.details,
                                  style: Theme.of(context).textTheme.headline6.copyWith(color: AColors.white, fontStyle: FontStyle.italic),
                                ),
                              ),
                            ),
                            _userProvider.user.type == UsersTypes.normal_user
                                ?
                                // AIconButton(
                                //   iconData: Icons.warning_amber_rounded,
                                //   color: AColors.white,
                                //   buttonSize: 42,
                                //   backgroundColor: AColors.deepOrange,
                                //   onPressed: (){
                                //     Navigator.of(context).push(
                                //         MaterialPageRoute(
                                //             builder: (_) => ReportIssuesPage(serviceRequest: serviceRequest,)
                                //         )
                                //     );
                                //   },
                                // )
                                const SizedBox(
                                    width: 48,
                                  )
                                : AIconButton(
                                    iconData: Icons.edit,
                                    color: AColors.white,
                                    buttonSize: 42,
                                    backgroundColor: AColors.green,
                                    onPressed: (serviceRequest.statusValue == 5 || serviceRequest.statusValue == 3)
                                        ? null
                                        : () async {
                                            Navigator.of(context).push(
                                              MaterialPageRoute(builder: (_) => CreateRequestPage(serviceRequest: serviceRequest)),
                                            );
                                            // showModalBottomSheet(
                                            //     context: context,
                                            //     builder: (context) {
                                            //       return ServiceRequestsUpdateDialog(
                                            //         request: serviceRequest,
                                            //       );
                                            //     });
                                            // DateTime picked = await showDatePicker(
                                            //     context: context,
                                            //     initialDate: DateTime.now(),
                                            //     firstDate: DateTime.now(),
                                            //     lastDate: DateTime.now().add(Duration(days: 182))
                                            // );
                                            // if(picked == null){return;}
                                            // showDialog<void>(
                                            //   context: context,
                                            //   barrierDismissible: false,
                                            //   builder: (BuildContext context) {
                                            //     return CupertinoAlertDialog(
                                            //       title: Text(context.translation.updatingDots),
                                            //       content: Center(child: CircularProgressIndicator()),
                                            //     );
                                            //   },
                                            // );
                                            // int status = await _serviceRequestsProvider.updateDate(
                                            //     user: _userProvider.user,
                                            //     host: _settingProvider.host,
                                            //     request: serviceRequest,
                                            //     newDate: picked.toString().split(" ").first
                                            // );
                                            // Navigator.of(context).pop();
                                            // Fluttertoast.showToast(
                                            //   msg: HttpStatusManger.getStatusMessage(status: status, subtitle: context.translation),
                                            // );
                                          },
                                  ),
                            SizedBox(
                              width: 16,
                            )
                          ],
                        ),
                      ),
                      serviceRequest.devicePhotos.isEmpty
                          ? const SizedBox.shrink()
                          : SizedBox(
                              height: 60 * AppStyle.getScaleFactor(context),
                              child: FilesList(
                                images: serviceRequest.devicePhotos,
                              ),
                            ).paddingOnly(top: 4, bottom: 4),
                      TabBar(labelColor: AColors.primaryColor, tabs: [
                        Tab(
                          text: context.translation.general,
                        ),
                        Tab(
                          text: context.translation.serviceRequestInformation,
                        ),
                      ]),
                      SizedBox(
                        height: 8,
                      ),
                      Expanded(
                        child: TabBarView(
                          children: [
                            Column(
                              children: [
                                ListView(
                                  padding: const EdgeInsets.all(16),
                                  children: [
                                    informationCard(),
                                    RequestInfoRow(
                                      title: context.translation.callId,
                                      info: serviceRequest.requestCode,
                                    ),
                                    RequestInfoRow(
                                      title: "Asset Number",
                                      info: serviceRequest.deviceNumber,
                                    ),
                                    RequestInfoRow(
                                      title: context.translation.assetName,
                                      info: serviceRequest.deviceEnName,
                                    ),
                                    RequestInfoRow(
                                      title: context.translation.deviceModel,
                                      info: serviceRequest.deviceModel,
                                    ),
                                    RequestInfoRow(
                                      title: context.translation.engineerName,
                                      info: serviceRequest.engineerName,
                                    ),
                                    RequestInfoRow(
                                      title: context.translation.engineerPhone,
                                      info: serviceRequest.engineerMobile,
                                    ),
                                    RequestInfoRow(
                                      title: context.translation.date,
                                      info: serviceRequest.date,
                                    ),
                                    serviceRequest.nextVisitDate == null
                                        ? SizedBox.shrink()
                                        : RequestInfoRow(
                                            title: context.translation.next,
                                            info: DateFormat('EE dd/MM/yyyy').format(serviceRequest.nextVisitDate),
                                          ),
                                    Row(
                                      children: [
                                        Expanded(
                                          child: Text(
                                            "${context.translation.status} :  ",
                                            style: Theme.of(context).textTheme.subtitle1,
                                            textScaleFactor: AppStyle.getScaleFactor(context),
                                          ),
                                        ),
                                        StatusLabel(label: serviceRequest.statusLabel, backgroundColor: AColors.getRequestStatusColor(serviceRequest.statusValue)),
                                      ],
                                    ),
                                    Divider(
                                      color: Theme.of(context).primaryColor,
                                    ),
                                    RequestInfoRow(
                                      title: context.translation.hospital,
                                      info: serviceRequest.hospitalName,
                                    ),
                                    RequestInfoRow(
                                      title: context.translation.unite,
                                      info: serviceRequest.departmentName,
                                    ),
                                    // RequestInfoRow(
                                    //   title: context.translation.deviceArName,
                                    //   content: serviceRequest.deviceArName,
                                    // ),
                                    // RequestInfoRow(
                                    //   title: context.translation.deviceName,
                                    //   content: serviceRequest.deviceEnName,
                                    // ),
                                    RequestInfoRow(
                                      title: context.translation.maintenanceIssue,
                                      content: serviceRequest.callComments,
                                    ),
                                    if (serviceRequest.audio?.isNotEmpty == true)
                                      ASoundPlayer(
                                        audio: serviceRequest.audio,
                                      ),
                                    //
                                    // Center(
                                    //   child: Padding(
                                    //     padding: EdgeInsets.all(32),
                                    //     child: AButton(
                                    //       text: context.translation.duplicateRequest,
                                    //       onPressed: () async {
                                    //         bool result = await showDialog(
                                    //             context: context,
                                    //             builder: (_) => AAlertDialog(
                                    //               title: context.translation.duplicateAlert,
                                    //               content: context.translation.duplicateAlertMessage,
                                    //             )
                                    //         );
                                    //         if(result == true){
                                    //           showDialog(
                                    //               context: context,
                                    //               builder: (context){
                                    //                 return Center(child: CircularProgressIndicator());
                                    //               }
                                    //           );
                                    //           int status = await _serviceRequestsProvider.createDuplicatedReport(
                                    //               host: _settingProvider.host,
                                    //               user: _userProvider.user,
                                    //               request: serviceRequest
                                    //           );
                                    //           Navigator.of(context).pop();
                                    //           ScaffoldMessenger.of(context).showSnackBar(
                                    //               SnackBar(
                                    //                 content: Text(
                                    //                   HttpStatusManger.getStatusMessage(status: status, subtitle: context.translation)
                                    //                 )
                                    //               )
                                    //           );
                                    //         }
                                    //       },
                                    //     ),
                                    //   ),
                                    // )
                                  ],
                                ).expanded,
                                AppFilledButton(label: context.translation.login, maxWidth: true, onPressed: () {}).paddingOnly(left: 16, right: 16, bottom: 24),
                              ],
                            ),
                            // workOrders.isEmpty ?
                            FutureBuilder(
                              future: _serviceRequestsProvider.searchWorkOrders(callId: serviceRequest.requestCode),
                              builder: (context, snap) {
                                workOrders = snap.data as List<SearchWorkOrder>;
                                if (snap.connectionState == ConnectionState.waiting) return Center(child: CircularProgressIndicator());
                                if (snap.connectionState == ConnectionState.done && (snap.data?.length ?? 0) != 0) {
                                  return SingleChildScrollView(
                                    child: Column(
                                      children: [
                                        ListView.separated(
                                          shrinkWrap: true,
                                          physics: const NeverScrollableScrollPhysics(),
                                          padding: EdgeInsets.all(21),
                                          itemCount: workOrders.length,
                                          separatorBuilder: (czt, index) => 21.height,
                                          itemBuilder: (context, index) {
                                            Color itemColor = index % 2 == 0 ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.onPrimary;
                                            Color onItemColor = index % 2 != 0 ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.onPrimary;

                                            return ElevatedButton(
                                              style: ElevatedButton.styleFrom(
                                                padding: EdgeInsets.symmetric(vertical: 8, horizontal: 8),
                                                primary: itemColor.withOpacity(.7),
                                                shape: RoundedRectangleBorder(
                                                  borderRadius: BorderRadius.circular(AppStyle.getBorderRadius(context)),
                                                ),
                                              ),
                                              //padding: EdgeInsets.symmetric(vertical: 8,horizontal: 8),
                                              onPressed: () {
                                                //  onPressed(request);
                                              },
                                              child: Column(
                                                children: [
                                                  RequestInfoRow(
                                                    title: context.translation.callId,
                                                    content: serviceRequest.requestCode,
                                                  ),
                                                  RequestInfoRow(
                                                    title: context.translation.orderWorkNumber,
                                                    info: workOrders[index].workOrderNo.toString(),
                                                  ),
                                                  RequestInfoRow(
                                                    title: context.translation.visitDate,
                                                    info: workOrders[index].visitDate,
                                                  ),
                                                  RequestInfoRow(title: context.translation.assignedEmployee, info: workOrders[index].assignedEmployee?.name ?? ""),
                                                  RequestInfoRow(
                                                    title: context.translation.assetSN,
                                                    info: workOrders[index].callRequest.asset.assetSerialNo,
                                                  ),
                                                  RequestInfoRow(
                                                    title: context.translation.assetName,
                                                    info: workOrders[index].callRequest.asset.modelDefinition.assetName,
                                                  ),
                                                  RequestInfoRow(
                                                    title: context.translation.assetNumber,
                                                    info: workOrders[index].callRequest.asset.assetNumber,
                                                  ),
                                                  RequestInfoRow(
                                                    title: context.translation.model,
                                                    info: workOrders[index].callRequest.asset.modelDefinition.modelName,
                                                  ),
                                                  RequestInfoRow(
                                                    title: context.translation.site,
                                                    info: workOrders[index].callRequest.asset.site.custName,
                                                  ),
                                                  RequestInfoRow(
                                                    title: "Call last Situation",
                                                    info: workOrders[index].currentSituation.name ?? '',
                                                  ),
                                                  _userProvider.user.type == UsersTypes.engineer && workOrders[index].workOrderNo != null
                                                      ? Padding(
                                                          padding: EdgeInsets.all(32),
                                                          child: AButton(
                                                            text: context.translation.editServiceReport,
                                                            onPressed: serviceRequest.statusValue == 5 || serviceRequest.statusValue == 3
                                                                ? null
                                                                : () {
                                                                    Navigator.of(context).push(
                                                                      MaterialPageRoute(
                                                                          builder: (_) => FutureServiceReport(
                                                                                request: serviceRequest,
                                                                                workOrder: workOrders[index],
                                                                              )),
                                                                    );
                                                                  },
                                                          ),
                                                        )
                                                      : SizedBox.shrink(),
                                                ],
                                              ),
                                            );
                                          },
                                        ),
                                        if (_userProvider.user.type == UsersTypes.engineer)
                                          Center(
                                            child: Padding(
                                              padding: const EdgeInsets.all(32),
                                              child: AButton(
                                                text: "Create Work Order",
                                                onPressed: serviceRequest.statusValue == 5 || serviceRequest.statusValue == 3
                                                    ? null
                                                    : () {
                                                        Navigator.of(context).push(MaterialPageRoute(builder: (_) => CreateServiceReport(request: serviceRequest)));
                                                      },
                                              ),
                                            ),
                                          ),
                                      ],
                                    ),
                                  );
                                } else {
                                  return Column(
                                    children: [
                                      Expanded(
                                        child: Center(
                                          child: ASubTitle(context.translation.dataNotFound),
                                        ),
                                      ),
                                      if (_userProvider.user.type == UsersTypes.engineer)
                                        Center(
                                          child: Padding(
                                            padding: const EdgeInsets.all(32),
                                            child: AButton(
                                              text: "Create Work Order",
                                              onPressed: serviceRequest.statusValue == 5 || serviceRequest.statusValue == 3
                                                  ? null
                                                  : () {
                                                      Navigator.of(context).push(MaterialPageRoute(builder: (_) => CreateServiceReport(request: serviceRequest)));
                                                    },
                                            ),
                                          ),
                                        ),
                                    ],
                                  );
                                }
                              },
                            ),
                          ],
                        ),
                      ),
                    ],
                  );
                }
                return const SizedBox();
              }),
        ),
      ),
    );
  }
}
