import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:core_localization/core_localization.dart';
import 'package:krow_domain/krow_domain.dart';
import '../blocs/client_hubs_bloc.dart';
import '../blocs/client_hubs_event.dart';
import '../blocs/client_hubs_state.dart';
import '../widgets/add_hub_dialog.dart';
import '../widgets/hub_card.dart';
import '../widgets/hub_empty_state.dart';
import '../widgets/hub_info_card.dart';
import '../widgets/identify_nfc_dialog.dart';

/// The main page for the client hubs feature.
///
/// This page follows the KROW Clean Architecture by being a [StatelessWidget]
/// and delegating all state management to the [ClientHubsBloc].
class ClientHubsPage extends StatelessWidget {
  /// Creates a [ClientHubsPage].
  const ClientHubsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider<ClientHubsBloc>(
      create: (BuildContext context) =>
          Modular.get<ClientHubsBloc>()..add(const ClientHubsFetched()),
      child: BlocConsumer<ClientHubsBloc, ClientHubsState>(
        listenWhen: (ClientHubsState previous, ClientHubsState current) {
          return previous.errorMessage != current.errorMessage ||
              previous.successMessage != current.successMessage;
        },
        listener: (BuildContext context, ClientHubsState state) {
          if (state.errorMessage != null && state.errorMessage!.isNotEmpty) {
            final String errorMessage = translateErrorKey(state.errorMessage!);
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text(errorMessage)),
            );
            BlocProvider.of<ClientHubsBloc>(
              context,
            ).add(const ClientHubsMessageCleared());
          }
          if (state.successMessage != null && state.successMessage!.isNotEmpty) {
            ScaffoldMessenger.of(
              context,
            ).showSnackBar(SnackBar(content: Text(state.successMessage!)));
            BlocProvider.of<ClientHubsBloc>(
              context,
            ).add(const ClientHubsMessageCleared());
          }
        },
        builder: (BuildContext context, ClientHubsState state) {
          return Scaffold(
            backgroundColor: UiColors.bgMenu,
            floatingActionButton: FloatingActionButton(
              onPressed: () => BlocProvider.of<ClientHubsBloc>(
                context,
              ).add(const ClientHubsAddDialogToggled(visible: true)),
              shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(8)),
              ),
              child: const Icon(UiIcons.add),
            ),
            body: Stack(
              children: <Widget>[
                CustomScrollView(
                  slivers: <Widget>[
                    _buildAppBar(context),
                    SliverPadding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: UiConstants.space5,
                        vertical: UiConstants.space5,
                      ).copyWith(bottom: 100),
                      sliver: SliverList(
                        delegate: SliverChildListDelegate(<Widget>[
                          if (state.status == ClientHubsStatus.loading)
                            const Center(child: CircularProgressIndicator())
                          else if (state.hubs.isEmpty)
                            HubEmptyState(
                              onAddPressed: () =>
                                  BlocProvider.of<ClientHubsBloc>(context).add(
                                    const ClientHubsAddDialogToggled(
                                      visible: true,
                                    ),
                                  ),
                            )
                          else ...<Widget>[
                            ...state.hubs.map(
                              (Hub hub) => HubCard(
                                hub: hub,
                                onNfcPressed: () =>
                                    BlocProvider.of<ClientHubsBloc>(
                                      context,
                                    ).add(
                                      ClientHubsIdentifyDialogToggled(hub: hub),
                                    ),
                                onDeletePressed: () =>
                                    BlocProvider.of<ClientHubsBloc>(
                                      context,
                                    ).add(ClientHubsDeleteRequested(hub.id)),
                              ),
                            ),
                          ],
                          const SizedBox(height: UiConstants.space5),
                          const HubInfoCard(),
                        ]),
                      ),
                    ),
                  ],
                ),
                if (state.showAddHubDialog)
                  AddHubDialog(
                    onCreate: (
                      String name,
                      String address, {
                      String? placeId,
                      double? latitude,
                      double? longitude,
                    }) {
                      BlocProvider.of<ClientHubsBloc>(context).add(
                        ClientHubsAddRequested(
                          name: name,
                          address: address,
                          placeId: placeId,
                          latitude: latitude,
                          longitude: longitude,
                        ),
                      );
                    },
                    onCancel: () => BlocProvider.of<ClientHubsBloc>(
                      context,
                    ).add(const ClientHubsAddDialogToggled(visible: false)),
                  ),
                if (state.hubToIdentify != null)
                  IdentifyNfcDialog(
                    hub: state.hubToIdentify!,
                    onAssign: (String tagId) {
                      BlocProvider.of<ClientHubsBloc>(context).add(
                        ClientHubsNfcTagAssignRequested(
                          hubId: state.hubToIdentify!.id,
                          nfcTagId: tagId,
                        ),
                      );
                    },
                    onCancel: () => BlocProvider.of<ClientHubsBloc>(
                      context,
                    ).add(const ClientHubsIdentifyDialogToggled()),
                  ),
                if (state.status == ClientHubsStatus.actionInProgress)
                  Container(
                    color: UiColors.black.withValues(alpha: 0.1),
                    child: const Center(child: CircularProgressIndicator()),
                  ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildAppBar(BuildContext context) {
    return SliverAppBar(
      backgroundColor: UiColors.foreground, // Dark Slate equivalent
      automaticallyImplyLeading: false,
      expandedHeight: 140,
      pinned: true,
      flexibleSpace: FlexibleSpaceBar(
        background: Container(
          color: UiColors.foreground,
          padding: const EdgeInsets.fromLTRB(
            UiConstants.space5,
            UiConstants.space12,
            UiConstants.space5,
            0,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              GestureDetector(
                onTap: () => Modular.to.navigate('/client-main/home/'),
                child: Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: UiColors.white.withValues(alpha: 0.2),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    UiIcons.arrowLeft,
                    color: UiColors.white,
                    size: 20,
                  ),
                ),
              ),
              const SizedBox(height: UiConstants.space4),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        t.client_hubs.title,
                        style: UiTypography.headline1m.white,
                      ),
                      Text(
                        t.client_hubs.subtitle,
                        style: UiTypography.body2r.copyWith(
                          color: UiColors.switchInactive,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
