import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/constants/app_constants.dart';
import 'package:hamlemuhcrm/core/constants/url_services_constant.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/customers/cubit/customers_cubit.dart';
import 'package:hamlemuhcrm/features/customers/widgets/int_textfield.dart';
import 'package:hamlemuhcrm/features/customers/widgets/string_textfield.dart';
import 'package:hamlemuhcrm/features/customers/widgets/web_textfield.dart';

import '../../../../core/constants/color_constants.dart';
import '../../../../core/constants/font_styles.dart';
import '../../../../core/utility/toast_manager.dart';
import '../../../../data/dropdown_models/country_api.dart';

class CreateCompany extends StatefulWidget {
  const CreateCompany({super.key});

  @override
  State<CreateCompany> createState() => _CreateCompanyState();
}

class _CreateCompanyState extends State<CreateCompany> {
  final String baseURL = URLAPIService.baseURL;
  String? _secilen1;
  String? _secilen2;

  var gelenIller;
  var gelenIlceler;

  String gonderilenIL = "";
  String gonderilenILCE = "";

  final String ilid = "1";
  final String ilceid = "4";

  bool isFinish = false;

  Future<void> ilData(String token, String loginuserid) async {
    var illerURL = "$baseURL/mobil/api/dd/il_dd_pdo.php";
    var veri = {"token": token, "loginuserid": loginuserid};
    var ilCevap = await Dio().post(illerURL, data: FormData.fromMap(veri));
    //print("res01 = $res01");
    if (ilCevap.statusCode == 200) {
      setState(() {
        gelenIller = json.decode(ilCevap.data.toString());
        //print("data_01 = $data_01");
      });
    } else {}
  }

  Future<void> ilceData(res01, String token, String loginuserid) async {
    var ilcelerURL = "$baseURL/mobil/api/dd/ilce_dd_pdo.php";
    var veri = {
      "il_id": _secilen1 ?? ilid,
      "token": token,
      "loginuserid": loginuserid
    };
    var ilceCevap = await Dio().post(ilcelerURL, data: FormData.fromMap(veri));
    //print(res02);

    if (ilceCevap.statusCode == 200) {
      setState(() {
        gelenIlceler = json.decode(ilceCevap.data.toString());
        //print(data_02);
      });
    } else {}
  }

