import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../application/outlet/outlet_list_loader/outlet_list_loader_bloc.dart';
import '../../../../application/outlet/selected_outlet/selected_outlet_bloc.dart';
import '../../../../common/theme/theme.dart';
import '../../../components/spacer/spacer.dart';

class HeaderOutletBottomSheet extends StatelessWidget {
  const HeaderOutletBottomSheet({super.key});

  static void show(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (_) => MultiBlocProvider(
        providers: [
          BlocProvider.value(value: context.read<OutletListLoaderBloc>()),
          BlocProvider.value(value: context.read<SelectedOutletBloc>()),
        ],
        child: const HeaderOutletBottomSheet(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.height * 0.6,
      ),
      decoration: const BoxDecoration(
        color: AppColor.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Handle bar
          const SizedBox(height: 12),
          Container(
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: AppColor.border,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(height: 16),

          // Title
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Row(
              children: [
                Text(
                  'Pilih Outlet',
                  style: AppStyle.lg.copyWith(
                    fontWeight: FontWeight.w700,
                    color: AppColor.textPrimary,
                  ),
                ),
                const Spacer(),
                GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child: const Icon(
                    Icons.close_rounded,
                    color: AppColor.textSecondary,
                    size: 24,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),

          // List
          Flexible(
            child: BlocBuilder<OutletListLoaderBloc, OutletListLoaderState>(
              builder: (context, outletListState) {
                if (outletListState.isFetching &&
                    outletListState.outlets.isEmpty) {
                  return const Center(
                    child: Padding(
                      padding: EdgeInsets.all(24),
                      child: CircularProgressIndicator(),
                    ),
                  );
                }

                return BlocBuilder<SelectedOutletBloc, SelectedOutletState>(
                  builder: (context, selectedState) {
                    return ListView(
                      shrinkWrap: true,
                      padding: const EdgeInsets.symmetric(horizontal: 20),
                      children: [
                        // Semua Outlet
                        _OutletTile(
                          title: 'Semua Outlet',
                          subtitle: '${outletListState.outlets.length} outlet',
                          icon: Icons.store_rounded,
                          isSelected: selectedState.isAllOutlets,
                          onTap: () {
                            context.read<SelectedOutletBloc>().add(
                              const SelectedOutletEvent.cleared(),
                            );
                            Navigator.pop(context);
                          },
                        ),

                        const SizedBox(height: 8),

                        // Individual outlets
                        ...outletListState.outlets.map((outlet) {
                          final isSelected =
                              selectedState.selectedOutletId == outlet.id;
                          return Padding(
                            padding: const EdgeInsets.only(bottom: 8),
                            child: _OutletTile(
                              title: outlet.name,
                              subtitle: outlet.isActive
                                  ? 'Aktif'
                                  : 'Tidak aktif',
                              icon: Icons.storefront_rounded,
                              isSelected: isSelected,
                              isActive: outlet.isActive,
                              onTap: () {
                                context.read<SelectedOutletBloc>().add(
                                  SelectedOutletEvent.selected(outlet),
                                );
                                Navigator.pop(context);
                              },
                            ),
                          );
                        }),

                        const SizedBox(height: 16),
                      ],
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

class _OutletTile extends StatelessWidget {
  final String title;
  final String subtitle;
  final IconData icon;
  final bool isSelected;
  final bool isActive;
  final VoidCallback onTap;

  const _OutletTile({
    required this.title,
    required this.subtitle,
    required this.icon,
    required this.isSelected,
    this.isActive = true,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        decoration: BoxDecoration(
          color: isSelected
              ? AppColor.primary.withOpacity(0.08)
              : AppColor.background,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: isSelected ? AppColor.primary : AppColor.border,
            width: isSelected ? 1.5 : 1,
          ),
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: isSelected
                    ? AppColor.primary.withOpacity(0.15)
                    : AppColor.border.withOpacity(0.5),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Icon(
                icon,
                color: isSelected ? AppColor.primary : AppColor.textSecondary,
                size: 20,
              ),
            ),
            const SpaceWidth(12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: AppStyle.md.copyWith(
                      fontWeight: FontWeight.w600,
                      color: AppColor.textPrimary,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 2),
                  Text(
                    subtitle,
                    style: AppStyle.xs.copyWith(color: AppColor.textSecondary),
                  ),
                ],
              ),
            ),
            if (isSelected)
              Icon(
                Icons.check_circle_rounded,
                color: AppColor.primary,
                size: 22,
              ),
            if (!isSelected && !isActive)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: AppColor.error.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Text(
                  'Off',
                  style: AppStyle.xs.copyWith(
                    color: AppColor.error,
                    fontWeight: FontWeight.w600,
                    fontSize: 10,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
