import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/route/page_route.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/calendar/view/add_meet_one_view.dart';
import 'package:hamlemuhcrm/features/calendar/view/calendar_detail_one_view.dart';

import '../../../core/constants/color_constants.dart';
import '../../../core/cubits/dropdown_cubit.dart';
import '../../../core/extensions/responsive_extension.dart';
import '../constants/meet_constants.dart';
import '../cubit/calendar_cubit.dart';
import '../cubit/calendar_state.dart';
import '../model/calendar_model.dart';
import '../widgets/custom_table_calendar_widget.dart';
import '../widgets/filter_meeting_chip.dart';
import '../widgets/meet_card_item.dart';

final class CalendarView extends StatefulWidget {
  const CalendarView({super.key});
  @override
  State<CalendarView> createState() => _CalendarViewState();
}

class _CalendarViewState extends State<CalendarView> {
  //sayfa index 5
  late final DropdownCubit dropdownCubit;
  @override
  void initState() {
    dropdownCubit = DropdownCubit();
    context.read<CalendarCubit>().fetchMeets(
        context.read<LoginCubit>().token, context.read<LoginCubit>().id);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: SizedBox(
          height: context.dynamicHeight(1),
          child: Padding(
            padding:
                EdgeInsets.symmetric(horizontal: context.dynamicWidth(0.05)),
            child: Column(
              children: [
                //const GestureCalendarWidget(),
                const CustomTableCalendar(),
                _emptySpace(context),
                _pageHeader,
                _emptySpace(context),
                _meetingList(context),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget get _pageHeader => Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [const FilterMeetingChip(), onTapAddMeetButton],
      );

  Widget get onTapAddMeetButton =>
      Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        InkWell(
          onTap: () {
            // önce ddler için servislerden datalar getirilsin sonra sayfa açılsın
            context.read<DropdownCubit>().fetchProjectsData(
                context.read<LoginCubit>().userfirmId,
                context.read<LoginCubit>().token,
                context.read<LoginCubit>().id);
            context
                .read<DropdownCubit>()
                .fetchCalisanData(
                    context.read<LoginCubit>().userfirmId,
                    context.read<LoginCubit>().token,
                    context.read<LoginCubit>().id)
                .whenComplete(() => Navigator.push(
                    context, CustomPageRoute(child: const AddMeetOneView())));
          },
          child: addMeetButon,
        ),
      ]);

  Widget _navigateButtonTheme(Widget child) => Container(
      decoration: ShapeDecoration(
        color: ColorsConstants.instance.baseTheme,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
      ),
      child: child);

  Widget get addMeetButon => _navigateButtonTheme(
        Center(
          heightFactor: 2,
          widthFactor: 1.2,
          child: Text(MeetConstants.instance.navigateAddMeetButtonTxt,
              style: Theme.of(context)
                  .textTheme
                  .bodySmall
                  ?.copyWith(color: Colors.white, fontWeight: FontWeight.w600)),
        ),
      );

  Widget _meetingList(BuildContext context) {
    return Expanded(
      child: BlocBuilder<CalendarCubit, CalendarState>(
        builder: (context, state) {
          if (state.status == CalendarStatus.initial) {
            return const Center(
              child: Text('Bir Tarih Seçin'),
            );
          } else if (state.status == CalendarStatus.loading) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          } else if (state.status == CalendarStatus.error) {
            return Center(
              child: Text(state.errorMessage),
            );
          } else if (state.toplantiList.isEmpty &&
              state.secilenGun.isNotEmpty) {
            return Center(
              child: Text(
                'Toplantı Bulunamadı',
                style: Theme.of(context).textTheme.titleMedium,
              ),
            );
          } else {
            final toplantiList = state.toplantiList;
            return _meetingListViewSeperated(toplantiList);
          }
        },
      ),
    );
  }

  Widget _meetingListViewSeperated(List<CalendarModel> toplantiListesi) {
    return ListView.separated(
      separatorBuilder: (context, index) {
        return const Divider(
          height: kRadialReactionRadius,
          color: Colors.red,
        );
      },
      itemCount: toplantiListesi.length,
      itemBuilder: (context, index) {
        final toplantiList = toplantiListesi[index];
        return MeetCardItem(
          toplantiListesi: toplantiList,
          onMeetUpdate: () {
            //toplantıya girerken bu toplantının görüldüğünü haber ver
            context.read<CalendarCubit>().viewUpdateMeet(
                context.read<LoginCubit>().token,
                context.read<LoginCubit>().id,
                toplantiList.toplantiId ?? '');
            _navigateToUpdateMeet(toplantiList);
          },
        );
      },
    );
  }

  void _navigateToUpdateMeet(CalendarModel calendarModel) {
    context.read<DropdownCubit>().fetchCalisanData(
        context.read<LoginCubit>().userfirmId,
        context.read<LoginCubit>().token,
        context.read<LoginCubit>().id);
    context.read<DropdownCubit>().fetchYetkiliData(
        calendarModel.toplantiFirmaId ?? '',
        context.read<LoginCubit>().token,
        context.read<LoginCubit>().id);
    context
        .read<DropdownCubit>()
        .fetchProjectsData(calendarModel.toplantiUserfirmId ?? "",
            context.read<LoginCubit>().token, context.read<LoginCubit>().id)
        .whenComplete(() => Navigator.push(
            context,
            CustomPageRoute(
                child: CalendarDetailOneView(
                    calendarModel: calendarModel, cubit: dropdownCubit))));
  }

  Widget _emptySpace(BuildContext context) {
    return SizedBox(
      height: context.dynamicHeight(0.02),
    );
  }
}
