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_asset.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/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 PaymentMethodsScreen extends ConsumerStatefulWidget {
  final List<ConfigurePaymentMethod> configures;
  const PaymentMethodsScreen({super.key, required this.configures});

  @override
  ConsumerState<PaymentMethodsScreen> createState() =>
      _PaymentMethodsScreenState();
}

class _PaymentMethodsScreenState extends ConsumerState<PaymentMethodsScreen> {
  final Map<String, Map<String, dynamic>> _controllers = {
    "dana": {
      "id": null,
      "no": TextEditingController(),
      "name": TextEditingController(),
    },
    "gopay": {
      "id": null,
      "no": TextEditingController(),
      "name": TextEditingController(),
    },
    "shopeepay": {
      "id": null,
      "no": TextEditingController(),
      "name": TextEditingController(),
    },
    "bri": {
      "id": null,
      "no": TextEditingController(),
      "name": TextEditingController(),
    },
    "mandiri": {
      "id": null,
      "no": TextEditingController(),
      "name": TextEditingController(),
    },
    "bni": {
      "id": null,
      "no": TextEditingController(),
      "name": TextEditingController(),
    },
    "bca": {
      "id": null,
      "no": TextEditingController(),
      "name": TextEditingController(),
    },
    "custom": {
      "id": null,
      "source": TextEditingController(),
      "no": TextEditingController(),
      "name": TextEditingController(),
    },
  };

  bool _isButtonEnabled = false;

  String _expandedSection = "";

  @override
  void initState() {
    super.initState();
    for (final group in _controllers.values) {
      for (final controller in group.values) {
        if (controller is TextEditingController) {
          controller.addListener(_validateForm);
        }
      }
    }

    _fetchConfiguration();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    for (final group in _controllers.values) {
      for (final controller in group.values) {
        if (controller is TextEditingController) {
          controller.dispose();
        }
      }
    }
    super.dispose();
  }

  void _fetchConfiguration() {
    final configures = widget.configures;

    final List<String> keys = [
      "dana",
      "gopay",
      "shopeepay",
      "bri",
      "mandiri",
      "bni",
      "bca",
    ];

    if (configures.isNotEmpty) {
      for (final configure in configures) {
        final sourceName = configure.sourceName;

        final accountNumber = configure.accountNumber;

        final receipentName = configure.receipentName;

        final hasData =
            sourceName.isNotEmpty &&
            accountNumber.isNotEmpty &&
            receipentName.isNotEmpty;

        final String key = keys.contains(sourceName) ? sourceName : "custom";

        _controllers[key]!["id"] = configure.localId;

        if (hasData) {
          if (keys.contains(sourceName)) {
            _controllers[sourceName]!["no"]!.text = accountNumber;
            _controllers[sourceName]!["name"]!.text = receipentName;
          } else {
            _controllers["custom"]!["id"] = configure.localId;
            _controllers["custom"]!["source"]!.text = sourceName.capitalize();
            _controllers["custom"]!["no"]!.text = accountNumber;
            _controllers["custom"]!["name"]!.text = receipentName;
          }
        }
      }
    }
  }

  void _validateForm() {
    bool hasAtLeastOneComplete = false;
    bool hasIncompleteEntry = false;

    _controllers.forEach((key, value) {
      if (key == "custom") {
        final bool s = value["source"]!.text.isNotEmpty;
        final bool n = value["no"]!.text.isNotEmpty;
        final bool p = value["name"]!.text.isNotEmpty;

        if ((s || n || p) && !(s && n && p)) {
          hasIncompleteEntry = true;
        }

        if (s && n && p) {
          hasAtLeastOneComplete = true;
        }
      } else {
        final bool n = value["no"]!.text.isNotEmpty;
        final bool p = value["name"]!.text.isNotEmpty;

        if ((n || p) && !(n && p)) {
          hasIncompleteEntry = true;
        }
        if (n && p) {
          hasAtLeastOneComplete = true;
        }
      }
    });
    final bool finalStatus = hasAtLeastOneComplete && !hasIncompleteEntry;

    if (_isButtonEnabled != finalStatus) {
      setState(() {
        _isButtonEnabled = finalStatus;
      });
    }
  }

  String? _getErrorText(String key, String value) {
    final fields = _controllers[key]!;

    if (key == "custom") {
      final bool s = fields["source"]!.text.isNotEmpty;
      final bool n = fields["no"]!.text.isNotEmpty;
      final bool p = fields["name"]!.text.isNotEmpty;

      if (fields[value] is TextEditingController) {
        if ((s || n || p) && fields[value]!.text.isEmpty) {
          return "Kolom ini belum diisi";
        }
      }
    } else {
      final bool n = fields["no"]!.text.isNotEmpty;
      final bool p = fields["name"]!.text.isNotEmpty;

      if (fields[value] is TextEditingController) {
        if ((n || p) && !fields[value]!.text.isNotEmpty) {
          return "Kolom ini belum diisi";
        }
      }
    }
    return null;
  }

