import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/core/route/page_route.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/activity_state.dart';
import 'package:hamlemuhcrm/features/customers/tab_bar/mixin/activity_tab_bar_mixin.dart';
import 'package:hamlemuhcrm/features/customers/view/activities/activity_update.dart';
import 'package:hamlemuhcrm/features/customers/view/activities/mixin/shared_activity_mixin.dart';
import 'package:hamlemuhcrm/features/customers/widgets/shimmer_container.dart';

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

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

  @override
  State<ActivityTabBar> createState() => _ActivityTabBarState();
}

class _ActivityTabBarState extends State<ActivityTabBar>
    with ActivityTabBarMixin, SharedActivityMixin {
  @override
  Widget build(BuildContext context) {
    return Scaffold(body: _activityBloc(context));
  }

  Widget _activityBloc(BuildContext context) {
    return BlocBuilder<ActivityCubit, ActivityState>(
      builder: (context, state) {
        if (state.isLoading && !state.isComplete) {
          return _shimmerList;
        } else if (state.isError && !state.isComplete) {
          return const Center(
            child: Text('Hata Oluştu'),
          );
        } else if (state.aktiviteler.isEmpty) {
          return Center(
            child: Text(
              'Aktivite Yok',
              style: Theme.of(context).textTheme.titleMedium,
            ),
          );
        } else {
          return _activityList(state);
        }
      },
    );
  }

  Widget get _shimmerList => ListView.builder(
        itemCount: 5,
        itemBuilder: (context, index) => ShimmerContainer(
          color: Colors.grey,
          opacity: 0.3,
          height: context.dynamicHeight(0.092),
          width: context.dynamicWidth(0.92),
        ),
      );

  Widget _activityList(ActivityState state) {
    return ListView.builder(
      itemCount: state.aktiviteler.length,
      physics: const PageScrollPhysics(),
      itemBuilder: (context, index) {
        bool arsiv;
        arsiv = state.aktiviteler[index].gorusmeOnay == '0';
        ///////////////////////////////////////////////////////////////
        String tarih = state.aktiviteler[index].gorusmeTarihi!;
        final DateFormat format = DateFormat.yMd('tr');
        var trTarih = format.format(DateTime.parse(tarih));
        ///////////////////////////////////////////////////////////////
        String id = "";
        state.aktiviteler[index].gorusmeUserIdler! == ',' ||
                state.aktiviteler[index].gorusmeUserIdler! == ',,'
            ? id = ',14,'
            : id = state.aktiviteler[index].gorusmeUserIdler!;
        List<String> ilksayiyiAl = id.substring(1).split(',');
        String atanacakSayi = ilksayiyiAl[0];
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 8),
          child: InkWell(
              onTap: () {
                Navigator.push(
                    context,
                    CustomPageRoute(
                        child: ActivityUpdate(
                      gorusmeID: state.aktiviteler[index].gorusmeId!,
                      firmaAd: state.aktiviteler[index].firmaIsim!,
                      firmaID: state.aktiviteler[index].gorusmeFirmaId!,
                      gorusmeBaslik: state.aktiviteler[index].gorusmeBaslik!,
                      yetkiliID: state.aktiviteler[index].gorusmeYetkiliId!,
                      katilanPersonelID: atanacakSayi,
                      tarih: state.aktiviteler[index].gorusmeTarihi!,
                      gorusmeTuru: state.aktiviteler[index].gorusmeTip!,
                      aciklama: state.aktiviteler[index].gorusmeNot!,
                      arsivMi: arsiv,
                    )));
              },
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 14),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5),
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                          color: Colors.grey.withOpacity(0.5),
                          offset: const Offset(0.4, 0.5),
                          blurRadius: 7)
                    ]),
                child: Row(
                  children: [
                    Container(
                      width: 10,
                      height: context.dynamicHeight(0.092),
                      decoration: BoxDecoration(
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(5),
                            bottomLeft: Radius.circular(5)),
                        color: arsiv
                            ? Colors.red.withOpacity(0.2)
                            : Colors.blue.withOpacity(0.2),
                      ),
                    ),
                    SizedBox(
                      width: context.dynamicWidth(0.03),
                    ),
                    const Icon(Icons.task_alt_outlined),
                    SizedBox(
                      width: context.dynamicWidth(0.03),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                            state.aktiviteler[index].gorusmeBaslik! == ''
                                ? 'baslik yok'
                                : state.aktiviteler[index].gorusmeBaslik!,
                            style: const TextStyle(
                                fontWeight: FontWeight.w600, fontSize: 13)),
                        const SizedBox(height: 2),
                        Row(
                          children: [
                            const Icon(Icons.calendar_month,
                                size: 14, color: Colors.grey),
                            SizedBox(
                              width: context.dynamicWidth(0.008),
                            ),
                            Text(
                              trTarih,
                              style: const TextStyle(fontSize: 12),
                            ),
                            const Text(
                              ' | ',
                              style: TextStyle(color: Colors.grey),
                            ),
                            SizedBox(
                              width: context.dynamicWidth(0.008),
                            ),
                            const Icon(Icons.business_rounded,
                                size: 14, color: Colors.grey),
                            SizedBox(
                              width: context.dynamicWidth(0.008),
                            ),
                            Text(
                              state.aktiviteler[index].firmaIsim
                                          .toString()
                                          .length >
                                      20
                                  ? ' ${state.aktiviteler[index].firmaIsim.toString().substring(0, 19)}..'
                                  : ' ${state.aktiviteler[index].firmaIsim.toString()}',
                              style: const TextStyle(fontSize: 11),
                            ),
                          ],
                        ),
                      ],
                    ),
                    const Spacer(),
                    arsiv
                        ? Container(
                            height: 35,
                            width: 35,
                            decoration: BoxDecoration(
                                color: Colors.red.withOpacity(0.2),
                                borderRadius: BorderRadius.circular(10)),
                            child: IconButton(
                              tooltip: 'Arşivden Çıkar',
                              onPressed: () {
                                ScaffoldMessenger.of(context).showSnackBar(
                                    unArchiveSnackBar(
                                        state.aktiviteler[index].gorusmeId!));
                              },
                              icon: const Icon(Icons.send_and_archive,
                                  color: Colors.red, size: 17),
                            ))
                        : Container(
                            height: 35,
                            width: 35,
                            decoration: BoxDecoration(
                                color: Colors.blue.withOpacity(0.2),
                                borderRadius: BorderRadius.circular(10)),
                            child: Icon(Icons.arrow_forward_ios_sharp,
                                color: Colors.blue.withOpacity(0.5), size: 17),
                          ),
                    const SizedBox(width: 15),
                  ],
                ),
              )),
        );
      },
    );
  }

  SnackBar unArchiveSnackBar(String gorusmeId) => SnackBar(
        backgroundColor: ColorsConstants.instance.baseTheme,
        behavior: SnackBarBehavior.floating,
        content: const Text(
          "Arşivden Çıkarılsın Mı?",
        ),
        action: SnackBarAction(
          label: "Evet",
          textColor: Colors.white,
          onPressed: () {
            context.read<ActivityCubit>().aktiviteArsivdenCikar(
                gorusmeId,
                context.read<LoginCubit>().id,
                context.read<LoginCubit>().token,
                context.read<LoginCubit>().tip,
                context.read<LoginCubit>().userfirmId);
            Future.delayed(const Duration(seconds: 1), () {
              context.read<ActivityCubit>().kisiAktiviteleriListele(
                  context.read<LoginCubit>().id,
                  context.read<LoginCubit>().token,
                  context.read<LoginCubit>().tip,
                  context.read<LoginCubit>().userfirmId,
                  2);
            });
          },
        ),
      );
}
