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/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/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_suggestion_input.dart';
import 'package:krow/features/create_event/domain/bloc/create_event_bloc.dart';
import 'package:krow/features/create_event/domain/google_places_service.dart';
import 'package:krow/features/create_event/presentation/create_role_section/create_roles_list.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/create_shift_details_section/widgets/shift_contacts_widget.dart';

class CreateShiftDetailsWidget extends StatefulWidget {
  final String id;

  final int index;

  final bool expanded;

  const CreateShiftDetailsWidget({
    super.key,
    required this.id,
    required this.index,
    this.expanded = true,
  });

  @override
  State<CreateShiftDetailsWidget> createState() =>
      _CreateShiftDetailsWidgetState();
}

class _CreateShiftDetailsWidgetState extends State<CreateShiftDetailsWidget>
    with AutomaticKeepAliveClientMixin {
  ExpandableController? _expandableController;

  @override
  bool get wantKeepAlive => true;

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

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

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BlocBuilder<CreateEventBloc, CreateEventState>(
      builder: (context, eventState) {
        return BlocConsumer<CreateShiftDetailsBloc, CreateShiftDetailsState>(
          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.all(12),
              decoration: KwBoxDecorations.white12.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(
                      context, state, eventState.shifts.length > 1),
                  expanded: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      _addressInput(state, context),
                      ShiftContactsWidget(
                          allContacts: eventState.contacts,
                          selectedContacts: state.shift?.managers ?? []),
                      CreateRolesList(id: widget.id),
                      const Gap(12),
                      KwButton.outlinedPrimary(
                          label: 'Add New Role',
                          leftIcon: Assets.images.icons.add,
                          onPressed: () {
                            context
                                .read<CreateShiftDetailsBloc>()
                                .add(CreateEventAddRoleEvent());
                          }),
                      const Gap(12),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildHeader(
    BuildContext context,
    CreateShiftDetailsState state,
    bool canBeRemoved,
  ) {
    return GestureDetector(
      onTap: () {
        context.read<CreateShiftDetailsBloc>().add(ExpandShiftEvent());
      },
      child: Container(
        color: Colors.transparent,
        padding: const EdgeInsets.symmetric(vertical: 12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              'Shift Details #${widget.index + 1}',
              style: AppTextStyles.bodyMediumMed,
            ),
            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 && canBeRemoved)
              GestureDetector(
                onTap: () {
                  context
                      .read<CreateEventBloc>()
                      .add(CreateEventRemoveShift(widget.id));
                },
                child: Container(
                  height: 24,
                  width: 24,
                  color: Colors.transparent,
                  child: Padding(
                    padding: const EdgeInsets.only(right: 4),
                    child: Center(
                      child: Assets.images.icons.delete.svg(
                        width: 16,
                        height: 16,
                        colorFilter: const ColorFilter.mode(
                            AppColors.statusError, BlendMode.srcIn),
                      ),
                    ),
                  ),
                ),
              )
          ],
        ),
      ),
    );
  }

  KwSuggestionInput<MapPlace> _addressInput(
      CreateShiftDetailsState state, BuildContext context) {
    state.suggestions.removeWhere(
        (e) => e.description == state.shift.fullAddress?.formattedAddress);
    return KwSuggestionInput(
      key: ValueKey('address_key${widget.id}'),
      title: 'Address',
      hintText: 'Hub address',
      horizontalPadding: 28,
      initialText: state.shift.fullAddress?.formattedAddress,
      items: state.suggestions,
      onQueryChanged: (query) {
        context
            .read<CreateShiftDetailsBloc>()
            .add(CreateShiftAddressQueryChangedEvent(query));
      },
      itemToStringBuilder: (item) => item.description,
      onSelected: (item) {
        context
            .read<CreateShiftDetailsBloc>()
            .add(CreateShiftAddressSelectEvent(place: item));
      },
    );
  }
}
