import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.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/core/providers/app_provider.dart';
import 'package:niogu_app/core/system/system_setting.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/core/components/modal_outlet_bottom_shimmer.dart';
import 'package:niogu_app/features/outlets/presentation/providers/outlet_provider.dart';
import 'package:sizer/sizer.dart';

class ModalOutletBottom extends ConsumerStatefulWidget {
  const ModalOutletBottom({super.key});

  @override
  ConsumerState<ModalOutletBottom> createState() => _ModalOutletBottomState();
}

class _ModalOutletBottomState extends ConsumerState<ModalOutletBottom> {
  String? _activeOutletId;

  String? _tempSelectedId;

  String? _currentOutletName;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      Future.delayed(const Duration(milliseconds: 400), () {
        initCurrentOutlet();
      });
    });
  }

  Future<void> initCurrentOutlet() async {
    _activeOutletId = await SystemSetting.getCurrentOutletId();

    _currentOutletName = await SystemSetting.getCurrentOutletName();

    setState(() {
      _tempSelectedId = _activeOutletId;
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  Future<void> _handleSwicthOutlet() async {
    await SystemSetting.switchOutlet(
      outletId: _tempSelectedId!,
      outletName: _currentOutletName!,
    );

    _activeOutletId = await SystemSetting.getCurrentOutletId();

    _currentOutletName = await SystemSetting.getCurrentOutletName();

    ref.read(currentOutletIdProvider.notifier).state = _activeOutletId;

    ref.read(currentOutletNameProvider.notifier).state = _currentOutletName;

    context.pop();

    CustomSnackbar.showSuccess(
      context,
      "Berhasil masuk ke ${_currentOutletName!}",
    );
  }

  @override
  Widget build(BuildContext context) {
    final bool isTablet = 100.w >= 600;

    final outletState = ref.watch(outletStreamProvider);

    return Container(
      height: 85.h,
      width: 100.w,
      padding: EdgeInsets.fromLTRB(5.w, 2.h, 5.w, 5.h),
      clipBehavior: Clip.hardEdge,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(6.w)),
      ),
      constraints: BoxConstraints(maxHeight: 85.h),
      child: Material(
        color: Colors.white,
        type: MaterialType.card,
        child: outletState.when(
          data: (outlets) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Center(
                  child: Container(
                    width: 15.w,
                    height: 0.6.h,
                    decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.circular(2.25.w),
                    ),
                  ),
                ),
                SizedBox(height: 3.h),

                Text(
                  "Pilih Outlet",
                  style: TextStyle(
                    fontSize: isTablet
                        ? AppFontSize.medium.sp
                        : AppFontSize.small.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
                SizedBox(height: 2.h),

                Expanded(
                  child: ListView.builder(
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemCount: outlets.length,
                    itemBuilder: (context, index) {
                      final outlet = outlets[index];

                      final File imageFile = File(
                        outlet.photoPath ?? "image not found",
                      );

                      final bool imageFileExists = imageFile.existsSync();

                      final isSelected = outlet.id == _tempSelectedId;

                      final isActiveReal = outlet.id == _activeOutletId;

                      return Padding(
                        padding: EdgeInsets.only(bottom: 1.5.h),
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              _tempSelectedId = outlet.id;
                              _currentOutletName = outlet.name;
                            });
                          },
                          borderRadius: BorderRadius.circular(2.5.w),
                          child: AnimatedContainer(
                            duration: const Duration(milliseconds: 200),
                            padding: EdgeInsets.symmetric(
                              horizontal: 4.w,
                              vertical: 2.h,
                            ),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(2.5.w),
                              border: Border.all(
                                color: isSelected
                                    ? AppColor.primaryColor
                                    : Colors.grey.shade300,
                                width: isSelected ? 2 : 1,
                              ),
                              boxShadow: isSelected
                                  ? [
                                      BoxShadow(
                                        color: AppColor.primaryColor.withValues(
                                          alpha: 0.1,
                                        ),
                                        blurRadius: 8,
                                        offset: Offset(0, 4),
                                      ),
                                    ]
                                  : [],
                            ),
                            child: Row(
                              children: [
                                Container(
                                  width: 15.w,
                                  height: 15.w,
                                  clipBehavior: Clip.hardEdge,

                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(2.5.w),
                                    border: Border.all(
                                      color: Colors.grey.shade300,
                                      width: 1,
                                    ),
                                  ),

                                  child: Center(
                                    child: imageFileExists
                                        ? Image.file(
                                            imageFile,
                                            fit: BoxFit.cover,
                                            width: double.infinity,
                                            height: double.infinity,
                                            errorBuilder:
                                                (context, error, stackTrace) {
                                                  return Icon(
                                                    Icons.error,
                                                    color: Colors.grey,
                                                    size: 8.w,
                                                  );
                                                },
                                          )
                                        : Icon(
                                            Icons.store_outlined,
                                            color: Colors.grey,
                                            size: 8.w,
                                          ),
                                  ),
                                ),

                                SizedBox(width: 2.w),

                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        outlet.name,
                                        style: TextStyle(
                                          fontSize: isTablet
                                              ? AppFontSize.medium.sp
                                              : AppFontSize.small.sp,
                                          fontWeight: isSelected
                                              ? FontWeight.bold
                                              : FontWeight.normal,
                                          color: isSelected
                                              ? Colors.black87
                                              : Colors.grey[800],
                                        ),
                                      ),

                                      if (outlet.isMainOutlet) ...[
                                        SizedBox(height: 0.75.h),
                                        Text(
                                          "(Outlet Utama)",
                                          style: TextStyle(
                                            fontSize: isTablet
                                                ? (AppFontSize.medium - 2).sp
                                                : (AppFontSize.small - 2).sp,
                                            fontWeight: isSelected
                                                ? FontWeight.bold
                                                : FontWeight.normal,
                                            color: isSelected
                                                ? Colors.black87
                                                : Colors.grey[800],
                                          ),
                                        ),
                                      ],

                                      if (isActiveReal) ...[
                                        SizedBox(height: 0.75.h),
                                        Container(
                                          padding: EdgeInsets.symmetric(
                                            horizontal: 2.w,
                                            vertical: 0.2.h,
                                          ),
                                          decoration: BoxDecoration(
                                            color: Colors.green,
                                            borderRadius: BorderRadius.circular(
                                              4,
                                            ),
                                          ),
                                          child: Text(
                                            "Sedang Aktif",
                                            style: TextStyle(
                                              fontSize: isTablet
                                                  ? AppFontSize.medium.sp
                                                  : AppFontSize.small.sp,
                                              color: Colors.white,
                                            ),
                                          ),
                                        ),
                                      ],

                                      if (!outlet.isActive) ...[
                                        SizedBox(height: 0.75),
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.end,
                                          children: [
                                            Text(
                                              "Non Aktif / Tutup",
                                              style: TextStyle(
                                                color: Colors.red,
                                                fontSize: isTablet
                                                    ? (AppFontSize.medium - 2)
                                                          .sp
                                                    : (AppFontSize.small - 2)
                                                          .sp,
                                                fontWeight: isSelected
                                                    ? FontWeight.bold
                                                    : FontWeight.normal,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ],
                                  ),
                                ),
                                if (isSelected)
                                  Icon(
                                    Icons.check_circle,
                                    color: AppColor.primaryColor,
                                    size: 6.w,
                                  ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),

                SizedBox(height: 1.h),

                SizedBox(
                  width: double.infinity,
                  height: 6.5.h,
                  child: ElevatedButton(
                    onPressed:
                        !(_tempSelectedId != null &&
                            outlets
                                .firstWhere(
                                  (outlet) => outlet.id == _tempSelectedId,
                                )
                                .isActive)
                        ? null
                        : _handleSwicthOutlet,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColor.primaryColor,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(2.5.w),
                      ),
                      elevation: 4,
                    ),
                    child: Text(
                      "Masuk Ke Outlet Ini",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: AppFontSize.medium.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),

                SizedBox(height: MediaQuery.of(context).padding.bottom),
              ],
            );
          },
          error: (error, stackTrace) {
            return CustomErrorScreen(
              message: "Ups, terjadi kesalahan",
              onRefresh: () {},
            );
          },
          loading: () => const ModalOutletBottomShimmer(),
        ),
      ),
    );
  }
}
