import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/data/models/event/event_model.dart';
import 'package:krow/core/data/models/event/skill.dart';
import 'package:krow/core/data/models/shift/business_skill_model.dart';
import 'package:krow/core/data/models/shift/department_model.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_box_decorations.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/kw_time_slot.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_dropdown.dart';
import 'package:krow/features/create_event/domain/bloc/create_event_bloc.dart';
import 'package:krow/features/create_event/presentation/create_role_section/bloc/create_role_bloc.dart';
import 'package:krow/features/create_event/presentation/create_shift_details_section/bloc/create_shift_details_bloc.dart';
import 'package:krow/features/create_event/presentation/role_schedule_dialog/recurring_schedule_widget.dart';

class CreateRoleDetailsWidget extends StatefulWidget {
  final String id;

  const CreateRoleDetailsWidget({
    super.key,
    required this.id,
  });

  @override
  State<CreateRoleDetailsWidget> createState() =>
      _CreateRoleDetailsWidgetState();
}

class _CreateRoleDetailsWidgetState extends State<CreateRoleDetailsWidget> {
  ExpandableController? _expandableController;

  @override
  void initState() {
    super.initState();
    _expandableController = ExpandableController(initialExpanded: true);
  }

  @override
  void dispose() {
    super.dispose();
    _expandableController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CreateEventBloc, CreateEventState>(
      builder: (context, eventState) {
        return BlocBuilder<CreateShiftDetailsBloc, CreateShiftDetailsState>(
          builder: (context, shiftState) {
            return BlocConsumer<CreateRoleBloc, CreateRoleState>(
              listener: (context, state) {
                if (state.isExpanded != _expandableController?.expanded) {
                  _expandableController!.toggle();
                }
              },
              builder: (context, state) {
                return AnimatedContainer(
                  duration: const Duration(milliseconds: 250),
                  width: double.infinity,
                  margin: const EdgeInsets.only(top: 12),
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  decoration: KwBoxDecorations.primaryLight8.copyWith(
                      border: state.validationState != null
                          ? Border.all(color: AppColors.statusError, width: 1)
                          : null),
                  child: ExpandableTheme(
                    data: const ExpandableThemeData(
                        hasIcon: false,
                        animationDuration: Duration(milliseconds: 250)),
                    child: ExpandablePanel(
                      collapsed: Container(),
                      controller: _expandableController,
                      header: _buildHeader(state, shiftState, context),
                      expanded: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          _skillDropDown(state.entity.businessSkill,
                              eventState.skills, context),
                          const Gap(8),
                          _departmentDropDown(state.entity.department,
                              eventState.departments, context),
                          const Gap(8),
                          _timeRow(context, state.entity.startTime,
                              state.entity.endTime),
                          const Gap(8),
                          _countDropDown(state.entity.count, context),
                          const Gap(8),
                          _breakDropDown(context, state),
                          if (eventState.recurringType ==
                              EventScheduleType.recurring)
                            const RecurringScheduleWidget(),
                          const Gap(12),
                          textRow('Cost',
                              '\$${state.entity.businessSkill?.price?.toStringAsFixed(2) ?? '0'}'),
                          const Gap(12),
                          textRow('Value', '\$${state.entity.price.toStringAsFixed(2)}'),
                          const Gap(12),
                          KwButton.accent(
                              label: 'Save Role',
                              onPressed: () {
                                context
                                    .read<CreateRoleBloc>()
                                    .add(ExpandRoleEvent());
                              }),
                          const Gap(12),
                        ],
                      ),
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    );
  }

  Widget _buildHeader(CreateRoleState state, CreateShiftDetailsState shiftState,
      BuildContext context) {
    return GestureDetector(
      onTap: () {
        context.read<CreateRoleBloc>().add(ExpandRoleEvent());
      },
      child: Container(
        color: Colors.transparent,
        padding: const EdgeInsets.only(bottom: 12, top: 12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              state.entity.businessSkill?.skill?.name ?? 'New Role',
              style: AppTextStyles.bodyLargeMed,
            ),
            if (!state.isExpanded)
              Center(
                child: Assets.images.icons.chevronDown.svg(
                  height: 24,
                  width: 24,
                  colorFilter: const ColorFilter.mode(
                    AppColors.grayStroke,
                    BlendMode.srcIn,
                  ),
                ),
              ),
            if (state.isExpanded && shiftState.roles.length > 1)
              GestureDetector(
                onTap: () {
                  context
                      .read<CreateShiftDetailsBloc>()
                      .add(DeleteRoleDeleteEvent(widget.id));
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: 4),
                  child: Assets.images.icons.delete.svg(
                    width: 16,
                    height: 16,
                    colorFilter: const ColorFilter.mode(
                        AppColors.statusError, BlendMode.srcIn),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  _skillDropDown(BusinessSkillModel? selectedSkill,
      List<BusinessSkillModel> allSkills, BuildContext context) {
    return KwDropdown(
        key: ValueKey('skill_key${widget.id}'),
        title: 'Role',
        hintText: 'Role name',
        horizontalPadding: 40,
        selectedItem: selectedSkill != null
            ? KwDropDownItem(
                data: selectedSkill, title: selectedSkill.skill?.name ?? '')
            : null,
        items: allSkills
            .map((e) => KwDropDownItem(data: e, title: e.skill?.name ?? '')),
        onSelected: (item) {
          context.read<CreateRoleBloc>().add(CreateRoleSelectSkillEvent(item));
          Future.delayed(
              const Duration(milliseconds: 500),
              () => context
                  .read<CreateEventBloc>()
                  .add(CreateEventEntityUpdatedEvent()));
        });
  }

  _departmentDropDown(DepartmentModel? selected,
      List<DepartmentModel> allDepartments, BuildContext context) {
    return KwDropdown(
        title: 'Department',
        hintText: 'Department name',
        horizontalPadding: 40,
        selectedItem: selected != null
            ? KwDropDownItem(data: selected, title: selected.name)
            : null,
        items:
            allDepartments.map((e) => KwDropDownItem(data: e, title: e.name)),
        onSelected: (item) {
          context
              .read<CreateRoleBloc>()
              .add(CreateRoleSelectDepartmentEvent(item));
        });
  }

  _countDropDown(int? selected, BuildContext context) {
    return KwDropdown(
        key: ValueKey('count_key${widget.id}'),
        title: 'Number of Employee for one Role',
        hintText: 'Person count',
        horizontalPadding: 40,
        selectedItem: selected != null
            ? KwDropDownItem(data: selected, title: selected.toString())
            : null,
        items: List.generate(98, (e) => e + 1)
            .map((e) => KwDropDownItem(data: e, title: (e).toString())),
        onSelected: (item) {
          context.read<CreateRoleBloc>().add(CreateRoleSelectCountEvent(item));
          Future.delayed(
              const Duration(milliseconds: 500),
                  () {
                    context
                  .read<CreateEventBloc>()
                  .add(CreateEventEntityUpdatedEvent());
                  });
        });
  }

  _timeRow(context, DateTime? startTime, DateTime? endTime) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
          child: KwTimeSlotInput(
            key: ValueKey('start_time_key${widget.id}'),
            label: 'Start Time',
            initialValue: startTime ?? DateTime(2000,1,1,9,0),
            onChange: (value) {

              BlocProvider.of<CreateRoleBloc>(context)
                  .add(SetRoleStartTimeEvent(value));
              try {
              // Future.delayed(
              //     const Duration(milliseconds: 100),
              //         () => context
              //         .read<CreateEventBloc>()
              //         .add(CreateEventEntityUpdatedEvent()));
              } catch (e) {
                print(e);
              }
            },
          ),
        ),
        const Gap(8),
        Expanded(
          child: KwTimeSlotInput(
            key: ValueKey('end_time_key${widget.id}'),
            label: 'End Time',
            initialValue: endTime ?? DateTime(2000,1,1,14,0),
            onChange: (value) {
              BlocProvider.of<CreateRoleBloc>(context)
                  .add(SetRoleEndTimeEvent(value));
              try {
                // Future.delayed(
                //     const Duration(milliseconds: 100),
                //         () => context
                //         .read<CreateEventBloc>()
                //         .add(CreateEventEntityUpdatedEvent()));
              } catch (e) {
                print(e);
              }
            },
          ),
        ),
      ],
    );
  }

  _breakDropDown(BuildContext context,CreateRoleState state) {
    String formatBreakDuration(int minutes) {
      if (minutes == 60) {
        return '1h';
      } else if (minutes > 60) {
        final hours = minutes ~/ 60;
        final remainder = minutes % 60;
        return remainder == 0 ? '${hours}h' : '${hours}h ${remainder} min';
      }
      return '${minutes} min';
    }



    return KwDropdown(
        key: ValueKey('break_key${widget.id}'),
        title: 'Break Duration',
        hintText: 'Duration',
        horizontalPadding: 40,
        selectedItem:  KwDropDownItem(data: state.entity.breakDuration, title: formatBreakDuration(state.entity.breakDuration??0)),
        items: [15, 30].map((e) {
          return KwDropDownItem(data: e, title: formatBreakDuration(e));
        }),
        onSelected: (item) {
          context.read<CreateRoleBloc>().add(CreateRoleSelectBreak(item??0));
        });


  }

  Widget textRow(String key, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(key,
            style: AppTextStyles.bodyMediumReg
                .copyWith(color: AppColors.blackGray)),
        Text(value, style: AppTextStyles.bodyMediumMed),
      ],
    );
  }
}
