import 'package:flutter/material.dart';
import 'package:search_choices/search_choices.dart';

import '../device_model.dart';
import 'device_update_bloc.dart';
import 'map_dialog.dart';
import '../../../product/base/bloc/base_bloc.dart';
import '../../../product/extention/context_extention.dart';
import '../../../product/services/api_services.dart';
import '../../../product/services/language_services.dart';

import '../../../product/shared/model/district_model.dart';
import '../../../product/shared/model/province_model.dart';
import '../../../product/shared/model/ward_model.dart';

class DeviceUpdateScreen extends StatefulWidget {
  const DeviceUpdateScreen({super.key, required this.thingID});
  final String thingID;
  @override
  State<DeviceUpdateScreen> createState() => _DeviceUpdateScreenState();
}

class _DeviceUpdateScreenState extends State<DeviceUpdateScreen> {
  late DeviceUpdateBloc deviceUpdateBloc;
  APIServices apiServices = APIServices();
  Device device = Device();
  bool isChanged = false;
  TextEditingController deviceNameController = TextEditingController();
  TextEditingController deviceLatitudeController = TextEditingController();
  TextEditingController deviceLongitudeController = TextEditingController();
  List<DropdownMenuItem<Province>> provincesData = [];
  String? selectedProvince = "";
  List<DropdownMenuItem<District>> districtsData = [];
  String? selectedDistrict = "";
  List<DropdownMenuItem<Ward>> wardsData = [];
  String? selectedWard = "";

  // static String provinceCode = "";
  // static String districtCode = "";
  // static String wardCode = "";

  Map<String, String> provinceData = {};
  Map<String, String> districtData = {};
  Map<String, String> wardData = {};

