import 'package:enaklo_pos/core/components/buttons.dart';
import 'package:enaklo_pos/core/components/custom_modal_dialog.dart';
import 'package:enaklo_pos/core/components/spaces.dart';
import 'package:enaklo_pos/core/extensions/build_context_ext.dart';
import 'package:enaklo_pos/presentation/home/bloc/outlet_loader/outlet_loader_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/user_update_outlet/user_update_outlet_bloc.dart';
import 'package:enaklo_pos/presentation/home/models/outlet_model.dart';
import 'package:enaklo_pos/presentation/home/widgets/outlet_card.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

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

  @override
  State<OutletDialog> createState() => _OutletDialogState();
}

class _OutletDialogState extends State<OutletDialog> {
  Outlet? selectedOutlet;

  void selectOutlet(Outlet outlet) {
    setState(() {
      if (selectedOutlet == outlet) {
        selectedOutlet = null; // Deselect jika outlet yang sama diklik
      } else {
        selectedOutlet =
            outlet; // Select outlet baru (akan mengganti selection sebelumnya)
      }
    });
  }

  @override
  void initState() {
    super.initState();
    context.read<OutletLoaderBloc>().add(OutletLoaderEvent.getOutlet());
  }

  @override
  Widget build(BuildContext context) {
    return CustomModalDialog(
      title: 'Outlet',
      subtitle: 'Silahkan pilih outlet',
      minWidth: context.deviceWidth * 0.4,
      contentPadding:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0),
      child: BlocBuilder<OutletLoaderBloc, OutletLoaderState>(
        builder: (context, state) {
          return state.maybeWhen(
            orElse: () => Center(
              child: Text('Error has occured'),
            ),
            loading: () => Center(child: CircularProgressIndicator()),
            error: (message) => Center(
              child: Text(message),
            ),
            loaded: (outlets) => Column(
              children: [
                ...List.generate(
                  outlets.length,
                  (index) => GestureDetector(
                    onTap: () {
                      selectOutlet(outlets[index]);
                    },
                    child: OutletCard(
                      outlet: outlets[index],
                      isSelected: selectedOutlet == outlets[index],
                    ),
                  ),
                ),
                SpaceHeight(24),
                BlocListener<UserUpdateOutletBloc, UserUpdateOutletState>(
                  listener: (context, state) {
                    state.maybeWhen(
                      orElse: () {},
                      success: () {
                        context.pop();
                      },
                    );
                  },
                  child:
                      BlocBuilder<UserUpdateOutletBloc, UserUpdateOutletState>(
                    builder: (context, state) {
                      return state.maybeWhen(
                        orElse: () => Button.filled(
                          onPressed: selectedOutlet == null
                              ? null
                              : () {
                                  context.read<UserUpdateOutletBloc>().add(
                                      UserUpdateOutletEvent.update(
                                          selectedOutlet!.id ?? ""));
                                },
                          label: 'Terapkan',
                        ),
                        loading: () => Center(
                          child: CircularProgressIndicator(),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
