import 'package:car_provider_app/api/client/branch_api_client.dart';
import 'package:car_provider_app/classes/app_state.dart';
import 'package:car_provider_app/extensions/int_extensions.dart';
import 'package:car_provider_app/extensions/string_extensions.dart';
import 'package:car_provider_app/extensions/widget_extensions.dart';
import 'package:car_provider_app/utils/utils.dart';
import 'package:car_provider_app/widgets/app_bar.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:geolocator/geolocator.dart';

import '../../../classes/colors.dart';
import '../../../classes/utils.dart';
import '../../../config/routes.dart';
import '../../../generated/locale_keys.g.dart';

import '../../../models/m_response.dart';
import '../../../models/profile/branch.dart';
import '../../../models/profile/branch2.dart';
import '../../../utils/navigator.dart';
import '../../../widgets/button/show_fill_button.dart';

class BranchListPage extends StatefulWidget {
  @override
  State<BranchListPage> createState() => _BranchListPageState();
}

class _BranchListPageState extends State<BranchListPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(
        context,
        title: LocaleKeys.myServiceBranches.tr(),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(
          Icons.add,
          color: Colors.white,
        ),
        onPressed: () async {
          await navigateWithName(context, AppRoutes.defineBranch);
          setState(() {});
        },
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Builder(builder: (context) {
          return FutureBuilder<Branch2>(
            future: BranchApiClent().getBranchAndServices(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return snapshot.data!.data!.serviceProviderBranch!.length == 0
                    ? Center(child: Text(LocaleKeys.no_branch.tr()))
                    : ListView.separated(
                        itemBuilder: (context, index) {
                          return Row(
                            children: [
                              Container(
                                width: 74,
                                height: 50,
                                decoration: BoxDecoration(
                                  color: MyColors.darkPrimaryColor,
                                  borderRadius: BorderRadius.all(Radius.circular(8)),
                                ),
                                padding: EdgeInsets.all(6),
                                child: SvgPicture.asset(
                                  "assets/icons/ic_branchs.svg",
                                  color: Colors.white,
                                ),
                              ),
                              12.width,
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        Icon(
                                          Icons.place,
                                          size: 12,
                                          color: MyColors.darkPrimaryColor,
                                        ),
                                        Geolocator.distanceBetween(
                                                AppState().currentLocation.latitude,
                                                AppState().currentLocation.latitude,
                                                double.parse(snapshot.data!.data!.serviceProviderBranch![index].latitude ?? "0"),
                                                double.parse(snapshot.data!.data!.serviceProviderBranch![index].longitude ?? "0"))
                                            .toStringAsFixed(2)
                                            .toText12(
                                              color: MyColors.darkPrimaryColor,
                                            )
                                      ],
                                    ),
                                    Text(
                                      snapshot.data!.data!.serviceProviderBranch![index].branchName ?? "",
                                      style: TextStyle(
                                        fontSize: 14,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    LocaleKeys.tapToEdit.tr().toText10(color: MyColors.grey70Color),
                                  ],
                                ),
                              ),
                              12.width,
                              IconButton(
                                onPressed: () async {
                                  Utils.showLoading(context);
                                  MResponse res = await BranchApiClent().updateBranch(
                                      snapshot.data!.data!.serviceProviderBranch![index].id ?? 0,
                                      snapshot.data!.data!.serviceProviderBranch![index].branchName ?? "",
                                      snapshot.data!.data!.serviceProviderBranch![index].branchDescription ?? "",
                                      snapshot.data!.data!.serviceProviderBranch![index].cityId.toString(),
                                      snapshot.data!.data!.serviceProviderBranch![index].address ?? "",
                                      snapshot.data!.data!.serviceProviderBranch![index].latitude.toString(),
                                      snapshot.data!.data!.serviceProviderBranch![index].longitude.toString(),
                                      isNeedToDelete: false);
                                  Utils.hideLoading(context);
                                  if (res.messageStatus == 1) {
                                    Utils.showToast(LocaleKeys.branch_deleted.tr());
                                    setState(() {});
                                  } else {
                                    Utils.showToast(res.message ?? "");
                                  }
                                },
                                icon: Icon(Icons.delete),
                                color: Colors.red,
                              ),
                              Icon(
                                Icons.arrow_forward_rounded,
                                size: 16,
                              ),
                            ],
                          ).toContainer().onPress(() async {
                            // await navigateWithName(context, AppRoutes.defineBranch, arguments: snapshot.data!.data![index]);
                            // setState(() {});
                            snapshot.data!.data!.serviceProviderBranch![index].countryID = snapshot.data!.data!.countryID;
                            snapshot.data!.data!.serviceProviderBranch![index].countryName = snapshot.data!.data!.countryName;
                            await navigateWithName(context, AppRoutes.branchDetail, arguments: snapshot.data!.data!.serviceProviderBranch![index]);
                            setState(() {});
                          });
                        },
                        separatorBuilder: (context, index) {
                          return 12.height;
                        },
                        itemCount: snapshot.data!.data!.serviceProviderBranch!.length,
                        padding: EdgeInsets.all(12),
                      );
              } else {
                return Center(
                  child: CircularProgressIndicator(),
                );
              }
            },
          );
        }),
      ),
    );
  }
}
