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:intl/intl.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/features/customers/view/activities/activity_update.dart';

import '../../../../../core/constants/app_constants.dart';
import '../../../../../core/constants/color_constants.dart';
import '../../../../../core/constants/font_styles.dart';
import '../../../../../core/constants/url_services_constant.dart';
import '../../../../../data/dropdown_models/personal_getdata_api.dart';
import '../../../../auth/login/cubit/login_cubit.dart';

mixin ActivityUpdateMixin on State<ActivityUpdate> {
  //////////////////////////////// class fields /////////////////////////////////////////////////////////
  final String baseURL = URLAPIService.baseURL;
  bool isFinish = false;
  final TextEditingController tcAktiviteBaslik = TextEditingController();
  final TextEditingController tfAciklama = TextEditingController();
  final DateFormat format = DateFormat.yMd('tr');

  bool saatSecildi = false;
  String dbSaat = '';
  String gosterilenSaat = '';

  //////////////////////////////// yetkili dd /////////////////////////////////////////////////////////
  Map<String, dynamic>? gelenYetkililer;
  bool yetkiliGecerli = false;
  String? _secilen1;
  String? _secilenYetkili;
  bool yetkiliListesiBosMu = false;
  String gonderilenYetkiliID = "";
  late final String archiveBtn;
  late String yetkiliFirmaId;

  Future<void> yetkiliData(res01, String token, String loginuserid) async {
    var yetkililerURL = "$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: ${widget.yetkiliID},');
        'widget.yetkili_id : ${widget.yetkiliID}'.log();
        'gecerli : $yetkiliGecerli'.log();
        'bos liste : $yetkiliListesiBosMu'.log();
      });
    } else {}
  }

  Widget yetkiliDD() {
    List<YetkiliDDModel> personelListesi =
        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: personelListesi.map((personel) {
          return DropdownMenuItem(
            value: personel.yetkiliId,
            child: Text(
              txtSigdir(personel.yetkiliAdSoyad, personel.yetkiliIlgiliBirim),
              style: FontStyles.instance.ddYazi,
            ), //DATA SENDING
          );
        }).toList(),
        value: _secilenYetkili,
        onChanged: (newValue) {
          setState(() {
            _secilenYetkili = newValue.toString();
            gonderilenYetkiliID = _secilenYetkili!; //medium new
            "seçilen personel == $_secilenYetkili".log();
            "gonderilen YetkiliID == $gonderilenYetkiliID".log();
          });
        },
        buttonStyleData: ButtonStyleData(
          height: context.dynamicHeight(0.05),
          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';
  }

//////////////////////////////// calisan dd /////////////////////////////////////////////////////////

  Map<String, dynamic>? gelenCalisanlar;
  String? _secilenCalisan;
  String gonderilenCalisanID = "";

  Future<void> calisanData(
      String token, String loginuserid, String userfirmid) async {
    var calisanURL = "$baseURL/mobil/api/dd/personel_dd_pdo.php";
    var veri = {
      "token": token,
      "loginuserid": loginuserid,
      "userfirmid": userfirmid
    };
    var calisanCevap =
        await Dio().post(calisanURL, data: FormData.fromMap(veri));
    if (calisanCevap.statusCode == 200) {
      setState(() {
        gelenCalisanlar = json.decode(calisanCevap.data);
      });
    } else {}
  }

  Widget calisanDD() {
    List<CalisanDDModel> calisanListesi = List<CalisanDDModel>.from(
      gelenCalisanlar?["users"].map(
        (i) {
          return CalisanDDModel.fromJSON(i);
        },
      ),
    );

    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: const Text(
          "",
          style: TextStyle(fontSize: 12, color: Colors.black54),
        ), //Data1
        isExpanded: true,
        items: calisanListesi.map((calisan) {
          return DropdownMenuItem(
            value: calisan.id,
            child: Text(
                '${calisan.firstName} ${calisan.lastName} - (${calisan.userfirmAd})',
                style: FontStyles.instance.ddYazi), //value
          );
        }).toList(),
        value: _secilenCalisan,
        onChanged: (newValue) {
          setState(() {
            _secilenCalisan = newValue;
            gonderilenCalisanID = _secilenCalisan!;
            "_secilen CalisanID == $_secilenCalisan".log();
          });
        },
        buttonStyleData: ButtonStyleData(
          height: context.dynamicHeight(0.05),
          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),
        ),
      ),
    );
  }

///////////////// gorusme tipi /////////////////////////////////////////////////////////////////////////////////////////

  String? secilenGorusme;

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  Future<void> ddBilgilerCek() async {
    final String token = context.read<LoginCubit>().token;
    final String loginid = context.read<LoginCubit>().id;
    final String userfirmid = context.read<LoginCubit>().userfirmId;
    await calisanData(token, loginid, userfirmid);
    await yetkiliData(widget.firmaID, token, loginid);
  }

  @override
  void initState() {
    isFinish = false;
    yetkiliFirmaId = widget.firmaID;
    tcAktiviteBaslik.text = widget.gorusmeBaslik;
    _secilenCalisan = widget.katilanPersonelID;
    gonderilenCalisanID = widget.katilanPersonelID;
    secilenGorusme = widget.gorusmeTuru;
    dbSaat = widget.tarih;
    archiveBtn = widget.arsivMi
        ? ApplicationConstants.instance.moduleUnArchiveTxt
        : ApplicationConstants.instance.moduleArchiveTxt;
    String tRtarih = format.format(DateTime.parse(dbSaat));
    gosterilenSaat = tRtarih;
    tfAciklama.text = widget.aciklama;
    "widgettan gelen id : ${widget.katilanPersonelID}".log();
    ddBilgilerCek().whenComplete(() {
      if (widget.yetkiliID != '0') {
        yetkiliGecerli ? _secilenYetkili = widget.yetkiliID : null;
        yetkiliGecerli ? gonderilenYetkiliID = widget.yetkiliID : null;
      }
      isFinish = true;
    });
    super.initState();
  }
}
