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

import 'package:easy_localization/easy_localization.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/mowadhafhi/mowadhafhi_api_client.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_department_sections.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_project_departments.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_projects.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_section_topics.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_ticket_types.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/mowadhafhi_attachement_request.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/button/simple_button.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';

class MowadhafhiHRRequest extends StatefulWidget {
  const MowadhafhiHRRequest({Key? key}) : super(key: key);

  @override
  _MowadhafhiHRRequestState createState() => _MowadhafhiHRRequestState();
}

class _MowadhafhiHRRequestState extends State<MowadhafhiHRRequest> {
  List<GetTicketTypes> getTicketTypesList = [];
  List<GetMowadhafhiProjects> getMowadhafhiProjectsList = [];
  List<GetProjectDepartments> getProjectDepartmentsList = [];
  List<GetDepartmentSections> getDepartmentSectionsList = [];
  List<GetSectionTopics> getSectionTopicsList = [];

  GetProjectDepartments? selectedDepartment;
  GetDepartmentSections? selectedSection;
  GetSectionTopics? selectedTopic;
  List<File> attachmentFiles = [];

  GetTicketTypes? selectedServiceType;

  // String selectedServiceType = "";
  String description = "";
  int? projectID;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.createRequest.tr(),
      ),
      body: getTicketTypesList.isNotEmpty
          ? Column(
              children: [
                ListView(
                  padding: const EdgeInsets.all(21),
                  children: [
                    PopupMenuButton(
                        child: DynamicTextFieldWidget(
                          LocaleKeys.serviceType.tr(),
                          selectedServiceType?.typeName ?? LocaleKeys.selectTypeT.tr(),
                          isEnable: false,
                          isPopup: true,
                          isInputTypeNum: true,
                          isReadOnly: false,
                        ),
                        itemBuilder: (_) => <PopupMenuItem<int>>[
                              for (int i = 0; i < getTicketTypesList.length; i++) PopupMenuItem<int>(child: Text(getTicketTypesList[i].typeName!), value: i),
                            ],
                        onSelected: (int popupIndex) {
                          selectedServiceType = getTicketTypesList[popupIndex]; //.ticketTypeId!.toString();
                          setState(() {});
                        }),
                    12.height,
                    PopupMenuButton(
                        child: DynamicTextFieldWidget(
                          LocaleKeys.departmentName.tr(),
                          selectedDepartment?.departmentName ?? LocaleKeys.selectDepartment.tr(),
                          isEnable: false,
                          isPopup: true,
                          isInputTypeNum: true,
                          isReadOnly: false,
                        ),
                        itemBuilder: (_) => <PopupMenuItem<int>>[
                              for (int i = 0; i < getProjectDepartmentsList!.length; i++) PopupMenuItem<int>(child: Text(getProjectDepartmentsList![i].departmentName!), value: i),
                            ],
                        onSelected: (int popupIndex) {
                          selectedDepartment = getProjectDepartmentsList![popupIndex];
                          getDepartmentSections(selectedDepartment?.projectDepartmentId);
                          setState(() {});
                        }),
                    12.height,
                    PopupMenuButton(
                        child: DynamicTextFieldWidget(
                          LocaleKeys.relatedSection.tr(),
                          selectedSection?.sectionName ?? LocaleKeys.selectSection.tr(),
                          isEnable: false,
                          isPopup: true,
                          isInputTypeNum: true,
                          isReadOnly: false,
                        ),
                        itemBuilder: (_) => <PopupMenuItem<int>>[
                              for (int i = 0; i < getDepartmentSectionsList!.length; i++) PopupMenuItem<int>(child: Text(getDepartmentSectionsList![i].sectionName!), value: i),
                            ],
                        onSelected: (int popupIndex) {
                          selectedSection = getDepartmentSectionsList![popupIndex];
                          getSectionTopics(selectedSection?.departmentSectionId);
                          setState(() {});
                        }),
                    12.height,
                    PopupMenuButton(
                        child: DynamicTextFieldWidget(
                          LocaleKeys.relatedTopic.tr(),
                          selectedTopic?.topicName ?? LocaleKeys.selectTopic.tr(),
                          isEnable: false,
                          isPopup: true,
                          isInputTypeNum: true,
                          isReadOnly: false,
                        ),
                        itemBuilder: (_) => <PopupMenuItem<int>>[
                              for (int i = 0; i < getSectionTopicsList.length; i++) PopupMenuItem<int>(child: Text(getSectionTopicsList[i].topicName!), value: i),
                            ],
                        onSelected: (int popupIndex) {
                          selectedTopic = getSectionTopicsList[popupIndex];
                          // getDepartmentSections(selectedSection?.departmentSectionId);
                          setState(() {});
                        }),
                    12.height,
                    attachmentView("Attachments").objectContainerView(title: LocaleKeys.supportingDocument.tr()),
                    12.height,
                    DynamicTextFieldWidget(
                      LocaleKeys.description.tr(),
                      LocaleKeys.writeAMessage.tr(),
                      isEnable: true,
                      isPopup: false,
                      lines: 4,
                      isInputTypeNum: false,
                      isReadOnly: false,
                      onChange: (String value) {
                        debugPrint(value);
                        description = value;
                      },
                    ),
                  ],
                ).expanded,
                DefaultButton(
                  LocaleKeys.submit.tr(),
                  !checkValidation()
                      ? null
                      : () {
                          submitHRRequest();
                        },
                  color: const Color(0xFFD02127),
                ).insideContainer
              ],
            )
          : Container(),
    );
  }

  bool checkValidation() {
    if (selectedServiceType == null || selectedDepartment == null || selectedSection == null || selectedTopic == null) {
      return false;
    } else {
      return true;
    }
  }

  Widget attachmentView(String title) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            title.toText16().expanded,
            6.width,
            SimpleButton(LocaleKeys.add.tr(), () async {
              FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);
              if (result != null) {
                attachmentFiles = attachmentFiles + result.paths.map((path) => File(path!)).toList();
                attachmentFiles = attachmentFiles.toSet().toList();
                setState(() {});
              }
            }, fontSize: 14),
          ],
        ),
        if (attachmentFiles.isNotEmpty) 12.height,
        if (attachmentFiles.isNotEmpty)
          ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (cxt, index) {
                String fileName = attachmentFiles[index].path.split('/').last;

                return Row(
                  children: [
                    fileName.toText13().expanded,
                    6.width,
                    IconButton(
                      padding: EdgeInsets.zero,
                      iconSize: 20,
                      icon: const Icon(Icons.cancel_rounded),
                      color: MyColors.redColor,
                      constraints: const BoxConstraints(),
                      onPressed: () async {
                        attachmentFiles.removeAt(index);
                        setState(() {});
                      },
                    )
                  ],
                );
              },
              separatorBuilder: (cxt, index) => 6.height,
              itemCount: attachmentFiles.length),
      ],
    );
  }

  void getTicketTypes() async {
    try {
      Utils.showLoading(context);
      getTicketTypesList = await MowadhafhiApiClient().getTicketTypes();
      Utils.hideLoading(context);
      getMowadhafhiProjects();
      // setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getMowadhafhiProjects() async {
    try {
      Utils.showLoading(context);
      getMowadhafhiProjectsList = await MowadhafhiApiClient().getProjects();
      Utils.hideLoading(context);
      getProjectDepartments(getMowadhafhiProjectsList[0].projectId!);
      projectID = getMowadhafhiProjectsList[0].projectId;
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getProjectDepartments(int projectID) async {
    try {
      Utils.showLoading(context);
      getProjectDepartmentsList = await MowadhafhiApiClient().getProjectDepartments(projectID);
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getDepartmentSections(int? projectDepartmentID) async {
    try {
      Utils.showLoading(context);
      getDepartmentSectionsList = await MowadhafhiApiClient().getDepartmentSections(projectDepartmentID);
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getSectionTopics(int? departmentSectionID) async {
    try {
      Utils.showLoading(context);
      getSectionTopicsList = await MowadhafhiApiClient().getSectionTopics(departmentSectionID);
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void submitHRRequest() async {
    try {
      Utils.showLoading(context);
      List<Map<String, dynamic>> list = [];
      if (attachmentFiles.isNotEmpty) {
        for (int i = 0; i < attachmentFiles.length; i++) {
          String type = attachmentFiles[i].path.split('.').last;
          String name = attachmentFiles[i].path.split('/').last;
          List<int> fileContent = await attachmentFiles[i].readAsBytes();
          String encodedFile = base64Encode(fileContent);
          list.add(MowadhafhiRequestAttachment(
            contentType: "image/" + type,
            fileName: name,
            base64Data: encodedFile,
          ).toJson());
        }
      }
      int? messageStatus = await MowadhafhiApiClient().submitRequest(selectedDepartment?.projectDepartmentId, description, projectID, selectedSection?.departmentSectionId.toString(),
          selectedTopic?.sectionTopicId.toString(), selectedServiceType!.ticketTypeId, list);
      Utils.showToast(LocaleKeys.requestCreatedSuccessfully.tr());
      Utils.hideLoading(context);
      Navigator.pop(context);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