  Future<void> _configurePaymentMethod() async {
    String? key;

    final List<ConfigurePaymentMethod> configures = [];

    for (final controller in _controllers.entries) {
      final firstKey = controller.key;

      final values = controller.value;

      for (final value in values.entries) {
        final secondKey = value.key;

        final String? errorText = _getErrorText(firstKey, secondKey);

        if (errorText != null) {
          key = firstKey;
          break;
        }
      }
      configures.add(
        ConfigurePaymentMethod(
          localId: values["id"]?.toString(),
          sourceName: firstKey == "custom"
              ? values["source"]!.text.toLowerCase()
              : firstKey,
          accountNumber: values["no"]!.text,
          receipentName: values["name"]!.text,
        ),
      );
    }

    if (key != null) {
      setState(() {
        if (key == 'dana' || key == 'gopay' || key == 'shopeepay') {
          _expandedSection = "ewallet";
        } else if (key == 'bri' ||
            key == 'mandiri' ||
            key == 'bni' ||
            key == 'bca') {
          _expandedSection = "bank";
        } else {
          _expandedSection = "custom";
        }
      });
      return;
    }

    if (!_isButtonEnabled) {
      CustomSnackbar.showError(context, "Tambah minimal 1 metode pembayaran");
      return;
    }

    try {
      await ref
          .read(onlineStoreControllerProvider.notifier)
          .paymentMethodConfiguration(configures);

      if (!mounted) return;

      CustomSnackbar.showSuccess(
        context,
        "Metode pembayaran 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(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Stack(
            children: [
              Scaffold(
                backgroundColor: const Color(0xFFF9FAFB),
                appBar: TopBackBarApp(
                  title: "Atur Rekening/E-Wallet",
                  onTap: () => Navigator.pop(context),
                ),
                body: SingleChildScrollView(
                  padding: EdgeInsets.all(5.w),
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.all(4.w),
                        decoration: BoxDecoration(
                          color: Colors.amber.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(3.w),
                          border: Border.all(color: Colors.amber.shade300),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Icon(
                              Icons.info_outline_rounded,
                              color: Colors.amber.shade800,
                              size: 6.w,
                            ),
                            SizedBox(width: 3.w),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    "Informasi Verifikasi Manual",
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: isTablet
                                          ? AppFontSize.medium.sp
                                          : AppFontSize.small.sp,
                                      color: Colors.amber.shade900,
                                    ),
                                  ),
                                  SizedBox(height: 0.5.h),
                                  Text(
                                    "Pembayaran yang diterima melalui metode di bawah akan masuk langsung ke rekening/akun pribadi Anda. Harap lakukan pengecekan mutasi secara manual sebelum memproses pesanan.",
                                    style: TextStyle(
                                      fontSize: isTablet
                                          ? (AppFontSize.medium - 1.25).sp
                                          : (AppFontSize.small - 1.25).sp,
                                      color: Colors.amber.shade900,
                                      height: 1.4,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 3.h),

                      _buildExpandableSection(
                        title: "E-Wallet",
                        icon: Icons.account_balance_wallet_outlined,
                        isExpanded: _expandedSection == "ewallet",
                        onTap: () => setState(
                          () => _expandedSection = _expandedSection == "ewallet"
                              ? ""
                              : "ewallet",
                        ),
                        children: [
                          _buildPaymentItem(
                            _controllers['dana']!['no']!,
                            _controllers['dana']!['name']!,
                            _getErrorText('dana', 'no'),
                            _getErrorText('dana', 'name'),
                            isTablet,
                            "DANA",
                            AppAsset.DANA_LOGO,
                            isEwallet: true,
                          ),
                          _buildPaymentItem(
                            _controllers['gopay']!['no']!,
                            _controllers['gopay']!['name']!,
                            _getErrorText('gopay', 'no'),
                            _getErrorText('gopay', 'name'),
                            isTablet,
                            "GoPay",
                            AppAsset.GOPAY_LOGO,
                            isEwallet: true,
                          ),
                          _buildPaymentItem(
                            _controllers['shopeepay']!['no']!,
                            _controllers['shopeepay']!['name']!,
                            _getErrorText('shopeepay', 'no'),
                            _getErrorText('shopeepay', 'name'),
                            isTablet,
                            "ShopeePay",
                            AppAsset.SHOPEEPAY_LOGO,
                            isEwallet: true,
                          ),
                        ],
                      ),

                      SizedBox(height: 2.h),

                      _buildExpandableSection(
                        title: "Rekening Bank",
                        icon: Icons.account_balance_outlined,
                        isExpanded: _expandedSection == "bank",
                        onTap: () => setState(
                          () => _expandedSection = _expandedSection == "bank"
                              ? ""
                              : "bank",
                        ),
                        children: [
                          _buildPaymentItem(
                            _controllers['bri']!['no']!,
                            _controllers['bri']!['name']!,
                            _getErrorText('bri', 'no'),
                            _getErrorText('bri', 'name'),
                            isTablet,
                            "Bank BRI",
                            AppAsset.BRI_LOGO,
                          ),
                          _buildPaymentItem(
                            _controllers['mandiri']!['no']!,
                            _controllers['mandiri']!['name']!,
                            _getErrorText('mandiri', 'no'),
                            _getErrorText('mandiri', 'name'),
                            isTablet,
                            "Bank Mandiri",
                            AppAsset.MANDIRI_LOGO,
                          ),
                          _buildPaymentItem(
                            _controllers['bni']!['no']!,
                            _controllers['bni']!['name']!,
                            _getErrorText('bni', 'no'),
                            _getErrorText('bni', 'name'),
                            isTablet,
                            "Bank BNI",
                            AppAsset.BNI_LOGO,
                          ),
                          _buildPaymentItem(
                            _controllers['bca']!['no']!,
                            _controllers['bca']!['name']!,
                            _getErrorText('bca', 'no'),
                            _getErrorText('bca', 'name'),
                            isTablet,
                            "Bank BCA",
                            AppAsset.BCA_LOGO,
                          ),
                        ],
                      ),

                      SizedBox(height: 2.h),

                      _buildExpandableSection(
                        title: "Pembayaran Lain",
                        icon: Icons.add_card_outlined,
                        isExpanded: _expandedSection == "custom",
                        onTap: () => setState(
                          () => _expandedSection = _expandedSection == "custom"
                              ? ""
                              : "custom",
                        ),
                        children: [
                          _buildCustomForm(
                            _controllers['custom']!['source']!,
                            _controllers['custom']!['no']!,
                            _controllers['custom']!['name']!,
                            _getErrorText('custom', 'source'),
                            _getErrorText('custom', 'no'),
                            _getErrorText('custom', 'name'),
                          ),
                        ],
                      ),

                      SizedBox(height: 5.h),
                      ElevatedButton(
                        onPressed: onlineStoreControllerState.isLoading
                            ? null
                            : _configurePaymentMethod,
                        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 Metode Pembayaran",
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: AppFontSize.medium.sp,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildExpandableSection({
    required String title,
    required IconData icon,
    required bool isExpanded,
    required VoidCallback onTap,
    required List<Widget> children,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(3.w),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Column(
        children: [
          ListTile(
            onTap: onTap,
            leading: Icon(icon, color: AppColor.primaryColor),
            title: Text(
              title,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: AppFontSize.medium.sp,
              ),
            ),
            trailing: Icon(
              isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
              size: 5.w,
            ),
          ),
          if (isExpanded) ...[
            const Divider(height: 1),
            Padding(
              padding: EdgeInsets.all(4.w),
              child: Column(children: children),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildPaymentItem(
    TextEditingController accountController,
    TextEditingController nameController,
    String? errorAccountText,
    String? errorNameText,
    bool isTablet,
    String name,
    String assetPath, {
    bool isEwallet = false,
  }) {
    return Padding(
      padding: EdgeInsets.only(bottom: 2.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Image.asset(assetPath, width: 7.w, fit: BoxFit.contain),
              SizedBox(width: 3.w),
              Text(
                name,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: isTablet
                      ? (AppFontSize.medium - 1.25).sp
                      : (AppFontSize.small - 1.25).sp,
                ),
              ),
            ],
          ),
          SizedBox(height: 1.5.h),
          CustomTextFormField(
            label: "Nomor ${isEwallet ? 'Akun' : 'Rekening'}",
            hint: "Contoh: ${isEwallet ? '081234567890' : '0081236785'}",
            controller: accountController,
            prefixIcon: Icons.numbers,
            errorText: errorAccountText,
          ),
          SizedBox(height: 1.h),
          CustomTextFormField(
            label: "Nama Penerima",
            hint: "Isi penerima",
            controller: nameController,
            prefixIcon: Icons.person_outline,
            errorText: errorNameText,
          ),
        ],
      ),
    );
  }

  Widget _buildCustomForm(
    TextEditingController sourceController,
    TextEditingController accountController,
    TextEditingController nameController,
    String? errorSourceText,
    String? errorAccountText,
    String? errorNameText,
  ) {
    return Column(
      children: [
        CustomTextFormField(
          label: "Sumber Pembayaran",
          hint: "Contoh: Bank BSI/OVO",
          controller: sourceController,
          prefixIcon: Icons.source_outlined,
          errorText: errorSourceText,
        ),
        SizedBox(height: 1.5.h),
        CustomTextFormField(
          label: "Nomor Rekening / Akun",
          hint: "Contoh: 0081236785",
          controller: accountController,
          prefixIcon: Icons.numbers,
          errorText: errorAccountText,
        ),
        SizedBox(height: 1.5.h),
        CustomTextFormField(
          label: "Nama Penerima",
          hint: "Isi penerima",
          controller: nameController,
          prefixIcon: Icons.person_outline,
          errorText: errorNameText,
        ),
      ],
    );
  }
}
