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/enums/delivery_fee_type.dart';
import 'package:niogu_app/core/utils/extension_format.dart';
import 'package:niogu_app/core/utils/log_message.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/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 ShippingConfigurationScreen extends ConsumerStatefulWidget {
  final ShippingConfiguration configuration;
  const ShippingConfigurationScreen({super.key, required this.configuration});

  @override
  ConsumerState<ShippingConfigurationScreen> createState() =>
      _ShippingConfigurationScreenState();
}

class _ShippingConfigurationScreenState
    extends ConsumerState<ShippingConfigurationScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey();

  final TextEditingController _maxRadiusDeliveryKmController =
      TextEditingController();

  final TextEditingController _deliveryFeeController = TextEditingController();

  final TextEditingController _deliveryBaseFeeController =
      TextEditingController();

  bool _allowCOD = true;

  DeliveryFeeType _deliveryFeeType = DeliveryFeeType.fixed;

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

    final configuration = widget.configuration;

    _allowCOD = configuration.allowCOD;

    if (configuration.maxDeliveryRadiusKm > 0) {
      _maxRadiusDeliveryKmController.text = configuration.maxDeliveryRadiusKm
          .toStringWithoutTrailingZero();
    }

    _deliveryFeeType = configuration.deliveryFeeType;

    final double deliveryFee = _deliveryFeeType == DeliveryFeeType.fixed
        ? configuration.deliveryFlatFee
        : configuration.deliveryFeePerKm;

    if (deliveryFee > 0) {
      _deliveryFeeController.text = deliveryFee.toStringWithoutTrailingZero();
    }

    final double deliveryBaseFee = _deliveryFeeType == DeliveryFeeType.fixed
        ? configuration.deliveryFlatFee
        : configuration.deliveryBaseFee;

    if (deliveryBaseFee > 0) {
      _deliveryBaseFeeController.text = deliveryBaseFee
          .toStringWithoutTrailingZero();
    }
  }

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

  String? _validator({
    String? value,
    required String message1,
    required String message2,
    required String message3,
    bool isReadOnly = false,
  }) {
    if (isReadOnly) return null;

    if (value == null || value.isEmpty) {
      return message1;
    }

    if (double.tryParse(value) == null) {
      return message2;
    }

    if (double.parse(value) <= 0) {
      return message3;
    }

    return null;
  }

  Future<void> _shippingConfigureation() async {
    if (!_formKey.currentState!.validate()) return;

    final maxDeliveryRadiusKm = double.parse(
      _maxRadiusDeliveryKmController.text.trim(),
    );

    final deliveryFlatFee = _deliveryFeeType == DeliveryFeeType.fixed
        ? double.parse(_deliveryFeeController.text.trim())
        : 0.0;

    final deliveryFeePerKm = _deliveryFeeType == DeliveryFeeType.per_km
        ? double.parse(_deliveryFeeController.text.trim())
        : 0.0;

    final deliveryBaseFee = _deliveryFeeType == DeliveryFeeType.per_km
        ? double.parse(_deliveryBaseFeeController.text.trim())
        : 0.0;

    final configure = ShippingConfiguration(
      allowCOD: _allowCOD,
      deliveryFeeType: _deliveryFeeType,
      maxDeliveryRadiusKm: maxDeliveryRadiusKm,
      deliveryFlatFee: deliveryFlatFee,
      deliveryFeePerKm: deliveryFeePerKm,
      deliveryBaseFee: deliveryBaseFee,
    );

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

      if (!mounted) false;

      CustomSnackbar.showSuccess(
        context,
        "Biaya pengiriman 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 onlineStoreControllerState = ref.watch(
          onlineStoreControllerProvider,
        );

        return SafeArea(
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: TopBackBarApp(
              title: "Atur Biaya Pengiriman",
              onTap: () => context.pop(),
            ),
            body: SingleChildScrollView(
              padding: EdgeInsets.all(5.w),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.all(4.w),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(3.w),
                        border: Border.all(color: Colors.grey.shade200),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Icon(
                                Icons.payments_outlined,
                                color: AppColor.primaryColor,
                                size: 6.w,
                              ),
                              SizedBox(width: 3.w),
                              Text(
                                "Izinkan Pesanan COD",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: isTablet
                                      ? AppFontSize.medium.sp
                                      : AppFontSize.small.sp,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            width: 10.w,
                            child: FittedBox(
                              fit: BoxFit.fill,
                              child: Switch(
                                value: _allowCOD,
                                onChanged: (_) {
                                  setState(() {
                                    _allowCOD = !_allowCOD;
                                  });
                                },
                                activeColor: _allowCOD
                                    ? AppColor.primaryColor
                                    : Colors.grey,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    SizedBox(height: 3.h),

                    Padding(
                      padding: EdgeInsets.only(left: 1.w, bottom: 1.5.h),
                      child: Text(
                        "Metode & Biaya Pengiriman",
                        style: TextStyle(
                          fontSize: isTablet
                              ? AppFontSize.medium.sp
                              : AppFontSize.small.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ),

                    Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(3.w),
                        border: Border.all(color: Colors.grey.shade200),
                      ),
                      child: Column(
                        children: [
                          _buildMethodTile(
                            isTablet,
                            "Biaya Pengiriman Tetap",
                            DeliveryFeeType.fixed,
                          ),
                          const Divider(height: 1),
                          _buildMethodTile(
                            isTablet,
                            "Biaya Pengiriman Per Km",
                            DeliveryFeeType.per_km,
                          ),
                        ],
                      ),
                    ),

                    SizedBox(height: 3.h),
                    CustomTextFormField(
                      label: "Radius Jarak Pengiriman (Km)",
                      hint: "Contoh: 10",
                      addInformation:
                          "Radius jarak pengiriman dari lokasi outlet dalam km",
                      controller: _maxRadiusDeliveryKmController,
                      suffixText: "/ Km",
                      keyboardType: TextInputType.number,
                      validator: (value) {
                        return _validator(
                          value: value,
                          message1: "Radius tidak belum diisi",
                          message2: "Radius tidak valid",
                          message3: "Radius harus lebih dari 0 km",
                        );
                      },
                    ),
                    SizedBox(height: 2.h),
                    CustomTextFormField(
                      label: _deliveryFeeType == DeliveryFeeType.fixed
                          ? "Biaya Pengiriman Tetap"
                          : "Biaya Pengiriman Per Km",
                      hint: "Contoh: 7.000",
                      controller: _deliveryFeeController,
                      suffixText: _deliveryFeeType == DeliveryFeeType.per_km
                          ? "/ Km"
                          : null,
                      keyboardType: TextInputType.number,
                      validator: (value) {
                        return _validator(
                          value: value,
                          message1: "Biaya pengiriman belum diisi",
                          message2: "Biaya pengiriman tidak valid",
                          message3: "Biaya pengiriman harus lebih dari 0",
                        );
                      },
                    ),
                    SizedBox(height: 2.h),
                    CustomTextFormField(
                      label: "Biaya Pengiriman Jarak < 1Km",
                      hint: "Contoh: 2.000",
                      controller: _deliveryFeeType == DeliveryFeeType.per_km
                          ? _deliveryBaseFeeController
                          : _deliveryFeeController,
                      keyboardType: TextInputType.number,
                      readOnly: _deliveryFeeType == DeliveryFeeType.fixed,
                      validator: (value) {
                        return _validator(
                          value: value,
                          message1: "Biaya pengiriman belum diisi",
                          message2: "Biaya pengiriman tidak valid",
                          message3: "Biaya pengiriman harus lebih dari 0",
                          isReadOnly: _deliveryFeeType == DeliveryFeeType.fixed,
                        );
                      },
                    ),
                    SizedBox(height: 5.h),

                    ElevatedButton(
                      onPressed: onlineStoreControllerState.isLoading
                          ? null
                          : _shippingConfigureation,
                      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 Pengaturan",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: AppFontSize.medium.sp,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildMethodTile(
    bool isTablet,
    String title,
    DeliveryFeeType deliveryFeeType,
  ) {
    bool isSelected = _deliveryFeeType == deliveryFeeType;
    return InkWell(
      onTap: () => setState(() => _deliveryFeeType = deliveryFeeType),
      child: Padding(
        padding: EdgeInsets.all(4.w),
        child: Row(
          children: [
            Icon(
              isSelected ? Icons.radio_button_checked : Icons.radio_button_off,
              color: isSelected ? AppColor.primaryColor : Colors.grey,
              size: 5.w,
            ),
            SizedBox(width: 3.w),
            Text(
              title,
              style: TextStyle(
                fontSize: isTablet
                    ? AppFontSize.medium.sp
                    : AppFontSize.small.sp,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
