import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:hamlemuhcrm/core/constants/color_constants.dart';
import 'package:hamlemuhcrm/core/constants/font_styles.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/data/dropdown_models/personal_getdata_api.dart';

import '../../../core/constants/url_services_constant.dart';

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

  @override
  State<CustomersLeadersDropdown> createState() =>
      _CustomersLeadersDropdownState();
}

class _CustomersLeadersDropdownState extends State<CustomersLeadersDropdown> {
  ///////////////////////////////////////////
  late String yetkiliFirmaId;
  String? _secilen1;
  bool yetkiliListesiBosMu = false;
  String gonderilenYetkiliID = "";
  var gelenYetkililer;
  bool yetkiliGecerli = false;

  Future<void> yetkiliData(res01, String token, String loginuserid) async {
    var yetkililerURL =
        "${URLAPIService.baseURL}/mobil/api/dd/yetkili_dd_pdo.php";
    var veri = {
      "yetkili_firma_id": _secilen1 ?? yetkiliFirmaId,
      "token": token,
      "loginuserid": loginuserid
    };
    var yetkililerCevap =
        await Dio().post(yetkililerURL, data: FormData.fromMap(veri));
    '${yetkililerCevap.data}'.log();

    if (yetkililerCevap.statusCode == 200) {
      setState(() {
        gelenYetkililer = json.decode(yetkililerCevap.data.toString());
        yetkiliListesiBosMu =
            gelenYetkililer.toString().contains('{firma_yetkililer: []}');
        yetkiliGecerli = gelenYetkililer
            .toString()
            .contains('{yetkili_id: $yetkiliFirmaId,');
        'widget.yetkili_id : $yetkiliFirmaId'.log();
        'gecerli : $yetkiliGecerli'.log();
        'bos liste : $yetkiliListesiBosMu'.log();
      });
    } else {}
  }

  @override
  Widget build(BuildContext context) {
    List<YetkiliDDModel> personelList =
        List<YetkiliDDModel>.from(gelenYetkililer["firma_yetkililer"].map((i) {
      return YetkiliDDModel.fromJSON(i);
    }));

    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: Text(
          yetkiliListesiBosMu ? "Lütfen önce yetkili ekleyin" : '',
          style: const TextStyle(fontSize: 13, color: Colors.black54),
        ),
        isExpanded: true,
        items: personelList.map((personel) {
          return DropdownMenuItem(
            value: personel.yetkiliId,
            child: Text(
              txtSigdir(personel.yetkiliAdSoyad, personel.yetkiliIlgiliBirim),
              style: FontStyles.instance.ddYazi,
            ), //DATA SENDING
          );
        }).toList(),
        value: _secilen1,
        onChanged: (newValue) {
          setState(() {
            _secilen1 = newValue.toString();
            gonderilenYetkiliID = _secilen1!; //medium new
            "seçilen personel == $_secilen1".log();
            "gonderilen YetkiliID == $gonderilenYetkiliID".log();
          });
        },
        buttonStyleData: ButtonStyleData(
          height: context.dynamicHeight(0.054),
          width: context.dynamicWidth(0.9),
          padding: const EdgeInsets.symmetric(horizontal: 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                  color: Colors.grey.withOpacity(0.3),
                  offset: const Offset(0.4, 0.3),
                  blurRadius: 7)
            ],
          ),
          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.17),
          isOverButton: false,
          width: context.dynamicWidth(0.9),
          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),
        ),
      ),
    );
  }

  String txtSigdir(String txt, String? txt2) {
    return txt.length > 24
        ? '${txt.substring(0, 23)} ${txt2 ?? 'Unvan Yok'}'
        : '$txt $txt2';
  }
}
