import 'dart:ffi';

import 'package:cims_apps/application/assets/path_assets.dart';
import 'package:cims_apps/application/component/button/button_view.dart';
import 'package:cims_apps/application/component/custom_app_bar/custom_app_bar.dart';
import 'package:cims_apps/application/component/modal_redirect_app.dart';
import 'package:cims_apps/application/component/success_view.dart';
import 'package:cims_apps/application/theme/color_palette.dart';
import 'package:cims_apps/core/route/route.dart';
import 'package:cims_apps/core/utils/number_formatter.dart';
import 'package:cims_apps/core/utils/size_config.dart';
import 'package:cims_apps/features/bottom_navigation_view.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Payment {
  String name;
  int fee;
  double? discount;

  Payment({required this.name, required this.fee, this.discount = 1});
}

class PaymentMethodView extends StatefulWidget {
  final int totalInvest;
  const PaymentMethodView({super.key, required this.totalInvest });

  @override
  State<PaymentMethodView> createState() => _PaymentMethodViewState();
}

class _PaymentMethodViewState extends State<PaymentMethodView> {
  int selectedPayment = 0;
  Payment currentPayment = Payment(name: 'Wallet Pay', fee: 2500);
  List<Payment> listInstantPayment = [
    Payment(name: 'Wallet Pay', fee: 2500),
    Payment(name: 'Link Start', fee: 2500),
    Payment(name: 'Shopping Pay', fee: 2500, discount: 0.5),
    Payment(name: 'Fund', fee: 2500, discount: 0.2)
  ];

  List<Payment> listTransferBank = [
    Payment(name: 'BCA', fee: 2500),
    Payment(name: 'Bank Republik Indonesia', fee: 2500)
  ];

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: const CustomAppBar(
        height: 70,
        title: 'Payment Method'
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
        child: Column(
          children: [
            segmentTitle(Icons.bolt_rounded, 'Instant Payment'),
            Wrap(
              runSpacing: 16,
              children: listInstantPayment.asMap().entries.map((e) {
                return cardPayment(e.value, e.key);
              }).toList(),
            ),
            const SizedBox(height: 8),
            segmentTitle(Icons.account_balance_outlined, 'Transfer Bank'),
            Wrap(
              runSpacing: 16,
              children: listTransferBank.asMap().entries.map((e) {
                return cardPayment(e.value, e.key + (listInstantPayment.length));
              }).toList(),
            ),
            SizedBox(height: 16,)
          ],
        ),
      ),
      bottomNavigationBar: Container(
        padding: const EdgeInsets.all(24),
        child: segmentBottom(currentPayment)
      ),
    );
  }

  Widget segmentTitle(IconData? icon, String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Row(
        children: [
          Icon(icon, color: ColorPalette.primary),
          const SizedBox(width: 8),
          Text(title,
            style: const TextStyle(
                color: ColorPalette.slate800,
                fontWeight: FontWeight.w600,
                fontSize: 16
            ),
          )
        ],
      ),
    );
  }

  Widget cardPayment(Payment value, int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          selectedPayment = index;
          currentPayment = value;
        });
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(14),
          border: Border.all(color: selectedPayment == index ? ColorPalette.primary : ColorPalette.slate200)
        ),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(value.name,
                          style: const TextStyle(
                            fontSize: 16
                          ),
                        ),
                        RichText(
                          text: TextSpan(
                              text: 'Payment fee ',
                              style: const TextStyle(
                                fontFamily: 'Manrope',
                                color: ColorPalette.slate400,
                              ),
                              children: [
                                TextSpan(
                                  text: '${NumberFormatter.numberCurrency(value.fee, 'Rp ', 'id_ID', decimalDigits: 0)} ',
                                  style: TextStyle(
                                    decoration: value.discount != 1 ? TextDecoration.lineThrough : TextDecoration.none,
                                    fontFamily: 'Manrope',
                                    color: ColorPalette.slate400,
                                  ),
                                ),
                                if(value.discount != 1)...[
                                  TextSpan(
                                    text: value.discount == 0 ? 'Free' : NumberFormatter.numberCurrency(value.fee * value.discount!, 'Rp ', 'id_ID', decimalDigits: 0),
                                    style: const TextStyle(
                                      fontFamily: 'Manrope',
                                      color: ColorPalette.primary,
                                    ),
                                  )
                                ]
                              ]
                          )
                        )
                      ],
                    )
                  ],
                ),
                AnimatedContainer(
                  duration: const Duration(milliseconds: 200),
                  width: 16,
                  height: 16,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: selectedPayment == index ? ColorPalette.primary : Colors.white,
                    border: Border.all(color: selectedPayment == index ? ColorPalette.primary : ColorPalette.slate200, width: 1.5)
                  ),
                  child: const Icon(Icons.done_rounded, color: Colors.white, size: 12),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget segmentBottom(Payment currentPayment) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        rowTotal('Total Invest', widget.totalInvest),
        rowTotal('Payment Fee', (currentPayment.fee * currentPayment.discount!).toInt()),
        Row(
          children: [
            Expanded(child: Divider(color: ColorPalette.slate200, height: 1,)),
            Icon(Icons.add, size: 10,)
          ],
        ),
        rowTotal('Total Payment', widget.totalInvest + (currentPayment.fee * currentPayment.discount!).toInt()),
        SizedBox(height: 24),
        ButtonView(
          name: 'Buy',
          textSize: 18,
          marginVertical: 0,
          width: SizeConfig.width,
          heightWrapContent: true,
          contentPadding: EdgeInsets.symmetric(vertical: 16),
          onPressed: () {
            List<String> redirect = ['Shopping Pay'];
            if(redirect.contains(currentPayment.name)){
              showModalBottomSheet(
                context: context,
                builder: (context) {
                  return ModalRedirectApp(value: currentPayment.name);
                },
              );
            }
            routePush(context, page: SuccessView(
              img: PathAssets.imgPaymentSuccess,
              textTitle: 'Payment Success!',
              subtitle: RichText(
                  text: TextSpan(
                      text: 'Payment With ',
                      style: TextStyle(
                        fontFamily: 'Manrope',
                        fontWeight: FontWeight.w600,
                        fontSize: 16,
                        color: ColorPalette.slate500
                      ),
                      children: [
                        TextSpan(
                            text: currentPayment.name,
                            style: TextStyle(
                              fontFamily: 'Manrope',
                              fontWeight: FontWeight.w700,
                              fontSize: 16,
                              color: ColorPalette.slate800
                            )
                        ),
                        TextSpan(
                            text: ' successful',
                            style: TextStyle(
                              fontFamily: 'Manrope',
                              fontWeight: FontWeight.w600,
                              fontSize: 16,
                              color: ColorPalette.slate500
                            )
                        )
                      ]
                  )
              ),
              nextRoute: () {
                routePush(context, page: BottomNavigationView(), routeType: RouteType.pushRemove);
              },
            ));
          },
        )
      ],
    );
  }

  Widget rowTotal(String title, int value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(title,
          style: const TextStyle(
            fontWeight: FontWeight.w600,
            color: ColorPalette.slate500,
            fontSize: 16
          ),
        ),
        Text(NumberFormatter.numberCurrency(value, 'Rp', 'id_ID', decimalDigits: 0),
          style: const TextStyle(
            fontWeight: FontWeight.w700,
            color: ColorPalette.slate800,
            fontSize: 16
          ),
        )
      ],
    );
  }
}
