import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/widgets/custom_error_screen.dart';
import 'package:niogu_app/features/online_store/domain/entities/online_store.dart';
import 'package:niogu_app/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/checkbox_button.dart';
import 'package:sizer/sizer.dart';

class TargetOutletScreen extends ConsumerWidget {
  const TargetOutletScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final bool isTablet = 100.w >= 600;

        final targetOutletState = ref.watch(targetOutletStreamProvider);

        final selectedOutlet = ref.watch(
          selectedTargetOutletControllerProvider,
        );

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            appBar: TopBackBarApp(
              title: "Tujuan Campaign",
              onTap: () => context.pop(),
            ),
            body: targetOutletState.when(
              data: (outlets) {
                final bool isAllSelected =
                    selectedOutlet.isNotEmpty &&
                    (outlets.length == selectedOutlet.values.length);

                return Column(
                  children: [
                    InkWell(
                      onTap: () {
                        final selectedOutletState = ref.read(
                          selectedTargetOutletControllerProvider,
                        );

                        if (selectedOutletState.isNotEmpty &&
                            (outlets.length ==
                                selectedOutletState.values.length)) {
                          ref
                              .read(
                                selectedTargetOutletControllerProvider.notifier,
                              )
                              .clear();
                          return;
                        }

                        for (final outlet in outlets) {
                          final selectedOutlet = SelectedTargetOutlet(
                            outletId: outlet.id,
                            name: outlet.name,
                          );

                          ref
                              .read(
                                selectedTargetOutletControllerProvider.notifier,
                              )
                              .toggleSelectAll(selectedOutlet);
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 5.w,
                          vertical: 1.5.h,
                        ),
                        color: Colors.blue[50]!.withOpacity(0.5),
                        child: Row(
                          children: [
                            CheckboxButton(isSelected: isAllSelected),
                            SizedBox(width: 4.w),
                            Text(
                              "Pilih Semua Outlet",
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: isTablet
                                    ? AppFontSize.medium.sp
                                    : AppFontSize.small.sp,
                                color: Colors.blue[800],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),

                    Expanded(
                      child: ListView.builder(
                        padding: EdgeInsets.fromLTRB(4.w, 1.h, 4.w, 5.h),
                        itemCount: outlets.length,
                        itemBuilder: (context, index) {
                          final outlet = outlets[index];
                          return Container(
                            margin: EdgeInsets.only(bottom: 1.5.h),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(2.5.w),
                              border: Border.all(color: Colors.grey.shade200),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.02),
                                  blurRadius: 4,
                                  offset: const Offset(0, 2),
                                ),
                              ],
                            ),
                            child: InkWell(
                              onTap: () {
                                final selectedOutlet = SelectedTargetOutlet(
                                  outletId: outlet.id,
                                  name: outlet.name,
                                );
                                ref
                                    .read(
                                      selectedTargetOutletControllerProvider
                                          .notifier,
                                    )
                                    .toggle(selectedOutlet);
                              },
                              borderRadius: BorderRadius.circular(2.5.w),
                              child: Padding(
                                padding: EdgeInsets.all(4.w),
                                child: Row(
                                  children: [
                                    CheckboxButton(
                                      isSelected: selectedOutlet.containsKey(
                                        outlet.id,
                                      ),
                                    ),
                                    SizedBox(width: 4.w),
                                    Icon(
                                      Icons.storefront_rounded,
                                      color: Colors.grey[400],
                                      size: 6.w,
                                    ),
                                    SizedBox(width: 3.w),
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            outlet.name,
                                            style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize: isTablet
                                                  ? AppFontSize.medium.sp
                                                  : AppFontSize.small.sp,
                                              color: Colors.black87,
                                            ),
                                          ),

                                          if (outlet.address != null &&
                                              outlet.address!.isNotEmpty) ...[
                                            SizedBox(height: 0.5.h),
                                            Text(
                                              outlet.address!,
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                color: Colors.grey[600],
                                                fontSize: isTablet
                                                    ? (AppFontSize.medium -
                                                              1.25)
                                                          .sp
                                                    : (AppFontSize.small - 1.25)
                                                          .sp,
                                              ),
                                            ),
                                          ],
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                );
              },
              error: (error, stackTrace) => CustomErrorScreen(
                message: "Ups, terjadi kesalahan",
                onRefresh: () {},
              ),
              loading: () => const SizedBox(),
            ),
            bottomNavigationBar: Container(
              padding: EdgeInsets.all(5.w),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, -5),
                  ),
                ],
              ),
              child: ElevatedButton(
                onPressed: selectedOutlet.values.isEmpty
                    ? null
                    : () => context.pop(),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColor.primaryColor,
                  minimumSize: Size(double.infinity, 6.5.h),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(3.w),
                  ),
                  disabledBackgroundColor: Colors.grey[300],
                ),
                child: Text(
                  "Pilih",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: AppFontSize.medium.sp,
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
