import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.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/models/ppm/ppm.dart';
import 'package:test_sa/models/ppm/ppm_attachment.dart';
import 'package:test_sa/models/service_request/supplier_details.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/providers/ppm_asset_availability_provider.dart';
import 'package:test_sa/providers/ppm_electrical_safety_provider.dart';
import 'package:test_sa/providers/ppm_service_provider.dart';
import 'package:test_sa/providers/ppm_task_status_provider.dart';
import 'package:test_sa/providers/work_order/vendor_provider.dart';

import '../../../models/lookup.dart';
import '../../../new_views/common_widgets/app_text_form_field.dart';
import '../../../new_views/common_widgets/single_item_drop_down_menu.dart';
import '../../../providers/ppm_device_status_provider.dart';
import '../../../providers/ppm_visit_status_provider.dart';
import '../date_and_time/date_picker.dart';
import '../e_signature/e_signature.dart';
import '../images/multi_image_picker.dart';
import '../timer/app_timer.dart';

class PentryTBSForm extends StatefulWidget {
  final Ppm model;

  const PentryTBSForm({Key? key, required this.model}) : super(key: key);

  @override
  State<PentryTBSForm> createState() => _PentryTBSFormState();
}

class _PentryTBSFormState extends State<PentryTBSForm> {
  SupplierDetails? initialSupplier;
  SuppPersons? _suppPerson;

