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/router/app_route.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/widgets/custom_selector.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/core/widgets/custom_text_form_field.dart';
import 'package:niogu_app/core/widgets/custom_time_picker.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:sizer/sizer.dart';

class ConfigureOnlineStoreScreen extends ConsumerStatefulWidget {
  final ConfigureOnlineStore configure;
  const ConfigureOnlineStoreScreen({super.key, required this.configure});

  @override
  ConsumerState<ConfigureOnlineStoreScreen> createState() =>
      _ConfigureOnlineStoreScreenState();
}

class _ConfigureOnlineStoreScreenState
    extends ConsumerState<ConfigureOnlineStoreScreen> {
  final TextEditingController _storeNameController = TextEditingController();

  final TextEditingController _prepTimeController = TextEditingController();

  final TextEditingController _gapTimeController = TextEditingController();

  late TimeOfDay _onlineOpenTime;

  late TimeOfDay _onlineCloseTime;

  bool _isCloseService = false;

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

    final configure = widget.configure;

    _storeNameController.text = configure.onlineStoreName;

    _onlineOpenTime = configure.onlineOpenTime.isEmpty
        ? TimeOfDay(hour: 08, minute: 00)
        : _parseTimeOfDay(configure.onlineOpenTime);

    _onlineCloseTime = configure.onlineCloseTime.isEmpty
        ? TimeOfDay(hour: 20, minute: 00)
        : _parseTimeOfDay(configure.onlineCloseTime);

    _isCloseService = configure.isCloseService;

    final Map<String, String> selectedOnlineStoreProducts = {
      for (final productId in configure.productIds) productId: productId,
    };

    if (configure.preparationTimeMinutes > 0) {
      _prepTimeController.text = "${configure.preparationTimeMinutes}";
    }

    if (configure.orderIntervalMinutes > 0) {
      _gapTimeController.text = "${configure.orderIntervalMinutes}";
    }

    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(selectedOnlineStoreProductProvider.notifier).state =
          selectedOnlineStoreProducts;
    });
  }

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

  TimeOfDay _parseTimeOfDay(String timeString) {
    List<String> parts = timeString.split('.');

    int hour = int.parse(parts[0]);
    int minute = int.parse(parts[1]);

    return TimeOfDay(hour: hour, minute: minute);
  }

  Future<void> _selectTime(bool isStart) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: isStart ? _onlineOpenTime : _onlineCloseTime,
      builder: (BuildContext context, Widget? child) {
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
          child: child!,
        );
      },
    );

    if (picked != null) {
      setState(() {
        if (isStart) {
          _onlineOpenTime = picked;
        } else {
          _onlineCloseTime = picked;
        }
      });
    }
  }

  Future<void> _saveConfigureOnlineStore() async {
    final onlineStoreName = _storeNameController.text.trim();

    final preparationTimeMinutes =
        int.tryParse(_prepTimeController.text.trim()) ?? 0;

    final orderIntervalMinutes =
        int.tryParse(_gapTimeController.text.trim()) ?? 0;

    final productIds = ref
        .read(selectedOnlineStoreProductProvider)
        .values
        .toList();

    final configure = ConfigureOnlineStore(
      onlineStoreName: onlineStoreName,
      onlineOpenTime: _onlineOpenTime.format(context),
      onlineCloseTime: _onlineCloseTime.format(context),
      isCloseService: _isCloseService,
      preparationTimeMinutes: preparationTimeMinutes,
      orderIntervalMinutes: orderIntervalMinutes,
      productIds: productIds,
    );

    try {
      await ref
          .read(onlineStoreControllerProvider.notifier)
          .configureOnlineStore(configure);

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, "Toko online berhasil diperbarui");
      context.pop();
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, 'Ups, terjadi kesalahan');
    }
  }

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

        final selectedOnlineStoreProductState = ref.watch(
          selectedOnlineStoreProductProvider,
        );

        final onlineStoreControllerState = ref.watch(
          onlineStoreControllerProvider,
        );

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: TopBackBarApp(
              title: "Atur Toko Online",
              onTap: () => context.pop(),
            ),
            body: SingleChildScrollView(
              padding: EdgeInsets.all(5.w),
              child: Column(
                children: [
                  CustomTextFormField(
                    label: "Nama Toko Online",
                    hint: "Contoh : Kopi Senja",
                    prefixIcon: Icons.store_outlined,
                    controller: _storeNameController,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return "Nama toko online belum diisi";
                      }

                      return null;
                    },
                  ),

                  SizedBox(height: 3.h),

                  Align(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: EdgeInsets.only(bottom: 1.5.h, left: 1.w),
                      child: Text(
                        "Jam Layanan Toko Online",
                        style: TextStyle(
                          fontSize: isTablet
                              ? AppFontSize.medium.sp
                              : AppFontSize.small.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                  ),

                  Container(
                    padding: EdgeInsets.all(4.w),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(3.w),
                      border: Border.all(color: Colors.grey.shade200),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Expanded(
                              child: CustomTimePicker(
                                label: "Jam Buka",
                                time: _onlineOpenTime,
                                onTap: () => _selectTime(true),
                                isEnabled: !_isCloseService,
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: 4.w),
                              child: Icon(
                                Icons.arrow_forward,
                                color: Colors.grey.shade400,
                                size: 5.w,
                              ),
                            ),
                            Expanded(
                              child: CustomTimePicker(
                                label: "Jam Tutup",
                                time: _onlineCloseTime,
                                onTap: () => _selectTime(false),
                                isEnabled: !_isCloseService,
                              ),
                            ),
                          ],
                        ),

                        SizedBox(height: 0.75.h),

                        Divider(color: Colors.grey.withOpacity(0.15)),

                        Text(
                          "Tutup Layanan Toko Online Sekarang",
                          style: TextStyle(
                            fontSize: isTablet
                                ? AppFontSize.medium.sp
                                : AppFontSize.small.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.black87,
                          ),
                        ),

                        SizedBox(height: 0.75.h),

                        SizedBox(
                          width: 10.w,
                          child: FittedBox(
                            fit: BoxFit.fill,
                            child: Switch(
                              value: _isCloseService,
                              onChanged: (_) {
                                setState(() {
                                  _isCloseService = !_isCloseService;
                                });
                              },
                              activeColor: _isCloseService
                                  ? AppColor.primaryColor
                                  : Colors.grey,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  SizedBox(height: 3.h),

                  CustomSelector(
                    isTablet: isTablet,
                    title: selectedOnlineStoreProductState.values.isEmpty
                        ? "Atur produk yang tampil di toko online"
                        : "Lihat ${selectedOnlineStoreProductState.values.length} produk toko online",
                    padding: EdgeInsets.symmetric(
                      horizontal: 4.w,
                      vertical: 2.h,
                    ),
                    fontSize: isTablet
                        ? AppFontSize.medium.sp
                        : AppFontSize.small.sp,
                    onTap: () {
                      context.pushNamed(AppRoute.onlineStoreProductScreen);
                    },
                  ),

                  SizedBox(height: 2.h),

                  CustomTextFormField(
                    label: "Waktu Mempersiapakan Pesanan (Menit)",
                    hint: "Contoh: 15",
                    suffixText: "Menit",
                    controller: _prepTimeController,
                    keyboardType: TextInputType.number,
                    validator: (value) {
                      if (value != null && value.isNotEmpty) {
                        if (int.tryParse(value) == null) {
                          return "Waktu persiapan tidak valid";
                        }
                      }
                      return null;
                    },
                  ),

                  SizedBox(height: 2.h),

                  CustomTextFormField(
                    label: "Jeda Waktu Pesanan Selanjutnya (Menit)",
                    hint: "Contoh: 15",
                    suffixText: "Menit",
                    controller: _gapTimeController,
                    keyboardType: TextInputType.number,
                    validator: (value) {
                      if (value != null && value.isNotEmpty) {
                        if (int.tryParse(value) == null) {
                          return "Jeda waktu tidak valid";
                        }
                      }
                      return null;
                    },
                  ),

                  SizedBox(height: 5.h),

                  ElevatedButton(
                    onPressed: onlineStoreControllerState.isLoading
                        ? null
                        : _saveConfigureOnlineStore,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColor.primaryColor,
                      minimumSize: Size(double.infinity, 7.h),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(3.w),
                      ),
                      disabledBackgroundColor: Colors.grey.shade300,
                    ),
                    child: Text(
                      "Simpan Perubahan",
                      style: TextStyle(
                        fontSize: AppFontSize.medium.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