  @override
  void initState() {
    super.initState();
    deviceUpdateBloc = BlocProvider.of(context);
    deviceUpdateBloc.getAllProvinces();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(appLocalization(context).device_update_title),
      ),
      body: StreamBuilder<Map<String, String>>(
          stream: deviceUpdateBloc.streamProvinceData,
          builder: (context, provinceNameSnapshot) {
            return StreamBuilder<Map<String, String>>(
                stream: deviceUpdateBloc.streamDistrictData,
                builder: (context, districtNameSnapshot) {
                  return StreamBuilder<Map<String, String>>(
                      stream: deviceUpdateBloc.streamWardData,
                      builder: (context, wardNameSnapshot) {
                        return SafeArea(
                          child: StreamBuilder<Device>(
                            stream: deviceUpdateBloc.streamDeviceInfo,
                            initialData: device,
                            builder: (context, deviceInfoSnapshot) {
                              if (deviceInfoSnapshot.data!.thingId == null) {
                                deviceUpdateBloc.getDeviceInfomation(
                                    widget.thingID,
                                    districtsData,
                                    wardsData,
                                    deviceNameController,
                                    deviceLatitudeController,
                                    deviceLongitudeController);
                                return const Center(
                                  child: CircularProgressIndicator(),
                                );
                              } else {
                                return StreamBuilder<bool>(
                                  stream: deviceUpdateBloc.streamIsChanged,
                                  initialData: isChanged,
                                  builder: (context, isChangedSnapshot) {
                                    return SingleChildScrollView(
                                      child: Padding(
                                        padding: context.paddingLow,
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                                "${appLocalization(context).input_name_device_device}:",
                                                style: context
                                                    .titleMediumTextStyle),
                                            Padding(
                                              padding:
                                                  context.paddingLowVertical,
                                              child: TextField(
                                                onChanged: (value) {
                                                  isChangedListener();
                                                },
                                                textInputAction:
                                                    TextInputAction.next,
                                                controller:
                                                    deviceNameController,
                                                decoration: InputDecoration(
                                                  hintText: appLocalization(
                                                          context)
                                                      .input_name_device_hintText,
                                                ),
                                              ),
                                            ),
                                            Text(
                                                "${appLocalization(context).device_update_location}:",
                                                style: context
                                                    .titleMediumTextStyle),
                                            Padding(
                                              padding:
                                                  context.paddingLowVertical,
                                              child: Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                children: [
                                                  SizedBox(
                                                    width: context
                                                        .dynamicWidth(0.6),
                                                    child: Column(
                                                      children: [
                                                        SizedBox(
                                                          child: TextField(
                                                            onChanged: (value) {
                                                              isChangedListener();
                                                            },
                                                            textInputAction:
                                                                TextInputAction
                                                                    .next,
                                                            controller:
                                                                deviceLatitudeController,
                                                            decoration:
                                                                InputDecoration(
                                                              label: Text(
                                                                  "${appLocalization(context).update_device_dialog_location_longitude}:"),
                                                              hintText: appLocalization(
                                                                      context)
                                                                  .update_device_dialog_location_longitude_hintText,
                                                            ),
                                                          ),
                                                        ),
                                                        Padding(
                                                          padding: context
                                                              .paddingLowVertical,
                                                          child: SizedBox(
                                                            child: TextField(
                                                              onChanged:
                                                                  (value) {
                                                                isChangedListener();
                                                              },
                                                              controller:
                                                                  deviceLongitudeController,
                                                              textInputAction:
                                                                  TextInputAction
                                                                      .next,
                                                              decoration:
                                                                  InputDecoration(
                                                                label: Text(
                                                                    "${appLocalization(context).update_device_dialog_location_latitude}:"),
                                                                hintText: appLocalization(
                                                                        context)
                                                                    .update_device_dialog_location_latitude_hintText,
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                  Center(
                                                    child: IconButton.filled(
                                                      style: const ButtonStyle(
                                                          backgroundColor:
                                                              MaterialStatePropertyAll(
                                                                  Colors
                                                                      .lightGreen)),
                                                      // iconSize: 24,
                                                      onPressed: () async {
                                                        showMapDialog(
                                                            context,
                                                            deviceUpdateBloc,
                                                            deviceLatitudeController,
                                                            deviceLongitudeController);
                                                      },
                                                      icon: const Icon(
                                                        Icons.map_outlined,
                                                      ),
                                                    ),
                                                  ),
                                                  SizedBox(
                                                      width: context.lowValue),
                                                ],
                                              ),
                                            ),
                                            Text(
                                                "${appLocalization(context).device_update_province}:",
                                                style: context
                                                    .titleMediumTextStyle),
                                            Padding(
                                              padding:
                                                  context.paddingLowVertical,
                                              child: StreamBuilder<
                                                  List<
                                                      DropdownMenuItem<
                                                          Province>>>(
                                                stream: deviceUpdateBloc
                                                    .streamListProvinces,
                                                builder: (dialogContext,
                                                    listProvinces) {
                                                  return Container(
                                                    decoration: BoxDecoration(
                                                      borderRadius:
                                                          const BorderRadius
                                                              .all(
                                                        Radius.circular(20),
                                                      ),
                                                      border: Border.all(),
                                                    ),
                                                    child: SearchChoices.single(
                                                      items:
                                                          listProvinces.data ??
                                                              provincesData,
                                                      hint: provinceNameSnapshot
                                                                  .data !=
                                                              null
                                                          ? Text(
                                                              provinceNameSnapshot
                                                                          .data![
                                                                      'name'] ??
                                                                  "",
                                                            )
                                                          : appLocalization(
                                                                  context)
                                                              .update_device_dialog_location_province_hintText,
                                                      searchHint: appLocalization(
                                                              context)
                                                          .update_device_dialog_location_province_searchHint,
                                                      displayClearIcon: false,
                                                      onChanged: (value) {
                                                        isChangedListener();
                                                        // provinceCode =
                                                        //     value.code;
                                                        selectedProvince =
                                                            value.fullName;
                                                        provinceData['name'] =
                                                            value.fullName;
                                                        provinceData['code'] =
                                                            value.code;
                                                        deviceUpdateBloc
                                                            .sinkProvinceData
                                                            .add(provinceData);
                                                        deviceUpdateBloc
                                                            .getAllDistricts(
                                                                value.code);
                                                        selectedDistrict = "";
                                                        districtData['name'] =
                                                            selectedDistrict!;
                                                        // deviceUpdateBloc.sinkDistrictName
                                                        //     .add(selectedDistrict);
                                                        deviceUpdateBloc
                                                            .sinkDistrictData
                                                            .add(districtData);
                                                        selectedWard = "";
                                                        wardData['name'] =
                                                            selectedWard!;
                                                        deviceUpdateBloc
                                                            .sinkWardData
                                                            .add(wardData);
                                                      },
                                                      isExpanded: true,
                                                    ),
                                                  );
                                                },
                                              ),
                                            ),
                                            Text(
                                                "${appLocalization(context).device_update_district}:",
                                                style: context
                                                    .titleMediumTextStyle),
                                            Padding(
                                              padding:
                                                  context.paddingLowVertical,
                                              child: StreamBuilder<
                                                  List<
                                                      DropdownMenuItem<
                                                          District>>>(
                                                stream: deviceUpdateBloc
                                                    .streamListDistricts,
                                                builder: (dialogContext,
                                                    listDistricts) {
                                                  return Container(
                                                    decoration: BoxDecoration(
                                                      borderRadius:
                                                          const BorderRadius
                                                              .all(
                                                        Radius.circular(20),
                                                      ),
                                                      border: Border.all(),
                                                    ),
                                                    child: SearchChoices.single(
                                                      items:
                                                          listDistricts.data ??
                                                              districtsData,
                                                      hint: districtNameSnapshot
                                                                  .data !=
                                                              null
                                                          ? Text(
                                                              districtNameSnapshot
                                                                          .data![
                                                                      'name'] ??
                                                                  selectedDistrict!,
                                                            )
                                                          : appLocalization(
                                                                  context)
                                                              .update_device_dialog_location_district_hintText,
                                                      searchHint: appLocalization(
                                                              context)
                                                          .update_device_dialog_location_district_searchHint,
                                                      displayClearIcon: false,
                                                      onChanged: (value) {
                                                        isChangedListener();
                                                        // districtCode =
                                                        //     value.code;
                                                        selectedDistrict =
                                                            value.fullName;
                                                        districtData['name'] =
                                                            value.fullName!;
                                                        districtData['code'] =
                                                            value.code;
                                                        deviceUpdateBloc
                                                            .sinkDistrictData
                                                            .add(districtData);
                                                        deviceUpdateBloc
                                                            .getAllWards(
                                                                value.code);
                                                        selectedWard = "";
                                                        wardData['name'] =
                                                            selectedWard!;
                                                        deviceUpdateBloc
                                                            .sinkWardData
                                                            .add(wardData);
                                                      },
                                                      isExpanded: true,
                                                    ),
                                                  );
                                                },
                                              ),
                                            ),
                                            Text(
                                                "${appLocalization(context).device_update_ward}:",
                                                style: context
                                                    .titleMediumTextStyle),
                                            Padding(
                                              padding:
                                                  context.paddingLowVertical,
                                              child: StreamBuilder<
                                                  List<DropdownMenuItem<Ward>>>(
                                                stream: deviceUpdateBloc
                                                    .streamListWards,
                                                builder:
                                                    (dialogContext, listWards) {
                                                  return Container(
                                                    decoration: BoxDecoration(
                                                        borderRadius:
                                                            const BorderRadius
                                                                    .all(
                                                                Radius.circular(
                                                                    20)),
                                                        border: Border.all()),
                                                    child: SearchChoices.single(
                                                      items: listWards.data ??
                                                          wardsData,
                                                      hint: wardNameSnapshot
                                                                  .data !=
                                                              null
                                                          ? Text(
                                                              wardNameSnapshot
                                                                          .data![
                                                                      'name'] ??
                                                                  selectedWard!,
                                                            )
                                                          : appLocalization(
                                                                  context)
                                                              .update_device_dialog_location_ward_hintText,
                                                      searchHint: appLocalization(
                                                              context)
                                                          .update_device_dialog_location_ward_searchHint,
                                                      displayClearIcon: false,
                                                      onChanged: (value) {
                                                        isChangedListener();
                                                        // wardCode = value.code;
                                                        selectedWard =
                                                            value.fullName;
                                                        wardData['name'] =
                                                            value.fullName!;
                                                        wardData['code'] =
                                                            value.code!;
                                                        deviceUpdateBloc
                                                            .sinkWardData
                                                            .add(wardData);
                                                      },
                                                      isExpanded: true,
                                                    ),
                                                  );
                                                },
                                              ),
                                            ),
                                            if (isChangedSnapshot.data == true)
                                              Center(
                                                child: SizedBox(
                                                  width:
                                                      context.dynamicWidth(0.6),
                                                  child: TextButton(
                                                      style: ButtonStyle(
                                                          foregroundColor:
                                                              MaterialStateProperty
                                                                  .all(Colors
                                                                      .white),
                                                          backgroundColor:
                                                              MaterialStateProperty
                                                                  .all(Colors
                                                                      .blue)),
                                                      onPressed: () async {
                                                        String provinceCode =
                                                            provinceNameSnapshot
                                                                        .data![
                                                                    "code"] ??
                                                                "";
                                                        String districtCode =
                                                            districtNameSnapshot
                                                                        .data![
                                                                    "code"] ??
                                                                "";
                                                        String wardCode =
                                                            wardNameSnapshot
                                                                        .data![
                                                                    "code"] ??
                                                                "";
                                                        String latitude =
                                                            deviceLatitudeController
                                                                .value.text;
                                                        String longitude =
                                                            deviceLongitudeController
                                                                .value.text;
                                                        String deviceName =
                                                            deviceNameController
                                                                .value.text;
                                                        // log("ProvinceCode: $provinceCode");
                                                        // log("DistrictCode: $districtCode");
                                                        // log("WardCode: $wardCode");
                                                        // log("Latitude: $latitude");
                                                        // log("Longitude: $longitude");
                                                        // log("Device Name: $deviceName");
                                                        await deviceUpdateBloc
                                                            .updateDevice(
                                                          context,
                                                          deviceInfoSnapshot
                                                              .data!.thingId!,
                                                          deviceName,
                                                          latitude,
                                                          longitude,
                                                          provinceCode,
                                                          districtCode,
                                                          wardCode,
                                                        );
                                                        Future.delayed(
                                                            // ignore: use_build_context_synchronously
                                                            context.lowDuration,
                                                            () {
                                                          Navigator.pop(
                                                              context);
                                                        });
                                                      },
                                                      child: Text(appLocalization(
                                                              context)
                                                          .update_button_content)),
                                                ),
                                              ),
                                          ],
                                        ),
                                      ),
                                    );
                                  },
                                );
                              }
                            },
                          ),
                        );
                      });
                });
          }),
    );
  }

  void isChangedListener() {
    isChanged = true;
    deviceUpdateBloc.sinkIsChanged.add(isChanged);
  }
}
