import 'package:car_provider_app/api/client/branch_api_client.dart';
import 'package:car_provider_app/classes/utils.dart';
import 'package:car_provider_app/generated/locale_keys.g.dart';
import 'package:car_provider_app/models/m_response.dart';
import 'package:car_provider_app/models/profile/branch.dart';
import 'package:car_provider_app/models/profile/categroy.dart';
import 'package:car_provider_app/models/profile/services.dart';
import 'package:car_provider_app/models/user/country.dart';
import 'package:car_provider_app/utils/navigator.dart';
import 'package:car_provider_app/widgets/app_bar.dart';
import 'package:car_provider_app/widgets/dropdown/dropdow_field.dart';
import 'package:car_provider_app/widgets/button/show_fill_button.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';
import 'package:car_provider_app/extensions/int_extensions.dart';
import 'package:car_provider_app/extensions/string_extensions.dart';

import '../../classes/colors.dart';
import '../../models/profile/branch2.dart';
import '../../utils/utils.dart';

class CreateServicesPage extends StatefulWidget {
  ServiceProviderBranch? serviceProviderBranch;

  CreateServicesPage(this.serviceProviderBranch);

  @override
  State<CreateServicesPage> createState() => _CreateServicesPageState();
}

class _CreateServicesPageState extends State<CreateServicesPage> {
  String? branchName;
  int categoryId = -1, branchId = -1;
  DropValue? branchValue;

  List<DropValue> countryDropList = [];
  List<DropValue> categoryDropList = [];

  Branch? branch;
  Category? category;
  Services? services;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.serviceProviderBranch != null) {
      branchId = widget.serviceProviderBranch!.id ?? -1;
      branchValue = new DropValue(branchId, widget.serviceProviderBranch!.branchName ?? "", "");
      print("llll1 " + branchId.toString() + "  " + widget.serviceProviderBranch!.branchName.toString());
      if (branchId != 1) fetchBrancheCategory();
    }
    fetchBranches();
  }

  fetchBranches() async {
    branch = await BranchApiClent().fetchAllBranches();
    setState(() {
      branch!.data?.forEach((element) {
        countryDropList.add(new DropValue(element.id ?? 0, ((element.branchName!.isEmpty ? "N/A" : element.branchName) ?? "N/A"), ""));
      });
    });
  }

  fetchBrancheCategory() async {
    category = await BranchApiClent().fetchBranchCategory();
    setState(() {
      category!.data?.forEach((element) {
        categoryDropList.add(new DropValue(
            element.id ?? 0,
            ((element.categoryName!.isEmpty
                    ? "N/A"
                    : EasyLocalization.of(context)?.currentLocale?.countryCode == "SA"
                        ? element.categoryNameN
                        : element.categoryName) ??
                "N/A"),
            ""));
      });
    });
  }

  fetchServices() async {
    services = await BranchApiClent().fetchServices(categoryId.toString());
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(context, title: LocaleKeys.defineServices.tr()),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    children: [
                      branch != null
                          ? (branchValue != null && branchId != -1)
                              ? Container(
                                  width: double.infinity,
                                  child: Text(
                                    branchValue!.value ?? "",
                                    style: TextStyle(
                                      fontSize: 12,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  decoration: containerColorRadiusBorderWidth(
                                    MyColors.textFieldColor,
                                    8,
                                    MyColors.textFieldColor,
                                    0,
                                  ),
                                  margin: EdgeInsets.all(0),
                                  padding: EdgeInsets.only(left: 8, right: 8, bottom: 12, top: 12),
                                )
                              : DropdownField(
                                  (DropValue value) {
                                    setState(() {
                                      // countryCode = value.subValue;
                                      // countryId = value.id;
                                      // fetchCites();
                                      branchId = value.id;
                                      fetchBrancheCategory();
                                    });
                                  },
                                  list: countryDropList,
                                  hint: LocaleKeys.selectBranch.tr(),
                                  dropdownValue: branchValue,
                                )
                          : CircularProgressIndicator(),
                      12.height,
                      (category != null)
                          ? DropdownField((DropValue value) {
                              setState(() {
                                // countryCode = value.subValue;
                                // countryId = value.id;
                                // fetchCites();
                                categoryId = value.id;
                                fetchServices();
                              });
                            }, list: categoryDropList, hint: LocaleKeys.selectServiceCategory.tr())
                          : branchId == -1
                              ? Container()
                              : CircularProgressIndicator(),
                      12.height,
                      if ((categoryId != -1))
                        services == null
                            ? CircularProgressIndicator()
                            : ListView.separated(
                                itemBuilder: (context, index) {
                                  return Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Row(
                                      children: [
                                        Checkbox(
                                          value: services!.data![index].isSelected,
                                          onChanged: (v) {
                                            setState(() {
                                              services!.data![index].isSelected = v;
                                            });
                                          },
                                        ),
                                        12.width,
                                        ((EasyLocalization.of(context)?.currentLocale?.countryCode == "SA" ? services!.data![index].descriptionN : services!.data![index].description) ?? "").toText12()
                                      ],
                                    ),
                                  );
                                },
                                separatorBuilder: (context, index) {
                                  return 1.height;
                                },
                                itemCount: services!.data!.length,
                                physics: NeverScrollableScrollPhysics(),
                                shrinkWrap: true,
                              )
                    ],
                  ),
                ),
              ),
            ),
            if (checkServicesSelection())
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: ShowFillButton(
                  title: LocaleKeys.save.tr(),
                  maxWidth: double.infinity,
                  onPressed: () {
                    createService();
                  },
                ),
              ),
          ],
        ),
      ),
    );
  }

  bool checkServicesSelection() {
    bool isServiceSelected = false;
    try {
      services!.data!.forEach((element) {
        if (element.isSelected ?? false) isServiceSelected = true;
      });
    } catch (e) {
      isServiceSelected = false;
    }

    return isServiceSelected;
  }

  createService() async {
    List<Map<String, dynamic>> map = [];
    if (widget.serviceProviderBranch != null && branchId != -1) {
      for (int i = 0; i < services!.data!.length; i++) {
        if (services!.data![i].isSelected ?? false) {
          var postParams = {
            // "id": services!.data![i].id,
            "providerBranchID": branchId,
            "serviceID": services!.data![i].id,
            "isAllowAppointment": true,
            "isActive": true
          };
          map.add(postParams);
        }
      }
      Utils.showLoading(context);
      MResponse mResponse = await BranchApiClent().createService(map);
      Utils.hideLoading(context);

      if (widget.serviceProviderBranch != null) {
        Utils.showToast(mResponse.message ?? "");
        if (mResponse.messageStatus != 2) {
          pop(context);
          pop(context);
        }
      }
    } else {
      for (int i = 0; i < services!.data!.length; i++) {
        if (services!.data![i].isSelected ?? false) {
          var postParams = {
            // "id": services!.data![i].id,
            "providerBranchID": branchId,
            "serviceID": services!.data![i].id,
            "isAllowAppointment": true,
            "isActive": true
          };
          map.add(postParams);
        }
      }
      Utils.showLoading(context);
      MResponse mResponse = await BranchApiClent().createService(map);
      Utils.hideLoading(context);
      Utils.showToast(mResponse.message ?? "");
    }
  }
}