  Widget ilListesi() {
    List<IlDDModel> ilListesi = List<IlDDModel>.from(
      gelenIller["harita_iller"].map(
        (i) {
          return IlDDModel.fromJSON(i);
        },
      ),
    );
    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: const Text("İl Seçiniz",
            style: TextStyle(
                color: Colors.grey,
                fontSize: 13.0,
                overflow: TextOverflow.visible)), //İl
        isExpanded: true,
        items: ilListesi.map((query1) {
          return DropdownMenuItem(
            value: query1.ilId,
            child: Text(
              query1.name,
              style: const TextStyle(fontSize: 12, color: Colors.black54),
            ), //value
          );
        }).toList(),
        value: _secilen1,
        onChanged: (newValue) {
          setState(() {
            _secilen1 = newValue.toString();
            gonderilenIL = _secilen1!;
            "_secilen ilid == $_secilen1".log();
            ilceData(ilid, context.read<LoginCubit>().token,
                context.read<LoginCubit>().id);
            _secilen2 = null;
          });
        },
        buttonStyleData: ButtonStyleData(
          height: context.dynamicHeight(0.054),
          width: context.dynamicWidth(0.38),
          padding: const EdgeInsets.symmetric(horizontal: 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: ColorsConstants.instance.backgroundColor,
            border: Border.all(
              color: Colors.grey.withOpacity(0.2),
            ),
          ),
          elevation: 0,
        ),
        iconStyleData: IconStyleData(
          icon: const Icon(
            Icons.keyboard_arrow_down_outlined, //ilk icon
          ),
          openMenuIcon: const Icon(
              Icons.keyboard_arrow_left_outlined), //açıldıktan sonraki icon
          iconSize: 23,
          iconEnabledColor: ColorsConstants.instance.baseTheme,
          iconDisabledColor: Colors.white,
        ),
        dropdownStyleData: DropdownStyleData(
          maxHeight: context.dynamicHeight(0.09), //açılır dropdown yüksekliği
          isOverButton: false,
          width: context.dynamicWidth(0.38),
          padding: null,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: ColorsConstants
                .instance.backgroundColor, //açılır menü arkaplan rengi
          ),
          elevation: 8,
          offset: const Offset(0, 0),
          scrollbarTheme: ScrollbarThemeData(
            thumbColor: MaterialStateColor.resolveWith((states) =>
                ColorsConstants
                    .instance.baseTheme), //dropdown scroll rengi değiştirme
            radius: const Radius.circular(10),
            thickness: MaterialStateProperty.all<double>(6),
            thumbVisibility: MaterialStateProperty.all<bool>(true),
          ),
        ),
        menuItemStyleData: const MenuItemStyleData(
          height: 35,
          padding: EdgeInsets.symmetric(horizontal: 14),
        ),
      ),
    );
  }

  Widget ilceListesi() {
    List<IlceDDModel> ilceListesi =
        List<IlceDDModel>.from(gelenIlceler['harita_ilceler'].map((i) {
      return IlceDDModel.fromJSON(i);
    }));

    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: const Text("İlçe",
            style: TextStyle(
                color: Colors.grey,
                fontSize: 13.0,
                overflow: TextOverflow.visible)), //İlçe
        isExpanded: true,
        items: ilceListesi.map((query2) {
          return DropdownMenuItem(
            value: query2.ilceId,
            child: Text(
              query2.name.toString().length > 14
                  ? query2.name.toString().substring(0, 13)
                  : query2.name,
              style: const TextStyle(fontSize: 13, color: Colors.black54),
            ), //DATA SENDING
          );
        }).toList(),
        value: _secilen2,
        onChanged: (newValue) {
          setState(() {
            _secilen2 = newValue.toString();
            gonderilenILCE = _secilen2!; //medium new
            "seçilen ilçe == $_secilen2".log();
          });
        },
        buttonStyleData: ButtonStyleData(
          height: context.dynamicHeight(0.054),
          width: context.dynamicWidth(0.38),
          padding: const EdgeInsets.symmetric(horizontal: 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: ColorsConstants.instance.backgroundColor,
            border: Border.all(
              color: Colors.grey.withOpacity(0.2),
            ),
          ),
          elevation: 0,
        ),
        iconStyleData: IconStyleData(
          icon: const Icon(
            Icons.keyboard_arrow_down_outlined, //ilk icon
          ),
          openMenuIcon: const Icon(
              Icons.keyboard_arrow_left_outlined), //açıldıktan sonraki icon
          iconSize: 23,
          iconEnabledColor: ColorsConstants.instance.baseTheme,
          iconDisabledColor: Colors.white,
        ),
        dropdownStyleData: DropdownStyleData(
          maxHeight: context.dynamicHeight(0.09), //açılır dropdown yüksekliği
          isOverButton: false,
          width: context.dynamicWidth(0.38),
          padding: null,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: ColorsConstants
                .instance.backgroundColor, //açılır menü arkaplan rengi
          ),
          elevation: 8,
          offset: const Offset(0, 0),
          scrollbarTheme: ScrollbarThemeData(
            thumbColor: MaterialStateColor.resolveWith((states) =>
                ColorsConstants
                    .instance.baseTheme), //dropdown scroll rengi değiştirme
            radius: const Radius.circular(10),
            thickness: MaterialStateProperty.all<double>(6),
            thumbVisibility: MaterialStateProperty.all<bool>(true),
          ),
        ),
        menuItemStyleData: const MenuItemStyleData(
          height: 35,
          padding: EdgeInsets.symmetric(horizontal: 14),
        ),
      ),
    );
  }

  Future<void> ddBilgilerCek() async {
    isFinish = false;
    await ilData(
        context.read<LoginCubit>().token, context.read<LoginCubit>().id);
    // ignore: use_build_context_synchronously
    await ilceData(
        ilid,
        // ignore: use_build_context_synchronously
        context.read<LoginCubit>().token,
        // ignore: use_build_context_synchronously
        context.read<LoginCubit>().id);
    isFinish = true;
  }

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

  final _companyKey = GlobalKey<FormState>();

  final tcFirmaAd = TextEditingController();

  final tcFirmaWeb = TextEditingController();

  final tcFirmaMail = TextEditingController();

  final tcFirmaVergiD = TextEditingController();

  final tcFirmaVergiN = TextEditingController();

  final tcFirmaTel = TextEditingController();

  final tcFirmaAdres = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return isFinish
        ? Scaffold(
            appBar: appBar(context),
            body: SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.symmetric(
                    horizontal: context.dynamicHeight(0.03)),
                child: Column(
                  children: [
                    Container(
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(15),
                          color: Colors.white,
                          boxShadow: [
                            BoxShadow(
                              color: Colors.grey.withOpacity(0.2),
                              blurRadius: 7,
                              offset: const Offset(4, 5),
                            )
                          ]),
                      child: Padding(
                        padding: const EdgeInsets.symmetric(
                            vertical: 10, horizontal: 20),
                        child: Form(
                          key: _companyKey,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const SizedBox(height: 10),
                              const Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    'Firma Adı',
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 11),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 5),
                              StringTextField(
                                textEditingController: tcFirmaAd,
                                aciklama: '',
                                yukseklik: context.dynamicHeight(0.05),
                                satirSayisi: 1,
                                kenarlik: true,
                                golge: false,
                                arkaplanRengi:
                                    ColorsConstants.instance.backgroundColor,
                                tekSatirMi: true,
                                kisitlama: 30,
                              ),
                              const SizedBox(height: 10),
                              const Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    'Web Sitesi',
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 11),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 5),
                              WebTextField(
                                textEditingController: tcFirmaWeb,
                                aciklama: '',
                                yukseklik: context.dynamicHeight(0.05),
                                satirSayisi: 1,
                                kenarlik: true,
                                golge: false,
                                arkaplanRengi:
                                    ColorsConstants.instance.backgroundColor,
                                tekSatirMi: true,
                                kisitlama: 37,
                              ),
                              const SizedBox(height: 10),
                              const Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    'Mail Adresi',
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 11),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 5),
                              StringTextField(
                                textEditingController: tcFirmaMail,
                                aciklama: '',
                                yukseklik: context.dynamicHeight(0.05),
                                satirSayisi: 1,
                                kenarlik: true,
                                golge: false,
                                arkaplanRengi:
                                    ColorsConstants.instance.backgroundColor,
                                tekSatirMi: true,
                                kisitlama: 70,
                              ),
                              const SizedBox(height: 10),
                              const Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    'Vergi Dairesi',
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 11),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 5),
                              StringTextField(
                                textEditingController: tcFirmaVergiD,
                                aciklama: '',
                                yukseklik: context.dynamicHeight(0.05),
                                satirSayisi: 1,
                                kenarlik: true,
                                golge: false,
                                arkaplanRengi:
                                    ColorsConstants.instance.backgroundColor,
                                tekSatirMi: true,
                                kisitlama: 30,
                              ),
                              const SizedBox(height: 10),
                              const Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    'Vergi No',
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 11),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 5),
                              IntTextField(
                                textEditingController: tcFirmaVergiN,
                                aciklama: '',
                                yukseklik: context.dynamicHeight(0.05),
                                satirSayisi: 1,
                                kenarlik: true,
                                golge: false,
                                arkaplanRengi:
                                    ColorsConstants.instance.backgroundColor,
                                tekSatirMi: true,
                                kisitlama: 10,
                              ),
                              const SizedBox(height: 10),
                              const Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    'Telefon No',
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 11),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 5),
                              IntTextField(
                                textEditingController: tcFirmaTel,
                                aciklama: '',
                                yukseklik: context.dynamicHeight(0.05),
                                satirSayisi: 1,
                                kenarlik: true,
                                golge: false,
                                arkaplanRengi:
                                    ColorsConstants.instance.backgroundColor,
                                tekSatirMi: true,
                                kisitlama: 11,
                              ),
                              const SizedBox(height: 15),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      const Text(
                                        'İl',
                                        style: TextStyle(
                                            fontSize: 11, color: Colors.grey),
                                      ),
                                      const SizedBox(height: 6),
                                      ilListesi(),
                                    ],
                                  ),
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      const Text(
                                        'İlçe',
                                        style: TextStyle(
                                            fontSize: 11, color: Colors.grey),
                                      ),
                                      const SizedBox(height: 6),
                                      ilceListesi(),
                                    ],
                                  ),
                                ],
                              ),
                              const SizedBox(height: 10),
                              const Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    'Adres',
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 11),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 5),
                              StringTextField(
                                textEditingController: tcFirmaAdres,
                                aciklama: '',
                                yukseklik: context.dynamicHeight(0.09),
                                satirSayisi: 3,
                                kenarlik: true,
                                golge: false,
                                arkaplanRengi:
                                    ColorsConstants.instance.backgroundColor,
                                tekSatirMi: false,
                                kisitlama: 100,
                              ),
                              const SizedBox(height: 14),
                              Container(
                                height: context.dynamicHeight(0.05),
                                decoration: BoxDecoration(
                                    color: ColorsConstants.instance.baseTheme,
                                    borderRadius: BorderRadius.circular(10),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.grey.withOpacity(0.4),
                                        blurRadius: 8,
                                        offset: const Offset(1, 1),
                                      )
                                    ]),
                                child: TextButton(
                                    onPressed: () async {
                                      await checkVerify().then((value) async {
                                        if (!value) return;
                                        await addCompanyService().then((value) {
                                          if (!value) return;
                                          Navigator.popUntil(context,
                                              (route) => route.isFirst);
                                        });
                                      });
                                    },
                                    style: TextButton.styleFrom(
                                        backgroundColor: Colors.transparent,
                                        shape: RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(10),
                                        )),
                                    child: Padding(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 10.0),
                                      child: Text(
                                        ApplicationConstants
                                            .instance.moduleSaveTxt,
                                        style: const TextStyle(
                                            color: Colors.white),
                                      ),
                                    )),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 15),
                  ],
                ),
              ),
            ),
          )
        : const Scaffold();
  }

  Future<bool> checkVerify() async {
    if (tcFirmaAd.text.isEmpty ||
        tcFirmaWeb.text.isEmpty ||
        tcFirmaMail.text.isEmpty ||
        tcFirmaVergiD.text.isEmpty ||
        tcFirmaVergiN.text.isEmpty ||
        tcFirmaTel.text.isEmpty ||
        tcFirmaAdres.text.isEmpty) {
      ToastManager.instance.toastMessageService("Eksik alanlar var !");
      return false;
    }

    return true;
  }

  Future<bool> addCompanyService() async {
    final response = await context.read<CustomersCubit>().firmaEkle(
        context.read<LoginCubit>().userfirmId,
        tcFirmaAd.text,
        tcFirmaWeb.text,
        tcFirmaMail.text,
        tcFirmaVergiD.text,
        tcFirmaVergiN.text,
        tcFirmaTel.text,
        tcFirmaAdres.text,
        context.read<LoginCubit>().id,
        gonderilenIL,
        gonderilenILCE,
        context.read<LoginCubit>().token,
        // Bu parametre listeyi güncelleyebilmek için gerekli
        context.read<LoginCubit>().tip);

    switch (response) {
      case true:
        return true;
      case false:
        return false;
    }
  }
}

AppBar appBar(BuildContext context) {
  return AppBar(
    backgroundColor: Colors.transparent,
    elevation: 0,
    title: Text('Firma Oluştur', style: FontStyles.instance.appbarTitleStyle),
    centerTitle: true,
    actions: [
      IconButton(
          onPressed: () {},
          icon: const Icon(
            Icons.notifications_none_outlined,
            color: Colors.black,
          )),
    ],
    leading: IconButton(
        onPressed: () {
          Navigator.of(context).popUntil((route) => route.isFirst);
        },
        icon: const Icon(
          Icons.arrow_back_ios_new,
          color: Colors.black54,
          size: 20,
        )),
  );
}
