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/constants/font_styles.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/activity_cubit.dart';
import 'package:hamlemuhcrm/features/customers/cubit/customers_cubit.dart';
import 'package:hamlemuhcrm/features/customers/tab_bar/all_activity_tab_bar.dart';
import 'package:hamlemuhcrm/features/customers/tab_bar/companys_tab_bar.dart';
import 'package:hamlemuhcrm/features/customers/tab_bar/custom_customers_tab_bar.dart';
import 'package:hamlemuhcrm/features/customers/view/activities/mixin/shared_activity_mixin.dart';
import 'package:hamlemuhcrm/features/customers/view/customers_page_view_mixin.dart';
import 'package:hamlemuhcrm/features/customers/widgets/navigate_width_button.dart';
import 'package:hamlemuhcrm/features/customers/widgets/order_buttons.dart';

import '../../../../core/constants/color_constants.dart';
import '../../../core/utility/toast_manager.dart';
import '../resources/search_tf_input_decoration.dart';

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

  @override
  State<CustomersPageView> createState() => _CustomersPageViewState();
}

class _CustomersPageViewState extends State<CustomersPageView>
    with CustomerPageMixin, SharedActivityMixin, TickerProviderStateMixin {
  @override
  void initState() {
    isFinish = false;
    tabController2 = TabController(length: 2, vsync: this);
    tabController2.addListener(onTabChange);
    firmaButonumu = true;
    isFinish = true;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return isFinish
        ? Scaffold(
            resizeToAvoidBottomInset: false,
            body: Column(
              children: [
                Container(
                  margin: EdgeInsets.symmetric(
                      horizontal: context.dynamicWidth(0.04)),
                  padding: EdgeInsets.symmetric(
                      horizontal: context.dynamicWidth(0.045)),
                  height: context.dynamicHeight(0.2780),
                  decoration: BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.3),
                        offset: const Offset(1, 3),
                        blurRadius: 5,
                      )
                    ],
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      CustomCustomerTabBar(
                          tabController: tabController2,
                          tabs: [
                            _tabBarContainer(
                                context,
                                "Firmalar",
                                Icons.business_sharp,
                                ColorsConstants.instance.baseTheme),
                            _tabBarContainer(context, "Aktiviteler",
                                Icons.stacked_line_chart_rounded, Colors.blue)
                          ],
                          onPressed: changeTabBar),
                      Form(
                          key: CustomerPageMixin.searchKey,
                          child: _searchContainer),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            flex: 1,
                            child: Material(
                              color: Colors.transparent,
                              child: InkWell(
                                onTap: tabController2.index == 0
                                    ? handleButtonCompany
                                    : handleButtonActivity,
                                splashColor: Colors.grey.shade200,
                                borderRadius: BorderRadius.circular(15),
                                child: const NavigateWidthButton(
                                  yazi: 'Arşiv',
                                  icon: Icons.archive_outlined,
                                  iconrenk: Colors.red,
                                  kenarlik: true,
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(width: 15),
                          Expanded(
                            flex: 1,
                            child: Material(
                              color: Colors.transparent,
                              child: InkWell(
                                onTap: tabController2.index == 0
                                    ? () {
                                        navigateToCreateCompany();
                                      }
                                    : () {
                                        navigateToCreateActivity();
                                      },
                                splashColor: Colors.grey.shade200,
                                borderRadius: BorderRadius.circular(15),
                                child: NavigateWidthButton(
                                  yazi: tabController2.index == 0
                                      ? 'Firma Oluştur'
                                      : 'Aktivite Oluştur',
                                  icon: tabController2.index == 0
                                      ? Icons.add_business_rounded
                                      : Icons.add_chart_rounded,
                                  iconrenk: tabController2.index == 0
                                      ? Colors.green
                                      : Colors.blue,
                                  kenarlik: true,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                aramaYapiliyor ? const SizedBox() : const SizedBox(height: 10),
                aramaYapiliyor
                    ? const SizedBox()
                    : Container(
                        margin: EdgeInsets.symmetric(
                            horizontal: context.dynamicWidth(0.04)),
                        padding: EdgeInsets.symmetric(
                            horizontal: context.dynamicWidth(0.050),
                            vertical: 1),
                        height: context.dynamicHeight(0.1),
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.grey.withOpacity(0.3),
                              offset: const Offset(1, 3),
                              blurRadius: 5,
                            )
                          ],
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(15),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            Row(
                              children: [
                                Expanded(
                                  flex: 1,
                                  child: Material(
                                    color: Colors.transparent,
                                    child: InkWell(
                                      onTap: tabController2.index == 0
                                          ? () {
                                              firmArsivMi
                                                  ? null
                                                  : context
                                                      .read<CustomersCubit>()
                                                      .kisifirmalariListele(
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .tip,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .token,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .id,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .userfirmId,
                                                          2); //.tumfirmalariListele(2);
                                            }
                                          : () {
                                              setState(() {
                                                tariheGoreSirala = false;
                                              });
                                              aktiviteArsivMi
                                                  ? null
                                                  : context
                                                      .read<ActivityCubit>()
                                                      .kisiAktiviteleriListele(
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .id,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .token,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .tip,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .userfirmId,
                                                          1); //adminAktiviteleriListele(1)
                                            },
                                      splashColor:
                                          Colors.black.withOpacity(0.5),
                                      borderRadius: BorderRadius.circular(10),
                                      child: OrderWidthButton(
                                        yazi: tabController2.index == 0
                                            ? 'Firma Adı (A-Z)'
                                            : 'Başlık (A-Z)',
                                        kenarlik: true,
                                      ),
                                    ),
                                  ),
                                ),
                                _emptyWidthSpace,
                                Expanded(
                                  flex: 1,
                                  child: Material(
                                    color: Colors.transparent,
                                    child: InkWell(
                                      onTap: tabController2.index == 0
                                          ? () {
                                              firmArsivMi
                                                  ? null
                                                  : context
                                                      .read<CustomersCubit>()
                                                      .kisifirmalariListele(
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .tip,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .token,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .id,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .userfirmId,
                                                          3); //tumfirmalariListele(3)
                                            }
                                          : () {
                                              setState(() {
                                                tariheGoreSirala = false;
                                              });
                                              aktiviteArsivMi
                                                  ? null
                                                  : context
                                                      .read<ActivityCubit>()
                                                      .kisiAktiviteleriListele(
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .id,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .token,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .tip,
                                                          context
                                                              .read<
                                                                  LoginCubit>()
                                                              .userfirmId,
                                                          2); //context.read<ActivityCubit>().adminAktiviteleriListele(2);
                                            },
                                      splashColor:
                                          Colors.black.withOpacity(0.5),
                                      borderRadius: BorderRadius.circular(10),
                                      child: OrderWidthButton(
                                        yazi: tabController2.index == 0
                                            ? 'Eklenme Tarihi'
                                            : 'Firma (A-Z)',
                                        kenarlik: true,
                                      ),
                                    ),
                                  ),
                                ),
                                _emptyWidthSpace,
                                Expanded(
                                  flex: 1,
                                  child: Material(
                                    color: Colors.transparent,
                                    child: InkWell(
                                      onTap: tabController2.index == 0
                                          ? () {}
                                          : () {
                                              setState(() {
                                                tariheGoreSirala =
                                                    !tariheGoreSirala;
                                                dbSaatbaslangic != ''
                                                    ? dbSaatbaslangic = ''
                                                    : null;
                                                gosterilenSaatbaslangic != ''
                                                    ? gosterilenSaatbaslangic =
                                                        ''
                                                    : null;
                                                dbSaatbitis != ''
                                                    ? dbSaatbitis = ''
                                                    : null;
                                                gosterilenSaatbitis != ''
                                                    ? gosterilenSaatbitis = ''
                                                    : null;
                                              });
                                            },
                                      splashColor:
                                          Colors.black.withOpacity(0.5),
                                      borderRadius: BorderRadius.circular(10),
                                      child: const OrderWidthButton(
                                        yazi: 'Tarih',
                                        kenarlik: true,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                SizedBox(height: context.dynamicHeight(0.02)),
                tariheGoreSirala
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Column(
                            children: [
                              const Text('Başlangıç Tarihi'),
                              SizedBox(height: context.dynamicHeight(0.012)),
                              Container(
                                  height: context.dynamicHeight(0.055),
                                  width: context.dynamicWidth(0.32),
                                  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(
                                        gosterilenSaatbaslangic,
                                        style: FontStyles.instance.ddYazi,
                                      ),
                                      const Spacer(),
                                      IconButton(
                                          padding: EdgeInsets.zero,
                                          onPressed: () {
                                            dateTimePickerWidget1(context);
                                          },
                                          tooltip: 'Tarih Seç',
                                          icon: Icon(
                                            Icons.keyboard_arrow_down_outlined,
                                            size: 23,
                                            color: Colors.blue.withOpacity(0.7),
                                          )),
                                    ],
                                  )),
                            ],
                          ),
                          SizedBox(width: context.dynamicWidth(0.06)),
                          Column(
                            children: [
                              const Text('Bitiş Tarihi'),
                              SizedBox(height: context.dynamicHeight(0.012)),
                              Container(
                                height: context.dynamicHeight(0.055),
                                width: context.dynamicWidth(0.32),
                                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(
                                      gosterilenSaatbitis,
                                      style: FontStyles.instance.ddYazi,
                                    ),
                                    const Spacer(),
                                    baslangicSecildi
                                        ? IconButton(
                                            onPressed: () {
                                              dateTimePickerWidget2(context);
                                            },
                                            tooltip: 'Bitiş Tarihi Seç',
                                            icon: Icon(
                                              Icons
                                                  .keyboard_arrow_down_outlined,
                                              size: 23,
                                              color:
                                                  Colors.blue.withOpacity(0.7),
                                            ))
                                        : IconButton(
                                            onPressed: () {
                                              ToastManager.instance
                                                  .toastMessageService(
                                                      'Başlangıç tarihini seçin..');
                                            },
                                            tooltip: 'Bitiş Tarihi Seç',
                                            icon: Icon(
                                              Icons
                                                  .keyboard_arrow_down_outlined,
                                              size: 23,
                                              color:
                                                  Colors.blue.withOpacity(0.7),
                                            ))
                                  ],
                                ),
                              ),
                            ],
                          ),
                          SizedBox(width: context.dynamicWidth(0.06)),
                          Column(
                            children: [
                              const Text('Sıfırla'),
                              SizedBox(height: context.dynamicHeight(0.012)),
                              Container(
                                  height: context.dynamicHeight(0.055),
                                  width: context.dynamicWidth(0.1),
                                  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: IconButton(
                                      onPressed: () {
                                        setState(() {
                                          baslangicSecildi = false;
                                          gosterilenSaatbaslangic = '';
                                          gosterilenSaatbitis = '';
                                          context
                                              .read<ActivityCubit>()
                                              .kisiAktiviteleriListele(
                                                  context.read<LoginCubit>().id,
                                                  context
                                                      .read<LoginCubit>()
                                                      .token,
                                                  context
                                                      .read<LoginCubit>()
                                                      .tip,
                                                  context
                                                      .read<LoginCubit>()
                                                      .userfirmId,
                                                  2); //bura
                                          tariheGoreSirala = false;
                                        });
                                      },
                                      icon: Icon(
                                        Icons.delete_forever_rounded,
                                        size: 20,
                                        color: Colors.blue.withOpacity(0.7),
                                      ))),
                            ],
                          ),
                        ],
                      )
                    : const SizedBox(),
                tariheGoreSirala
                    ? SizedBox(height: context.dynamicHeight(0.02))
                    : const SizedBox(),
                Expanded(
                  flex: 4,
                  child: TabBarView(
                    controller: tabController2,
                    children: const [
                      CompanysTabBar(),
                      ActivityTabBar(),
                    ],
                  ),
                )
              ],
            ),
          )
        : const Scaffold();
  }

  Widget get _searchContainer => Container(
        height: context.dynamicHeight(0.0564),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: ColorsConstants.instance.backgroundColor,
            border: Border.all(color: Colors.grey.withOpacity(0.3))),
        child: TextFormField(
          magnifierConfiguration: TextMagnifierConfiguration.disabled,
          controller: firmaButonumu ? tcfirmaAra : tcaktiviteAra,
          textInputAction: TextInputAction.search,
          onTap: tabController2.index == 0
              ? () {
                  setState(() {
                    aramaYapiliyor = true;
                  });
                }
              : () {
                  setState(() {
                    tariheGoreSirala = false;
                    aramaYapiliyor = true;
                  });
                },
          onChanged: tabController2.index == 0
              ? (aramasonucu) {
                  context.read<CustomersCubit>().ara(
                        aramasonucu,
                      );
                }
              : (aramasonucu) {
                  context.read<ActivityCubit>().tumAktiviteleriAra(aramasonucu);
                },
          onTapOutside: (event) => {
            aramaYapiliyor = false,
            if (tabController2.index == 0)
              {
                tcfirmaAra.text == '' ? null : tcfirmaAra.clear(),
              }
            else if (tabController2.index == 1)
              {
                tcaktiviteAra.text == '' ? null : tcaktiviteAra.clear(),
              }
          },
          textAlign: TextAlign.left,
          style: const TextStyle(color: Colors.grey, fontSize: 16.0),
          decoration: SearchTfInputDecoration(context),
        ),
      );

  @override
  void onTabChange() {
    debugPrint('kaydırmalı indeks : ${tabController2.index}');
    setState(() {
      if (tabController2.index == 0) {
        context.read<CustomersCubit>().firmaMi = true;
        context.read<CustomersCubit>().kisifirmalariListele(
            context.read<LoginCubit>().tip,
            context.read<LoginCubit>().token,
            context.read<LoginCubit>().id,
            context.read<LoginCubit>().userfirmId,
            2); //tumfirmalariListele(2);
        tariheGoreSirala = false;
      } else if (tabController2.index == 1) {
        context.read<CustomersCubit>().firmaMi = false;
        context.read<ActivityCubit>().kisiAktiviteleriListele(
            context.read<LoginCubit>().id,
            context.read<LoginCubit>().token,
            context.read<LoginCubit>().tip,
            context.read<LoginCubit>().userfirmId,
            2); //adminAktiviteleriListele(3);
      }
    });
  }

  Widget _tabBarContainer(
      BuildContext context, String title, IconData icon, Color iconRenk) {
    return Tab(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Icon(
            icon,
            color: iconRenk,
          ),
          const SizedBox(width: 14),
          Text(title, style: FontStyles.instance.buyukYazi),
        ],
      ),
    );
  }

  Widget get _emptyWidthSpace => SizedBox(width: context.dynamicWidth(0.05));

  @override
  void handleButtonCompany() {
    if (!isProcessing) {
      isProcessing = true;
      firmArsivMi = !firmArsivMi;
      if (firmArsivMi == true) {
        context.read<CustomersCubit>().kisiArsivFirmalar(
            context.read<LoginCubit>().tip,
            context.read<LoginCubit>().token,
            context.read<LoginCubit>().id,
            context.read<LoginCubit>().userfirmId);
      }
      if (firmArsivMi == false) {
        context.read<CustomersCubit>().kisifirmalariListele(
            context.read<LoginCubit>().tip,
            context.read<LoginCubit>().token,
            context.read<LoginCubit>().id,
            context.read<LoginCubit>().userfirmId,
            2);
      }
      isProcessing = false;
    }
  }

  @override
  void handleButtonActivity() {
    'isPrcessing : $isProcessing'.log();
    'aktivite arsiv butonu tıklandı'.log();
    'firma arsiv mi : $firmArsivMi ---- aktivite arsiv mi : $aktiviteArsivMi'
        .log();
    if (!isProcessing) {
      tariheGoreSirala = false;
      isProcessing = true;
      aktiviteArsivMi = !aktiviteArsivMi;
      if (aktiviteArsivMi == true) {
        context.read<ActivityCubit>().kisiArsivAktiviteleriListele(
              context.read<LoginCubit>().id,
              context.read<LoginCubit>().token,
              context.read<LoginCubit>().tip,
              context.read<LoginCubit>().userfirmId,
            );
      }
      if (aktiviteArsivMi == false) {
        context.read<ActivityCubit>().kisiAktiviteleriListele(
            context.read<LoginCubit>().id,
            context.read<LoginCubit>().token,
            context.read<LoginCubit>().tip,
            context.read<LoginCubit>().userfirmId,
            2);
      }
      isProcessing = false;
    }
  }

  void dateTimePickerWidget1(BuildContext context) {
    return 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: Text(
          'Onay',
          style: TextStyle(color: Colors.blue.withOpacity(0.7)),
        ),
      ),
      onConfirm: (dateTime, List<int> index) {
        DateTime selectdate1 = dateTime;
        birincidateTime = selectdate1;
        final baslangicTarihi =
            DateFormat('yyyy-MM-dd HH:mm').format(selectdate1);
        setState(() {
          dbSaatbaslangic = '$baslangicTarihi:00';
          gosterilenSaatbaslangic = dbSaatbaslangic.substring(0, 16);
          final DateFormat format = DateFormat.yMd('tr');
          var trTarih = format.format(DateTime.parse(gosterilenSaatbaslangic));
          gosterilenSaatbaslangic = trTarih;
          'birinci tarih ikinci tarihten önce ? ${ikincidateTime.isAfter(birincidateTime)}'
              .log();
          'birinci dateTimeNow $birincidateTime'.log();
          'ikinci dateTimeNow $ikincidateTime'.log();
          if (dbSaatbaslangic != '' && dbSaatbitis != '') {
            context.read<ActivityCubit>().tariheGoreAktiviteListele(
                dbSaatbaslangic,
                dbSaatbitis,
                context.read<LoginCubit>().userfirmId,
                context.read<LoginCubit>().id,
                context.read<LoginCubit>().tip,
                context.read<LoginCubit>().token);
            dbSaatbaslangic.log();
            dbSaatbitis.log();
          }
          baslangicSecildi = true;
          dbSaatbaslangic.log();
          gosterilenSaatbaslangic.log();
        });
      },
    );
  }

  void dateTimePickerWidget2(BuildContext context) {
    return DatePicker.showDatePicker(
      context,
      dateFormat: 'dd/MM/yyyy',
      locale: DateTimePickerLocale.tr,
      minDateTime: DateTime(2005),
      maxDateTime: DateTime(2100),
      pickerTheme: DateTimePickerTheme(
        backgroundColor: ColorsConstants.instance.backgroundColor,
        confirm: Text(
          'Onay',
          style: TextStyle(color: Colors.blue.withOpacity(0.7)),
        ),
      ),
      onConfirm: (dateTime, List<int> index) {
        DateTime selectdate2 = dateTime;
        ikincidateTime = selectdate2;
        final bitisTarihi = DateFormat('yyyy-MM-dd HH:mm').format(selectdate2);
        setState(() {
          dbSaatbitis = '$bitisTarihi:00';
          gosterilenSaatbitis = dbSaatbitis.substring(0, 16);
          final DateFormat format = DateFormat.yMd('tr');
          var trTarih = format.format(DateTime.parse(gosterilenSaatbitis));
          gosterilenSaatbitis = trTarih;
          'ikinci tarih birinci tarihten sonra mı ? ${ikincidateTime.isAfter(birincidateTime)}'
              .log();
          if (ikincidateTime.isAfter(birincidateTime) == false) {
            gosterilenSaatbitis = '';
            ToastManager.instance
                .toastMessageService('Geçerli bir tarih seçin..');
          }
          if (dbSaatbaslangic != '' &&
              dbSaatbitis != '' &&
              ikincidateTime.isAfter(birincidateTime)) {
            context.read<ActivityCubit>().tariheGoreAktiviteListele(
                dbSaatbaslangic,
                dbSaatbitis,
                context.read<LoginCubit>().userfirmId,
                context.read<LoginCubit>().id,
                context.read<LoginCubit>().tip,
                context.read<LoginCubit>().token);
            dbSaatbaslangic.log();
            dbSaatbitis.log();
          }
        });
      },
    );
  }
}
