import 'dart:math';

import 'package:cims_apps/application/assets/path_assets.dart';
import 'package:cims_apps/application/component/button/button_back.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/product/product_chart_view.dart';
import 'package:flutter/material.dart';
import 'package:group_button/group_button.dart';

class Time {
  int value;
  String simpleName, completeName;

  Time(this.value, this.simpleName, this.completeName);
}

class ProductView extends StatefulWidget {
  final String investType;
  const ProductView(this.investType, {super.key});

  @override
  State<ProductView> createState() => _ProductViewState();
}

class _ProductViewState extends State<ProductView> {
  int selectedTab = 0;
  Time selectedTime = Time(2, '1D', '1 day');
  int selectedMachineType = 0;
  int selectedMachineTime = 0;

  List<Time> listTime = [
    Time(2, '1D', '1 day'),
    Time(30, '1M', '1 month'),
    Time(90, '3M', '3 months'),
    Time(365, '1Y', '1 year'),
  ];

  List<String> listTab = ['NAV', 'AUM'];

  List<String> listMachine = ['Monthly Routine', 'Connect Once'];

  List<Time> listMachineTime = [
    Time(1, '1D', '1 year'),
    Time(3, '1M', '3 year'),
    Time(5, '3M', '5 year'),
    Time(10, '1Y', '10 year'),
  ];

  TextEditingController machineController = TextEditingController();

  GroupButtonController machineGroupButtonController = GroupButtonController(selectedIndex: 0);

  List<String> listTopHoldings = [
    'Bank Pembangunan Daerah Sulawesi Selatan dan Sulawesi Barat',
    'PT. Bank Jabar Banten, TBK',
    'PT. Bank Mega',
    'PT. Bank Nagaria',
    'PT. BPD Sulawesi Tengah'
  ];

  List<double> data = [];
  double estimatedValue = 0;

  void setEstimatedValue() {
    double parseValue = double.parse(machineController.text.replaceAll('Rp ', '').replaceAll('.', ''));
    int machineType = selectedMachineType == 0 ? 12 : 1;
    setState(() {
      estimatedValue = (machineType * (listMachineTime[selectedMachineTime].value) * ((parseValue * machineType) * 10/100)) + parseValue;
    });
  }