  @override
  Widget build(BuildContext context) {
    widget.model.files ??= [];
    widget.model.files = (widget.model.files ?? []).where((element) => element.attachmentName?.isNotEmpty ?? false).toList();

    double totalWorkingHours = widget.model.visitTimers?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endDateTime!).difference(DateTime.parse(item.startDateTime!)).inSeconds) ?? 0;

    totalWorkingHours = totalWorkingHours;

    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          8.height,
          SingleItemDropDownMenu<Lookup, PPMVisitStatusProvider>(
            context: context,
            initialValue: widget.model.visitStatusId == null ? null : Lookup(name: widget.model.visitStatusName ?? "", id: widget.model.visitStatusId?.toInt()),
            title: context.translation.ppmVisit,
            onSelect: (value) {
              if (value?.value == 4) {
                "Status cannot be change to ${value?.name}.".addTranslation.showToast;
                setState(() {});
                return;
              }

              if (value != null) {
                widget.model.visitStatusName = value.name;
                widget.model.visitStatusId = value.id;
              }
            },
          ),
          8.height,
          if (totalWorkingHours > 0.0) ...[
            Container(
              height: 56.toScreenHeight,
              padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth),
              alignment: Alignment.centerLeft,
              decoration: BoxDecoration(
                color: context.isDark ? AppColor.neutral40 : AppColor.background(context),
                borderRadius: BorderRadius.circular(10),
                boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "Total Working Time",
                    style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500),
                  ),
                  Text(
                    " ${formatDuration(totalWorkingHours.round())}",
                    style: Theme.of(context).textTheme.bodyMedium,
                  ),
                ],
              ),
            ),
            8.height,
          ],
          AppTimer(
            label: context.translation.timer,
            timer: widget.model.tbsTimer,
            enabled: widget.model.tbsTimer?.endAt == null,
            timerProgress: (isRunning) {
              print("timerProgress:$isRunning");
            },
            onChange: (timer) async {
              widget.model.tbsTimer = timer;
              return true;
            },
          ),
          8.height,
          SingleItemDropDownMenu<Lookup, PPMDeviceStatusProvider>(
            context: context,
            initialValue: widget.model.deviceStatusId == null ? null : Lookup(name: widget.model.deviceStatusName ?? "", id: widget.model.deviceStatusId?.toInt()),
            title: context.translation.deviceStatus,
            onSelect: (value) {
              if (value != null) {
                widget.model.deviceStatusId = value.id;
                widget.model.deviceStatusName = value.name;
              }
            },
          ),
          8.height,
          SingleItemDropDownMenu<Lookup, PpmTaskStatusProvider>(
            context: context,
            initialValue: widget.model.taskStatusId == null ? null : Lookup(name: widget.model.taskStatusName ?? "", id: widget.model.taskStatusId?.toInt()),
            title: context.translation.taskStatus,
            onSelect: (value) {
              if (value != null) {
                widget.model.taskStatusId = value.id;
                widget.model.taskStatusName = value.name;
              }
            },
          ),
          8.height,
          SingleItemDropDownMenu<Lookup, PpmAssetAvailabilityProvider>(
            context: context,
            initialValue: widget.model.assetAvailabilityId == null ? null : Lookup(name: widget.model.assetAvailabilityName ?? "", id: widget.model.assetAvailabilityId?.toInt()),
            title: "Asset Availability",
            onSelect: (value) {
              if (value != null) {
                widget.model.assetAvailabilityId = value.id;
                widget.model.assetAvailabilityName = value.name;
              }
            },
          ),
          8.height,
          SingleItemDropDownMenu<Lookup, PpmElectricalSafetyProvider>(
            context: context,
            initialValue: widget.model.safetyId == null ? null : Lookup(name: widget.model.safetyName ?? "", id: widget.model.safetyId?.toInt()),
            title: "Electrical Safety",
            onSelect: (value) {
              if (value != null) {
                widget.model.safetyId = value.id;
                widget.model.safetyName = value.name;
              }
            },
          ),
          8.height,
          SingleItemDropDownMenu<Lookup, PpmServiceProvider>(
            context: context,
            initialValue: widget.model.typeOfServiceId == null ? null : Lookup(name: widget.model.typeOfServiceName ?? "", id: widget.model.typeOfServiceId?.toInt()),
            title: context.translation.serviceType,
            onSelect: (value) {
              if (value != null) {
                widget.model.typeOfServiceId = value.id;
                widget.model.typeOfServiceName = value.name;

                widget.model.supplierId = null;
                widget.model.supplierName = null;
                initialSupplier = null;
                _suppPerson = null;
                widget.model.suppPersonId = null;
                widget.model.suppPerson = null;

                setState(() {});
              }
            },
          ),
          8.height,
          if (widget.model.typeOfServiceId == 66) ...[
            SingleItemDropDownMenu<SupplierDetails, VendorProvider>(
              context: context,
              title: context.translation.supplier,
              initialValue: initialSupplier,
              showAsBottomSheet: true,
              onSelect: (supplier) {
                if (supplier != null) {
                  widget.model.supplierId = supplier.id;
                  widget.model.supplierName = supplier.name;
                  initialSupplier = supplier;
                  _suppPerson = null;
                  widget.model.suppPersonId = null;
                  widget.model.suppPerson = null;
                  setState(() {});
                }
              },
            ),
            8.height,
            SingleItemDropDownMenu<SuppPersons, NullableLoadingProvider>(
              context: context,
              title: context.translation.supplierEngineer,
              enabled: initialSupplier?.suppPersons?.isNotEmpty ?? false,
              initialValue: _suppPerson,
              staticData: initialSupplier?.suppPersons,
              showAsBottomSheet: true,
              onSelect: (suppPerson) {
                if (suppPerson != null) {
                  _suppPerson = suppPerson;
                  widget.model.suppPersonId = suppPerson.id;
                  widget.model.suppPerson = suppPerson.name;
                  setState(() {});
                }
              },
            ),
            8.height,
            AppTextFormField(
              labelText: "Telephone",
              initialValue: (widget.model.telephone ?? "").toString(),
              textAlign: TextAlign.center,
              style: Theme.of(context).textTheme.titleMedium,
              textInputType: TextInputType.number,
              onChange: (value) {
                widget.model.telephone = value;
              },
            ),
            8.height,
            AppTimer(
              label: "External Supplier Timer",
              timer: widget.model.externalEngineerTimer,
              enabled: widget.model.externalEngineerTimer?.endAt == null,
              timerProgress: (isRunning) {
                print("timerProgress:$isRunning");
              },
              onChange: (timer) async {
                widget.model.externalEngineerTimer = timer;
                return true;
              },
            ),
            8.height,
          ],
          ADatePicker(
            label: context.translation.actualVisitDate,
            date: DateTime.tryParse(widget.model.actualDate ?? ""),
            from: DateTime.now().subtract(const Duration(days: 30)),
            onDatePicker: (date) {
              if (date.isBefore(DateTime.parse(widget.model.expectedDate!))) {
                "Actual visit date must be greater then expected date".showToast;
                return;
              }

              widget.model.actualDate = date.toIso8601String();
              setState(() {});
            },
          ),
          8.height,
          ADatePicker(
            label: context.translation.expectedVisitDate,
            date: DateTime.tryParse(widget.model.nextDate ?? ""),
            from: DateTime.now().subtract(const Duration(days: 30)),
            enable: false,
            onDatePicker: (date) {
              widget.model.nextDate = date.toIso8601String();
              setState(() {});
            },
          ),
          8.height,
          AppTextFormField(
            labelText: context.translation.travelingHours,
            initialValue: (widget.model.travelingHours ?? "").toString(),
            textAlign: TextAlign.center,
            style: Theme.of(context).textTheme.titleMedium,
            textInputType: TextInputType.number,
            onChange: (value) {
              widget.model.travelingHours = value;
            },
          ),
          8.height,
          MultiFilesPicker(
            label: context.translation.attachImage,
            files: widget.model.files!.map((e) => File(e.attachmentName!)).toList(),
            onChange: (files) {
              widget.model.files = files.map((e) => PpmAttachments(attachmentName: e.path)).toList();
            },
          ),
          8.height,
          AppTextFormField(
            labelText: context.translation.comments,
            initialValue: (widget.model.comments ?? "").toString(),
            textAlign: TextAlign.center,
            style: Theme.of(context).textTheme.titleMedium,
            onChange: (value) {
              widget.model.comments = value;
            },
          ),
          8.height,
          ESignature(
            title: context.translation.nurseSignature,
            oldSignature: widget.model.nurseSignature,
            newSignature: widget.model.localNurseSignature,
            onChange: (signature) {
              widget.model.localNurseSignature = signature;
              widget.model.nurseSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
            },
          ),
          8.height,
          ESignature(
            title: context.translation.engSign,
            oldSignature: widget.model.engSignature,
            newSignature: widget.model.localEngineerSignature,
            onChange: (signature) {
              widget.model.localEngineerSignature = signature;
              widget.model.engSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
            },
          ),
          8.height,
        ],
      ),
    );
  }

  String formatDuration1(int seconds) {
    int hours = seconds ~/ 3600;
    int minutes = (seconds % 3600) ~/ 60;

    String formattedDuration = '';
    if (hours > 0) {
      formattedDuration += '$hours hour${hours > 1 ? 's' : ''} ';
    }
    if (minutes > 0) {
      formattedDuration += '$minutes minute${minutes > 1 ? 's' : ''} ';
    }
    if (formattedDuration.isEmpty) {
      formattedDuration = 'Less than a minute';
    }

    return formattedDuration.trim();
  }

  String formatDuration(int seconds) {
    int hours = seconds ~/ 3600;
    int minutes = (seconds % 3600) ~/ 60;
    int remainingSeconds = seconds % 60;

    String formattedDuration = '';
    if (hours > 0) {
      formattedDuration += '$hours hour${hours > 1 ? 's' : ''} ';
    }
    if (minutes > 0) {
      formattedDuration += '$minutes minute${minutes > 1 ? 's' : ''} ';
    }
    if (remainingSeconds > 0) {
      formattedDuration += '$remainingSeconds second${remainingSeconds > 1 ? 's' : ''} ';
    }
    if (formattedDuration.isEmpty) {
      formattedDuration = 'Less than a second';
    }

    return formattedDuration.trim();
  }
}
