import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:intl/intl.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/core/widgets/page_loading.dart';
import 'package:hamlemuhcrm/features/customers/view/activities/mixin/shared_activity_mixin.dart';

import '../../../../core/constants/app_constants.dart';
import '../../../../core/constants/color_constants.dart';
import '../../../../core/constants/font_styles.dart';
import '../../../../core/extensions/responsive_extension.dart';
import '../../../../core/utility/toast_manager.dart';
import '../../../auth/login/cubit/login_cubit.dart';
import '../../cubit/activity_cubit.dart';
import '../../cubit/customers_cubit.dart';
import '../../widgets/custom_activity_textfield.dart';
import '../../widgets/interview_type_dd.dart';
import '../../widgets/string_textfield.dart';
import '../companies/add_person_parametry.dart';
import 'mixin/activity_update_mixin.dart';

class ActivityUpdate extends StatefulWidget {
  final String gorusmeID;
  final String gorusmeBaslik;
  final String yetkiliID;
  final String katilanPersonelID;
  final String tarih;
  final String gorusmeTuru;
  final String firmaAd;
  final String firmaID;
  final String aciklama;
  final bool arsivMi;

  const ActivityUpdate(
      {super.key,
      required this.gorusmeID,
      required this.firmaAd,
      required this.firmaID,
      required this.gorusmeBaslik,
      required this.yetkiliID,
      required this.katilanPersonelID,
      required this.tarih,
      required this.gorusmeTuru,
      required this.aciklama,
      required this.arsivMi});

  @override
  State<ActivityUpdate> createState() => _ActivityUpdateState();
}