  @override
  void initState() {
    machineController.text = NumberFormatter.numberCurrency(100000, 'Rp ', 'id_ID', decimalDigits: 0);
    selectedTime = listTime[0];
    setEstimatedValue();
    List.generate(2, (index) => {
      data.add((2500 + index - Random().nextInt(100)).toDouble())
    });
    // TODO: implement initState
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        width: SizeConfig.width,
        height: SizeConfig.height,
        child: Stack(
          children: [
            const ImageView(image: PathAssets.imgDashboardAccount),
            Column(
              children: [
                const SizedBox(
                  height: 50,
                ),
                const Padding(
                  padding: EdgeInsets.symmetric(horizontal: 24),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      ButtonBack(),
                      Wrap(
                        spacing: 12,
                        children: [
                          Icon(Icons.search_rounded, color: ColorPalette.blue200, size: 32),
                          Icon(Icons.file_download_outlined, color: ColorPalette.blue200, size: 32),
                          Icon(Icons.star_outline_rounded, color: ColorPalette.blue200, size: 32)
                        ],
                      )
                    ],
                  ),
                ),
                const SizedBox(
                  height: 24,
                ),
                headContainer(),
                const SizedBox(
                  height: 24,
                ),
                Expanded(
                  child: contentContainer()
                )
              ],
            )
          ],
        ),
      ),
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24),
        child: ButtonView(
          name: 'Buy',
          onPressed: () {

          },
          height: SizeConfig.height * 0.06,
          marginVertical: 16,
        ),
      ),
    );
  }

  Widget headContainer() {
    return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Row(
                children: [
                  ImageView(image: PathAssets.imgProduct, width: SizeConfig.width * .12),
                  SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'Gemilang Dana Kas Maxima',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.w700,
                          fontSize: 18
                      ),
                    ),
                  )
                ],
              ),
            ),
            Container(
              padding: const EdgeInsets.all(6),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(40),
                  color: ColorPalette.investTypeBgColor[widget.investType] ?? Colors.white,
                  border: Border.all(width: 2, color: ColorPalette.investTypeColor[widget.investType] ?? Colors.white)
              ),
              child: Text(
                widget.investType,
                style: TextStyle(
                    color: ColorPalette.investTypeColor[widget.investType],
                    fontWeight: FontWeight.w600
                ),
              ),
            )
          ],
        ),
      );
  }

  Widget contentContainer() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(12),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        child: ListView(
          children: [
            ProductChartView(
              tabType: listTab[selectedTab],
              lastTime: selectedTime.completeName,
              dataChart: data,
            ),
            Center(
              child: Padding(
                padding: const EdgeInsets.all(24),
                child: switchTab(listTab, (value) {
                  setState(() {
                    selectedTab = value;
                    data.clear();
                    List.generate(selectedTime.value, (index) => {
                      data.add((2500 + index - Random().nextInt(100)).toDouble())
                    });
                  });
                }, selectedTab),
              ),
            ),
            swithTime(),
            const SizedBox(
            height: 24,
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  columnInformation('CAGR 1Y', '3,88%'),
                  columnInformation('Drawdown 1Y', '0%'),
                  columnInformation('Expense Ratio', '1,99%')
                ],
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  columnInformation('Total AUM', '3,88%'),
                  columnInformation('Avg.Yield Dec 23', '6,44%'),
                  columnInformation('Risk Level', 'Conservative')
                ],
              ),
            ),
            const SizedBox(
              height: 24,
            ),
            cardInformation('Investment Information', informationInvest()),
            const SizedBox(
              height: 24,
            ),
            cardInformation('Investment Costs', investCost()),
            const SizedBox(
              height: 24,
            ),
            moreAction(),
            const SizedBox(
              height: 24,
            ),
            cardInformation('Time Machine', timeMachine()),
            const SizedBox(
              height: 24,
            ),
            topFiveHoldings(),
            const SizedBox(
              height: 24,
            ),
            cardInformation('Document', documentProduct()),
          ],
        ),
      ),
    );
  }

  Widget switchTab(List<String> dataTab, void Function(int value) onTap, int current) {
    return Container(
      width: SizeConfig.width,
      decoration: BoxDecoration(
        border: Border.all(
          color: ColorPalette.slate200,
        ),
        borderRadius: BorderRadius.circular(80)
      ),
      child: Stack(
        children: [
          // AnimatedPositioned(
          //   duration: const Duration(milliseconds: 200),
          //   curve: Curves.fastOutSlowIn,
          //   right: current == dataTab.length - 1 ? 0 : SizeConfig.width * current / dataTab.length - (12 * dataTab.length),
          //   left:  current == 0 ? 0 : SizeConfig.width * current / dataTab.length - (12 * dataTab.length),
          //   child: Container(
          //     height: 35,
          //     decoration: BoxDecoration(
          //       color: ColorPalette.blue200,
          //       borderRadius: BorderRadius.circular(80)
          //     ),
          //   ),
          // ),
          Container(
            height: 35,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(80)
            ),
            child: Row(
              children: dataTab.asMap().entries.map((e) => Expanded(
                  child: GestureDetector(
                      onTap: () {
                        onTap(e.key);
                      },
                      child: AnimatedContainer(
                        duration: const Duration(milliseconds: 300),
                        height: 35,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(80),
                          color: e.key == current ? ColorPalette.blue200 : ColorPalette.white
                        ),
                        child: Text(
                          e.value,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontWeight: e.key == current ? FontWeight.w700 : FontWeight.w500,
                            color: e.key == current ? ColorPalette.primary : ColorPalette.slate500
                          ),
                        ),
                      )
                  )
              )).toList(),
            ),
          )
        ],
      ),
    );
  }

  Widget swithTime() {
    return Container(
        color: ColorPalette.slate50,
        alignment: Alignment.center,
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          padding: const EdgeInsets.symmetric(horizontal: 24),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: listTime.map((e) {
              return GestureDetector(
                onTap: () {
                  setState(() {
                    selectedTime = e;
                    data.clear();
                    List.generate(e.value, (index) => {
                      data.add((2500 + index - Random().nextInt(100)).toDouble())
                    });
                  });
                },
                child: AnimatedContainer(
                  duration: const Duration(milliseconds: 200),
                  width: SizeConfig.width * .12,
                  alignment: Alignment.center,
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4),
                      color: selectedTime == e ? ColorPalette.primary : ColorPalette.slate50
                  ),
                  child: Text(e.simpleName, style: TextStyle(
                      color: selectedTime == e ? ColorPalette.white : ColorPalette.slate400,
                      fontWeight: FontWeight.w700
                  )),
                ),
              );
            }).toList(),
          ),
        )
    );
  }

  Widget columnInformation(String title, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        rowInformation(title),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(value)
          ],
        )
      ],
    );
  }

  Widget rowInformation(String title) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          title,
          maxLines: 1,
          style: const TextStyle(
            color: ColorPalette.slate400,
            fontWeight: FontWeight.w600
          ),
        ),
        const SizedBox(width: 2),
        const Icon(Icons.info_outline_rounded, size: 16, color: ColorPalette.slate400)
      ],
    );
  }
  
  Widget cardInformation(String title, Widget child) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 24),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        border: Border.all(color: ColorPalette.slate200),
        borderRadius: BorderRadius.circular(12)
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextTitle(title: title, fontSize: 16),
          const SizedBox(
            height: 16,
          ),
          child
        ],
      ),
    );
  }

  Widget informationInvest() {
    return Column(
      children: [
        const Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              'Minimum Purchase',
              style: TextStyle(
                color: ColorPalette.slate400,
                fontWeight: FontWeight.w600
              ),
            ),
            Text('Rp10.000')
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            rowInformation('Custodian Bank'),
            const Text('HSBC INDONESIA')
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            rowInformation('Depository Bank'),
            const Text('BCA')
          ],
        )
      ],
    );
  }

  Widget investCost(){
    return Column(
      children: [
        const Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              'Purchase Commission',
              style: TextStyle(
                  color: ColorPalette.slate400,
                  fontWeight: FontWeight.w600
              ),
            ),
            Text('Free',
              style: TextStyle(
                fontWeight: FontWeight.bold
              ),
            )
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            rowInformation('Sales Commission'),
            const Text('Free',
              style: TextStyle(
                fontWeight: FontWeight.bold
              ),
            )
          ],
        ),
      ],
    );
  }

  Widget moreAction() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24),
      child: Row(
        children: [
          Expanded(
            child: ButtonView(
              onPressed: () {

              },
              prefixIcon: Icon(Icons.space_dashboard_sharp),
              backgroundColor: ColorPalette.blue50,
              sizeBorderRadius: 8,
              isSecondaryColor: false,
              width: SizeConfig.width * .5,
              heightWrapContent: true,
              isOutlined: true,
              widthPrefix: 10,
              name: 'Routine Savings',
              textSize: 14,
              textAlign: TextAlign.start,
              contentPadding: EdgeInsets.all(12),
            )
          ),
          SizedBox(
            width: 16,
          ),
          Expanded(
              child: ButtonView(
                onPressed: () {

                },
                prefixIcon: Icon(Icons.space_dashboard_sharp, color: ColorPalette.orange500),
                widthPrefix: 10,
                name: 'Compare Mutual Funds',
                width: SizeConfig.width * .5,
                heightWrapContent: true,
                backgroundColor: ColorPalette.orange50,
                sizeBorderRadius: 8,
                isOutlined: true,
                borderColor: ColorPalette.orange500,
                textSize: 14,
                textAlign: TextAlign.start,
                textColor: ColorPalette.orange500,
                contentPadding: EdgeInsets.all(12),
              )
          ),
        ],
      ),
    );
  }

  Widget timeMachine() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        switchTab(listMachine, (value) {
            setState(() {
              selectedMachineType = value;
            });
            setEstimatedValue();
          },
          selectedMachineType
        ),
        const Padding(
          padding: EdgeInsets.only(top: 16, bottom: 8),
          child: Text(
            "Today's Investment Estimated Value",
            style: TextStyle(
              fontWeight: FontWeight.w600,
              color: ColorPalette.slate800
            ),
          ),
        ),
        TextFormView(
          name: '',
          ctrl: machineController,
          onChanged: (value) {
            value = value.replaceAll('Rp ', '').replaceAll('.', '');
            double parseValue = double.parse(value);
            if(value.isNotEmpty){
              machineController.text = NumberFormatter.numberCurrency(parseValue, 'Rp ', 'id_ID', decimalDigits: 0);
            }else{
              machineController.text = NumberFormatter.numberCurrency(0, 'Rp ', 'id_ID', decimalDigits: 0);
            }
            setEstimatedValue();
          },
          keyboardType: TextInputType.number,
        ),
        const Padding(
          padding: EdgeInsets.only(top: 16, bottom: 8),
          child: Text(
            "How many years ago did you start investing?",
            style: TextStyle(
                fontWeight: FontWeight.w600,
                color: ColorPalette.slate800
            ),
          ),
        ),
        Center(
          child: GroupButton(
            buttons: listMachineTime.map((e) => e.completeName).toList(),
            controller: machineGroupButtonController,
            onSelected: (value, index, isSelected) {
              setState(() {
                selectedMachineTime = index;
              });
              setEstimatedValue();
            },
            options: GroupButtonOptions(
              buttonWidth: SizeConfig.width * .375,
              mainGroupAlignment: MainGroupAlignment.spaceBetween,
              groupRunAlignment: GroupRunAlignment.spaceBetween,
              spacing: 16,
              elevation: 0,
              borderRadius: BorderRadius.circular(80),
              selectedShadow: const [],
              selectedColor: Colors.white,
              selectedBorderColor: ColorPalette.primary,
              selectedTextStyle: const TextStyle(
                fontWeight: FontWeight.w700,
                color: ColorPalette.primary
              ),
              unselectedShadow: const [],
              unselectedBorderColor: ColorPalette.slate200,
              unselectedTextStyle: const TextStyle(
                fontWeight: FontWeight.w500,
                color: ColorPalette.slate500
              ),
            ),
          ),
        ),
        const Padding(
          padding: EdgeInsets.only(top: 16, bottom: 8),
          child: Text(
            "Today's Investment Estimated Value",
            style: TextStyle(
                fontWeight: FontWeight.w600,
                color: ColorPalette.slate500
            ),
          ),
        ),
        TextTitle(
          title: NumberFormatter.numberCurrency(estimatedValue, 'Rp ', 'id_ID'),
          fontSize: 24,
          color: ColorPalette.primary,
        )
      ],
    );
  }

  Widget topFiveHoldings() {
    return Column(
      children: [
        const Padding(
          padding: EdgeInsets.symmetric(horizontal: 24),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextTitle(title: 'Top 5 Holdings'),
              Text(
                'As of 31 Dec 2023',
                style: TextStyle(
                  fontSize: 12,
                  color: ColorPalette.slate400
                ),
              )
            ],
          ),
        ),
        const SizedBox(
          height: 16,
        ),
        ...listTopHoldings.asMap().entries.map((e) {
          return topProduct(e.key, e.value);
        })
      ],
    );
  }

  Widget topProduct(int index, String name) {
    return Column(
      children: [
        if(index != 0)...[
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 16),
            child: Divider(color: ColorPalette.slate200,),
          )
        ],
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 24),
          child: Row(
            children: [
              Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 11),
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: ColorPalette.blue50,
                  border: Border.all(color: ColorPalette.blue200)
                ),
                child: Text(index.toString(), style: const TextStyle(color: ColorPalette.primary)),
              ),
              const SizedBox(
                width: 16,
              ),
              Expanded(
                child: Text(
                  name,
                  style: const TextStyle(
                    color: ColorPalette.slate800,
                    fontSize: 16
                  ),
                )
              )
            ],
          ),
        )
      ],
    );
  }

  Widget documentProduct() {
    return Column(
      children: [
        Wrap(
          runAlignment: WrapAlignment.spaceBetween,
          alignment: WrapAlignment.spaceBetween,
          children: [
            SizedBox(
              width: SizeConfig.width * .4,
              child: const Row(
                children: [
                  Icon(Icons.file_copy_outlined, color: ColorPalette.primary),
                  SizedBox(
                    width: 16,
                  ),
                  Text(
                    'Prospektus',
                    style: TextStyle(
                      color: ColorPalette.primary,
                      fontWeight: FontWeight.w600
                    ),
                  )
                ],
              ),
            ),
            SizedBox(
              width: SizeConfig.width * .4,
              child: const Row(
                children: [
                  Icon(Icons.file_copy_outlined, color: ColorPalette.primary),
                  SizedBox(
                    width: 16,
                  ),
                  Expanded(
                    child: Text(
                      'Fun Fact Sheet',
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: ColorPalette.primary,
                          fontWeight: FontWeight.w600
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        )
      ],
    );
  }
}
