import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/models/service_request/search_work_order.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/views/widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/buttons/app_button.dart';
import 'package:test_sa/views/widgets/status/report/service_report_assistant_employee_menu.dart';
import 'package:test_sa/views/widgets/status/report/service_report_maintenance_situation.dart';
import 'package:test_sa/views/widgets/status/report/service_report_repair_location.dart';
import 'package:test_sa/views/widgets/status/service_request/supplier_engineers_menu.dart';

import '../../../controllers/localization/localization.dart';
import '../../../controllers/providers/api/status_drop_down/report/service_report_maintenance_situation_provider.dart';
import '../../widgets/timer/app_timer.dart';
import '../../widgets/titles/app_sub_title.dart';
import 'auto_generated_vendor_name.dart';

class WorkOrderDetailsBottomSheet extends StatefulWidget {
  final SearchWorkOrder subWorkOrder;
  const WorkOrderDetailsBottomSheet({this.subWorkOrder, Key key}) : super(key: key);

  @override
  State<WorkOrderDetailsBottomSheet> createState() => _WorkOrderDetailsBottomSheetState();
}

class _WorkOrderDetailsBottomSheetState extends State<WorkOrderDetailsBottomSheet> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final SearchWorkOrder _workOrder = SearchWorkOrder();
  bool _showVendorFields = false;
  SuppEngineerWorkOrders engineer;

  @override
  void initState() {
    super.initState();

    _workOrder.copyFrom(widget.subWorkOrder);
    if (_workOrder.calllastSituation?.name?.toLowerCase()?.contains("under repair-vendor") ?? false) {
      _showVendorFields = true;
      _workOrder.supplier ??= SupplierModel(id: _workOrder?.supplier?.id);
    }
    if (context.mounted) {
      Provider.of<ServiceReportMaintenanceSituationProvider>(context, listen: false).reset();
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final Subtitle subtitle = AppLocalization.of(context).subtitle;
    return Padding(
      padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: ClipRRect(
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(15),
          topRight: Radius.circular(15),
        ),
        clipBehavior: Clip.antiAliasWithSaveLayer,
        child: Container(
          color: Colors.white,
          height: size.height * 0.9,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const ASubTitle("WO Details"),
                const SizedBox(height: 8),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const SizedBox(height: 8),
                          ATextFormField(enable: false, hintText: "Assigned Employee: ${_workOrder.assignedEmployee?.name}"),
                          const SizedBox(height: 8),
                          const ASubTitle("Assistant Employee"),
                          const SizedBox(height: 4),
                          ServiceReportAssistantEmployeeMenu(
                            initialValue: (_workOrder.assistantEmployees?.isNotEmpty ?? false) ? _workOrder.assistantEmployees?.first : null,
                            onSelect: (assistantsEmployee) {
                              _workOrder.assistantEmployees = [assistantsEmployee];
                            },
                          ),
                          const SizedBox(height: 8),
                          ASubTitle(subtitle.workingHours),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Expanded(
                                child: AppTimer(
                                  timer: _workOrder.timer,
                                  onChange: (timer) async {
                                    _workOrder.timer = timer;
                                    _workOrder.workingHours = num.tryParse((((timer?.durationInSecond ?? 0) / 60) / 60)?.toStringAsFixed(2) ?? "0");
                                    return true;
                                  },
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 16),
                          ATextFormField(
                            labelText: "Travel Hours",
                            initialValue: _workOrder.travelingHours?.toString(),
                            textInputType: TextInputType.number,
                            onSaved: (value) {
                              _workOrder.travelingHours = num.tryParse(value);
                            },
                          ),
                          const SizedBox(height: 8),
                          ATextFormField(
                            labelText: "Travel Expense",
                            initialValue: _workOrder.travelingExpenses?.toString(),
                            textInputType: TextInputType.number,
                            onSaved: (value) {
                              _workOrder.travelingExpenses = num.tryParse(value);
                            },
                          ),
                          const SizedBox(height: 8),
                          ASubTitle(subtitle.callLastSituation),
                          const SizedBox(height: 4),
                          ServiceReportMaintenanceSituation(
                            initialValue: _workOrder.calllastSituation,
                            onSelect: (status) {
                              if (status.name.toLowerCase().contains("under repair-vendor")) {
                                _showVendorFields = true;
                                _workOrder.supplier ??= SupplierModel(id: _workOrder?.supplier?.id);
                                engineer = null;
                              } else {
                                _showVendorFields = false;
                              }
                              setState(() {});
                              if (status?.value == 12 || _workOrder.calllastSituation?.value == 12) {
                                _workOrder.calllastSituation = status;
                                setState(() {});
                              } else {
                                _workOrder.calllastSituation = status;
                              }
                            },
                            woId: widget.subWorkOrder?.parentWOId?.toString(),
                          ),
                          if (_showVendorFields) const SizedBox(height: 8),
                          if (_showVendorFields)
                            AutoGeneratedVendorName(
                              initialValue: _workOrder.supplier?.suppliername,
                              onSearch: (supplier) {
                                _workOrder.supplier.id = supplier.id;
                                _workOrder.supplier.suppliername = supplier.suppliername;
                                _workOrder.supplier.suppPersons = supplier.suppPersons;
                                setState(() {});
                              },
                            ),
                          if (_showVendorFields) const SizedBox(height: 8),
                          if (_showVendorFields)
                            SupplierEngineersMenu(
                              initialValue: engineer,
                              engineers: _workOrder.supplier.suppPersons,
                              onSelect: (engineer) {
                                if (engineer != null) {
                                  this.engineer = engineer;
                                }
                              },
                            ),
                          const SizedBox(height: 8),
                          const ASubTitle("Repair Location"),
                          const SizedBox(height: 4),
                          ServiceReportRepairLocation(
                            initialValue: _workOrder.repairLocation,
                            onSelect: (status) {
                              _workOrder.repairLocation = status;
                            },
                          ),
                          const SizedBox(height: 8),
                          ATextFormField(
                            labelText: "Technical Comments",
                            initialValue: _workOrder.comment,
                            textInputType: TextInputType.multiline,
                            onSaved: (value) {
                              _workOrder.comment = value;
                            },
                          ),
                          const SizedBox(height: 24),
                        ],
                      ),
                    ),
                  ),
                ),
                AButton(
                  text: subtitle.submit,
                  onPressed: () async {
                    if (_workOrder?.workingHours == null) {
                      await Fluttertoast.showToast(msg: "Working Hours Timer Isn't Started");
                      return;
                    }
                    if (_showVendorFields && (_workOrder.supplier.suppliername == null || _workOrder.supplier.suppliername.isEmpty)) {
                      await Fluttertoast.showToast(msg: "Vendor Name is Required");
                      return;
                    }
                    if (_showVendorFields && _workOrder.suppEngineerWorkOrders == null) {
                      await Fluttertoast.showToast(msg: "Vendor Engineer is Required");
                      return;
                    }
                    _workOrder.suppEngineerWorkOrders ?? [];
                    _workOrder.suppEngineerWorkOrders.add(engineer..id = 0);
                    _formKey.currentState.save();
                    widget.subWorkOrder.copyFrom(_workOrder);
                    Navigator.pop(context);
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
