import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_pos_ecommerce/core/core.dart';
import 'package:flutter_pos_ecommerce/core/extensions/string_ext.dart';
import 'package:flutter_pos_ecommerce/module/ecommerce/presentation/address/bloc/add_address/add_address_bloc.dart';
import 'package:flutter_pos_ecommerce/module/ecommerce/presentation/address/bloc/address/address_bloc.dart';
import 'package:flutter_pos_ecommerce/module/ecommerce/presentation/home/bloc/checkout/checkout_bloc.dart';
import 'package:go_router/go_router.dart';

import '../../../../../core/assets/assets.gen.dart';
import '../../../../../core/components/buttons.dart';
import '../../../../../core/components/spaces.dart';
import '../../../../../core/router/app_router.dart';
import '../widgets/address_tile.dart';

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

  @override
  State<AddressPage> createState() => _AddressPageState();
}

class _AddressPageState extends State<AddressPage> {
  // final List<AddressModel> addresses = [
  //   AddressModel(
  //     country: 'Indonesia',
  //     firstName: 'Saiful',
  //     lastName: 'Bahri',
  //     address: 'Jl. Merdeka No. 123',
  //     city: 'Jakarta Selatan',
  //     province: 'DKI Jakarta',
  //     zipCode: 12345,
  //     phoneNumber: '08123456789',
  //     isPrimary: true,
  //   ),
  //   AddressModel(
  //     country: 'Indonesia',
  //     firstName: 'Saiful',
  //     lastName: '',
  //     address: 'Jl. Cendrawasih No. 456',
  //     city: 'Bandung',
  //     province: 'Jawa Barat',
  //     zipCode: 67890,
  //     phoneNumber: '08987654321',
  //   ),
  // ];

  @override
  void initState() {
    super.initState();
    context.read<AddressBloc>().add(const AddressEvent.getAddress());
  }

  @override
  Widget build(BuildContext context) {
    // int selectedIndex = addresses.indexWhere((element) => element.isPrimary);
    return Scaffold(
      appBar: AppBar(
        title: const Text('Alamat'),
        actions: [
          IconButton(
            onPressed: () {
              context.goNamed(
                RouteConstants.cart,
                pathParameters: PathParameters(
                  rootTab: RootTab.order,
                ).toMap(),
              );
            },
            icon: Assets.icons.cart.svg(height: 24.0),
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(20.0),
        children: [
          const Text(
            'Pilih atau tambahkan alamat pengiriman',
            style: TextStyle(
              fontSize: 16,
            ),
          ),
          const SpaceHeight(20.0),
          BlocBuilder<AddressBloc, AddressState>(
            builder: (context, state) {
              return state.maybeWhen(
                orElse: () => const Center(
                  child: CircularProgressIndicator(),
                ),
                loaded: (address) {
                  return BlocBuilder<CheckoutBloc, CheckoutState>(
                    builder: (context, state) {
                      // dapatkan addressid
                      final addressId = state.maybeWhen(
                        orElse: () => 0,
                        loaded:
                            (_, discount, addressId, __, ____, _____, ______) {
                          return addressId;
                        },
                      );
                      return ListView.separated(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: address.length,
                        itemBuilder: (context, index) => AddressTile(
                          isSelected: addressId == address[index].id,
                          data: address[index],
                          onTap: () {
                            context.read<CheckoutBloc>().add(
                                CheckoutEvent.addAddressId(address[index].id!));
                          },
                          onEditTap: () {
                            context.goNamed(
                              RouteConstants.editAddress,
                              pathParameters: PathParameters(
                                rootTab: RootTab.order,
                              ).toMap(),
                              extra: address[index],
                            );
                          },
                        ),
                        separatorBuilder: (context, index) =>
                            const SpaceHeight(16.0),
                      );
                    },
                  );
                },
              );
            },
          ),
          const SpaceHeight(40.0),
          Button.outlined(
            onPressed: () async {
              await context.pushNamed(
                RouteConstants.addAddress,
                pathParameters: PathParameters(
                  rootTab: RootTab.order,
                ).toMap(),
              );
              context.read<AddressBloc>().add(const AddressEvent.getAddress());
            },
            label: 'Tambah Alamat',
          ),
          const SpaceHeight(50.0),
        ],
      ),
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  'Subtotal (Estimasi)',
                  style: TextStyle(
                    fontSize: 16.0,
                  ),
                ),
                BlocBuilder<CheckoutBloc, CheckoutState>(
                  builder: (context, state) {
                    final price = state.maybeWhen(
                      orElse: () => 0,
                      loaded: (products, discount, _, __, ___, ____, _____) =>
                          products.fold(
                        0,
                        (previousValue, element) =>
                            previousValue +
                            (element.product.price! * element.quantity),
                      ),
                    );
                    final discount = state.maybeWhen(
                        orElse: () => 0,
                        loaded: (products, discount, _, __, ___, ____, _____) {
                          if (discount == null) {
                            return 0;
                          }
                          return discount.value!
                              .replaceAll('.00', '')
                              .toIntegerFromText;
                        });
                    final totalBayar = price - (discount / 100 * price);
                    return Text(
                      totalBayar.currencyFormatRp,
                      style: const TextStyle(
                        fontSize: 16.0,
                      ),
                    );
                  },
                ),
              ],
            ),
            const SpaceHeight(12.0),
            Button.filled(
              onPressed: () {
                context.goNamed(
                  RouteConstants.orderDetail,
                  pathParameters: PathParameters(
                    rootTab: RootTab.order,
                  ).toMap(),
                );
              },
              label: 'Lanjutkan',
            ),
          ],
        ),
      ),
    );
  }
}