class _ActivityUpdateState extends State<ActivityUpdate>
    with ActivityUpdateMixin, SharedActivityMixin {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text('Aktivite Detayı',
            style: FontStyles.instance.appbarTitleStyle),
        centerTitle: true,
        actions: [
          IconButton(
            onPressed: () {},
            icon: const Icon(
              Icons.notifications_none_outlined,
              color: Colors.black,
            ),
          ),
        ],
        leading: IconButton(
          onPressed: () {
            FocusScope.of(context).unfocus();
            Navigator.popUntil(context, (route) => route.isFirst);
          },
          icon: const Icon(
            Icons.arrow_back_ios_new,
            color: Colors.black54,
            size: 20,
          ),
        ),
      ),
      body: isFinish
          ? SingleChildScrollView(
              child: Padding(
                  padding: EdgeInsets.symmetric(
                      horizontal: context.dynamicHeight(0.02)),
                  child: Column(
                    children: [
                      const SizedBox(height: 4),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 14),
                        height: context.dynamicHeight(0.164),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(15),
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.2),
                                blurRadius: 7,
                                offset: const Offset(4, 5),
                              )
                            ]),
                        alignment: Alignment.center,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            CustomActivityTextField(
                                tf: tcAktiviteBaslik,
                                icon: Icons.stacked_line_chart_rounded,
                                icYazi: 'Aktivite Başlığı Giriniz..',
                                iconRenk: Colors.blue,
                                yukseklik: 0.050),
                            Container(
                              height: context.dynamicHeight(0.050),
                              decoration: BoxDecoration(
                                color: ColorsConstants.instance.backgroundColor,
                                borderRadius: BorderRadius.circular(8),
                                border: Border.all(
                                    color: Colors.grey.withOpacity(0.24),
                                    width: 1.1),
                              ),
                              alignment: Alignment.center,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  SizedBox(width: context.dynamicWidth(0.025)),
                                  Icon(
                                    Icons.business_rounded,
                                    color: ColorsConstants.instance.baseTheme,
                                  ),
                                  SizedBox(width: context.dynamicWidth(0.03)),
                                  Text(
                                    widget.firmaAd.length > 27
                                        ? widget.firmaAd.substring(0, 26)
                                        : widget.firmaAd,
                                    style: const TextStyle(color: Colors.grey),
                                    textAlign: TextAlign.center,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 15),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          const SizedBox(width: 5),
                          Container(
                            height: context.dynamicWidth(0.042),
                            width: context.dynamicWidth(0.042),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(7),
                              color: Colors.blue.withOpacity(0.2),
                            ),
                            child: const Icon(
                              Icons.person_outline_outlined,
                              size: 13,
                              color: Colors.blue,
                            ),
                          ),
                          const SizedBox(width: 10),
                          Row(
                            children: [
                              const Text('Görüşülen Firma Yetkilisi'),
                              SizedBox(
                                height: context.dynamicHeight(0.044),
                                width: context.dynamicWidth(0.07),
                                child: IconButton(
                                    tooltip: "Yetkili Ekle",
                                    onPressed: () {
                                      widget.firmaID == ''
                                          ? null
                                          : Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                  builder: (context) =>
                                                      AddPersonParametry(
                                                          id: widget.firmaID,
                                                          firmaAd:
                                                              widget.firmaAd,
                                                          durum: 3)));
                                    },
                                    icon: const Icon(
                                      Icons.add_circle_outlined,
                                      color: Colors.blue,
                                      size: 15,
                                    )),
                              ),
                            ],
                          ),
                          const SizedBox(height: 7),
                        ],
                      ),
                      const SizedBox(height: 5),
                      yetkiliDD(),
                      yetkiliListesiBosMu
                          ? const SizedBox(height: 13)
                          : const SizedBox(height: 7),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          const SizedBox(width: 5),
                          Container(
                            height: context.dynamicWidth(0.042),
                            width: context.dynamicWidth(0.042),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(7),
                              color: Colors.orangeAccent.withOpacity(0.2),
                            ),
                            child: const Icon(
                              Icons.people_alt_outlined,
                              size: 13,
                              color: Colors.orangeAccent,
                            ),
                          ),
                          const SizedBox(width: 10),
                          const Text('Görüşmeye Katılan Personel'),
                        ],
                      ),
                      yetkiliListesiBosMu
                          ? const SizedBox(height: 10)
                          : const SizedBox(height: 8),
                      calisanDD(),
                      yetkiliListesiBosMu
                          ? const SizedBox(height: 10)
                          : const SizedBox(height: 7),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          const SizedBox(width: 5),
                          Container(
                            height: context.dynamicWidth(0.042),
                            width: context.dynamicWidth(0.042),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(7),
                              color: Colors.green.withOpacity(0.2),
                            ),
                            child: const Icon(
                              Icons.calendar_month,
                              size: 13,
                              color: Colors.green,
                            ),
                          ),
                          const SizedBox(width: 10),
                          const Text('Görüşme Tarihi'),
                        ],
                      ),
                      const SizedBox(height: 5),
                      Container(
                          height: context.dynamicHeight(0.05),
                          width: context.dynamicWidth(0.9),
                          alignment: Alignment.center,
                          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)
                              ]),
                          child: Row(
                            children: [
                              const SizedBox(width: 10),
                              Text(
                                gosterilenSaat,
                                style: FontStyles.instance.ddYazi,
                              ),
                              const Spacer(),
                              IconButton(
                                  onPressed: dateTimePickerWidget,
                                  tooltip: 'Tarih Seç',
                                  padding: EdgeInsets.zero,
                                  icon: Icon(
                                    Icons.keyboard_arrow_down_outlined,
                                    size: 23,
                                    color: ColorsConstants.instance.baseTheme,
                                  )),
                            ],
                          )),
                      const SizedBox(height: 10),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          const SizedBox(width: 5),
                          Container(
                            height: context.dynamicWidth(0.042),
                            width: context.dynamicWidth(0.042),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(7),
                              color: Colors.purpleAccent.withOpacity(0.2),
                            ),
                            child: const Icon(
                              Icons.commit_outlined,
                              size: 13,
                              color: Colors.purpleAccent,
                            ),
                          ),
                          const SizedBox(width: 10),
                          const Text('Görüşme Tipi')
                        ],
                      ),
                      const SizedBox(height: 8),
                      const InterViewTypeDD(
                        isShadow: true,
                        isShort: false,
                      ),
                      const SizedBox(height: 8),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          const SizedBox(width: 5),
                          Container(
                            height: context.dynamicWidth(0.042),
                            width: context.dynamicWidth(0.042),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(7),
                              color: Colors.grey.withOpacity(0.5),
                            ),
                            child: const Icon(
                              Icons.message_outlined,
                              size: 13,
                              color: Colors.black26,
                            ),
                          ),
                          const SizedBox(width: 8),
                          const Text(
                            'Açıklama',
                            style: TextStyle(fontSize: 13),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      StringTextField(
                        textEditingController: tfAciklama,
                        aciklama: 'Lütfen açıklama giriniz..',
                        kenarlik: false,
                        satirSayisi: 4,
                        yukseklik: context.dynamicHeight(0.13),
                        arkaplanRengi: Colors.white,
                        golge: true,
                        tekSatirMi: false,
                        kisitlama: 140,
                      ),
                      const SizedBox(height: 8),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 8.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            TextButton(
                                onPressed: () {
                                  widget.arsivMi
                                      ? _showSnackBarAction(
                                          "Arşivden Çıkarılsın mı?",
                                          _activityUnArchive)
                                      : _showSnackBarAction(
                                          "Arşivlensin mi?", _activityArchive);
                                },
                                style: TextButton.styleFrom(
                                    backgroundColor:
                                        ColorsConstants.instance.baseTheme,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(10),
                                    )),
                                child: Center(
                                  child: Text(
                                    widget.arsivMi
                                        ? ApplicationConstants
                                            .instance.moduleUnArchiveTxt
                                        : ApplicationConstants
                                            .instance.moduleArchiveTxt,
                                    style: const TextStyle(color: Colors.white),
                                  ),
                                )),
                            const SizedBox(width: 15),
                            TextButton(
                                onPressed: updateButton,
                                style: TextButton.styleFrom(
                                    backgroundColor:
                                        ColorsConstants.instance.baseTheme,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(10),
                                    )),
                                child: Center(
                                  child: Text(
                                    ApplicationConstants
                                        .instance.moduleUpdateTxt,
                                    style: const TextStyle(color: Colors.white),
                                  ),
                                )),
                          ],
                        ),
                      ),
                    ],
                  )),
            )
          : const PageLoading(),
    );
  }

  void dateTimePickerWidget() => DatePicker.showDatePicker(
        context,
        dateFormat: 'dd/MM/yyyy',
        locale: DateTimePickerLocale.tr,
        initialDateTime: DateTime.now(),
        minDateTime: DateTime(2005),
        maxDateTime: DateTime(2100),
        pickerTheme: DateTimePickerTheme(
          backgroundColor: ColorsConstants.instance.backgroundColor,
          confirm: saatSecildi
              ? Text(
                  'Değiştir',
                  style: TextStyle(color: ColorsConstants.instance.baseTheme),
                )
              : Text(
                  'Yeni Tarih Seç',
                  style: TextStyle(color: ColorsConstants.instance.baseTheme),
                ),
        ),
        onMonthChangeStartWithFirstDate: true,
        onConfirm: (dateTime, List<int> index) {
          DateTime selectdate = dateTime;
          final selIOS = DateFormat('yyyy-MM-dd HH:mm').format(selectdate);
          setState(() {
            dbSaat = '$selIOS:00';
            dbSaat == '' ? saatSecildi = false : saatSecildi = true;
            String tRtarih = format.format(DateTime.parse(dbSaat));
            gosterilenSaat = tRtarih;
            dbSaat.log();
            gosterilenSaat.log();
          });
        },
      );

  void updateButton() {
    if (!yetkiliListesiBosMu) {
      if (gonderilenCalisanID.isNotEmpty &&
          gonderilenYetkiliID.isNotEmpty &&
          dbSaat.isNotEmpty &&
          context.read<CustomersCubit>().secilenGorusmeTipi.isNotEmpty &&
          tfAciklama.text.isNotEmpty) {
        context
            .read<ActivityCubit>()
            .aktiviteGuncelle(
                widget.gorusmeID,
                tcAktiviteBaslik.text,
                gonderilenYetkiliID,
                ',$gonderilenCalisanID,',
                dbSaat,
                context.read<CustomersCubit>().secilenGorusmeTipi,
                tfAciklama.text,
                context.read<LoginCubit>().id,
                context.read<LoginCubit>().token,
                context.read<LoginCubit>().tip,
                context.read<LoginCubit>().userfirmId)
            .then(resultValue);
      }
    } else {}
  }

  Future<void> resultValue(bool value) async {
    if (!value) {
      return ToastManager.instance
          .toastMessageService('Aktivite Güncellenemedi')
          .then(
              (value) => Future.delayed(const Duration(milliseconds: 800), () {
                    Navigator.popUntil(context, (route) => route.isFirst);
                  }));
    }
    ToastManager.instance
        .toastMessageService('Aktivite Güncellendi')
        .then((value) => Future.delayed(const Duration(milliseconds: 800), () {
              Navigator.popUntil(context, (route) => route.isFirst);
            }));
  }

  void _showSnackBarAction(String msg, void Function()? actionOnPressed) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        backgroundColor: ColorsConstants.instance.baseTheme,
        content: Text(msg),
        action: SnackBarAction(
          label: "Evet",
          textColor: Colors.white,
          onPressed: _activityArchive,
        ),
      ),
    );
  }

  void _activityArchive() {
    context.read<ActivityCubit>().aktiviteArsivle(
        widget.gorusmeID,
        context.read<LoginCubit>().id,
        context.read<LoginCubit>().token,
        context.read<LoginCubit>().tip,
        context.read<LoginCubit>().userfirmId);
    Future.delayed(const Duration(milliseconds: 800), () {
      Navigator.pop(context);
    });
  }

  void _activityUnArchive() {
    context.read<ActivityCubit>().aktiviteArsivdenCikar(
        widget.gorusmeID,
        context.read<LoginCubit>().id,
        context.read<LoginCubit>().token,
        context.read<LoginCubit>().tip,
        context.read<LoginCubit>().userfirmId);
    Future.delayed(const Duration(milliseconds: 800), () {
      Navigator.pop(context);
    });
  }
}
