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/image/image_view.dart';
import 'package:cims_apps/application/component/text_form/text_form_view.dart';
import 'package:cims_apps/application/component/text_title/text_title.dart';
import 'package:cims_apps/application/theme/color_palette.dart';
import 'package:cims_apps/core/utils/number_formatter.dart';
import 'package:cims_apps/core/utils/size_config.dart';
import 'package:cims_apps/features/dashboard/dashboard_account/view/portfolio/redeem_product/view/change_amount.dart';
import 'package:cims_apps/features/dashboard/dashboard_account/view/portfolio/redeem_product/view/change_destination_account.dart';
import 'package:cims_apps/features/dashboard/dashboard_account/view/portfolio/redeem_product/view/total_redeem.dart';
import 'package:cims_apps/features/dashboard/dashboard_account/view/portfolio/redeem_product/view_model/redeem_product_view_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class RedeemProduct extends StatefulWidget {
  const RedeemProduct({super.key});

  @override
  State<RedeemProduct> createState() => _RedeemProductState();
}

class _RedeemProductState extends State<RedeemProduct> {
  TextEditingController amountController = TextEditingController();

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

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

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => RedeemProductViewModel(),
      child: Consumer<RedeemProductViewModel>(
        builder: (context, provider, child) {
          amountController.text = NumberFormatter.numberCurrency(provider.getAmount!.toInt(), 'Rp ', 'id_ID', decimalDigits: 0);
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text('Products to be Redeemed',
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                        color: ColorPalette.slate800,
                        fontSize: 16
                      ),
                    ),
                    GestureDetector(
                      onTap: () => Navigator.pop(context),
                      child: const Icon(Icons.close_rounded, color: ColorPalette.slate800,)
                    )
                  ],
                ),
              ),
              const Divider(height: 1, color: ColorPalette.slate200,),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    cardProduct(),
                    const SizedBox(height: 16),
                    segmentAmount(
                      context,
                      provider.getAmount!,
                      provider.getUnit!,
                      (value) {
                        provider.setUnit(value);
                      },
                    ),
                    const SizedBox(height: 16),
                    segmentDestinationAcc(provider.getCurrentAccount),
                    const SizedBox(height: 36),
                    ButtonView(
                      name: 'Redeem',
                      textSize: 20,
                      marginVertical: 0,
                      onPressed: () {
                        Navigator.pop(context);
                        showModalBottomSheet(
                          context: context,
                          isScrollControlled: true,
                          builder: (context) {
                            return TotalRedeem();
                          },
                        );
                      },
                    ),
                    const SizedBox(height: 16)
                  ],
                ),
              )
            ],
          );
        }
      ),
    );
  }

  Widget cardProduct() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: ColorPalette.slate200),
          boxShadow: [
            BoxShadow(
                color: const Color(0xff1E293B).withOpacity(0.04),
                blurRadius: 8,
                spreadRadius: 2
            )
          ]
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ImageView(
            image: PathAssets.imgProduct,
            width: SizeConfig.width * .13,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const TextTitle(title: 'Gemilang Dana Kas Maxima', fontSize: 16,),
                const SizedBox(height: 4),
                Container(
                  padding: const EdgeInsets.all(6),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(40),
                      color: ColorPalette.investTypeBgColor['Money Market']?.withOpacity(0.5) ?? Colors.white,
                      border: Border.all(width: 2, color: ColorPalette.investTypeColor['Money Market']?.withOpacity(0.4) ?? Colors.white)
                  ),
                  child: Text(
                    'Money Market' ?? '',
                    style: TextStyle(
                        color: ColorPalette.investTypeColor['Money Market'],
                        fontWeight: FontWeight.w600
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget segmentAmount(context, double currentAmount, double currentUnit, void Function(double value) setUnit) {
    double sliderValue = currentUnit / Provider.of<RedeemProductViewModel>(context, listen: false).getCurrentProduct.totalUnit!;
    return Column(
      children: [
        const Align(
          alignment: Alignment.centerLeft,
          child: Text('Amount',
            style: TextStyle(
              fontWeight: FontWeight.w600,
              color: ColorPalette.slate800,
              fontSize: 16
            ),
          ),
        ),
        TextField(
          controller: amountController,
          textAlign: TextAlign.center,
          style: const TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.w700,
              color: ColorPalette.slate800
          ),
          keyboardType: TextInputType.number,
          readOnly: true,
          decoration: InputDecoration(
            enabledBorder: const UnderlineInputBorder(
              borderSide: BorderSide(
                  color: ColorPalette.slate200,
                  width: 1
              ),
            ),
            suffixIcon: GestureDetector(
              onTap: () {
                Navigator.pop(context);
                showModalBottomSheet(
                  context: context,
                  isScrollControlled: true,
                  builder: (context) {
                    return ChangeAmount(
                      totalAmount: currentAmount.toInt(),
                    );
                  },
                );
              },
              child: const Icon(Icons.edit, color: ColorPalette.primary),
            )
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 20),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(currentUnit.toStringAsFixed(2).replaceAll('.', ','),
                style: const TextStyle(
                  fontWeight: FontWeight.w700,
                  fontSize: 18,
                  color: ColorPalette.slate800
                ),
              ),
              const Text(' unit',
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                  color: ColorPalette.slate400
                ),
              )
            ],
          ),
        ),
        Row(
          children: [
            Expanded(
              child: SliderTheme(
                data: SliderTheme.of(context).copyWith(
                  trackHeight: 4.0,
                  thumbColor: ColorPalette.primary,
                  thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 10.0),
                  overlayColor:Colors.deepPurple,
                  inactiveTickMarkColor: ColorPalette.primary,
                  inactiveTrackColor: ColorPalette.slate200,
                  overlayShape: SliderComponentShape.noOverlay
                ),
                child: Slider(
                  value: sliderValue,
                  onChanged: setUnit,
                  label: sliderValue.round().toString(),
                ),
              ),
            ),
            SizedBox(width: 12),
            Text('${(sliderValue * 100).toStringAsFixed(2)} %',
              style: const TextStyle(
                color: ColorPalette.slate800,
                fontWeight: FontWeight.w600
              ),
            )
          ],
        )
      ],
    );
  }

  Widget segmentDestinationAcc(Account account) {
    List<String> listNumber = [];

    List.generate(account.number.length, (index) {
      if(index > 3 && index < account.number.length - 4){
        listNumber.add('*');
      }else{
        listNumber.add(account.number[index]);
      }
    });

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('Destination Account',
          style: TextStyle(
              fontWeight: FontWeight.w600,
              color: ColorPalette.slate800,
              fontSize: 16
          ),
        ),
        const SizedBox(height: 16),
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(14),
            border: Border.all(color: ColorPalette.slate200)
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(account.nameOwner,
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: ColorPalette.slate800
                          ),
                        ),
                        Text('${account.nameBank} - ${listNumber.join("")}',
                          style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: ColorPalette.slate400
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
              GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                  showModalBottomSheet(
                    context: context,
                    isScrollControlled: true,
                    builder: (context) => const ChangeDestinationAccount(),
                  );
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(18),
                    color: ColorPalette.blue200.withOpacity(0.5)
                  ),
                  child: const Row(
                    children: [
                      Icon(Icons.change_circle_outlined, color: ColorPalette.primary, size: 20),
                      SizedBox(width: 4),
                      Text('Change',
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: ColorPalette.primary
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        )
      ],
    );
  }
}
