import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../home/widgets/custom_tab_bar.dart';
import '../bloc/tax_settings/tax_settings_bloc.dart';
import '../dialogs/form_tax_dialog.dart';
import '../models/tax_model.dart';
import '../widgets/add_data.dart';
import '../widgets/manage_tax_card.dart';
import '../widgets/settings_title.dart';

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

  @override
  State<TaxPage> createState() => _TaxPageState();
}

class _TaxPageState extends State<TaxPage> {
  @override
  void initState() {
    super.initState();
    context.read<TaxSettingsBloc>().add(const TaxSettingsEvent.loadSettings());
  }

  void onEditTap(TaxModel item, int serviceChargeValue, int taxValue) {
    showDialog(
      context: context,
      builder: (context) => FormTaxDialog(
        taxValue: taxValue,
        serviceChargeValue: serviceChargeValue,
        onSave: (newTaxValue, newServiceChargeValue) {
          context.read<TaxSettingsBloc>().add(
                TaxSettingsEvent.updateSettings(
                  taxValue: newTaxValue,
                  serviceChargeValue: newServiceChargeValue,
                ),
              );
        },
      ),
    );
  }

  void onAddDataTap(int serviceChargeValue, int taxValue) {
    showDialog(
      context: context,
      builder: (context) => FormTaxDialog(
        taxValue: taxValue,
        serviceChargeValue: serviceChargeValue,
        onSave: (newTaxValue, newServiceChargeValue) {
          context.read<TaxSettingsBloc>().add(
                TaxSettingsEvent.updateSettings(
                  taxValue: newTaxValue,
                  serviceChargeValue: newServiceChargeValue,
                ),
              );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        const SettingsTitle(
          'Perhitungan Biaya',
          subtitle: 'Biaya Layanan dan Pajak',
        ),
        Expanded(
          child: SingleChildScrollView(
            child: BlocBuilder<TaxSettingsBloc, TaxSettingsState>(
              builder: (context, state) {
                return state.when(
                  initial: () =>
                      const Center(child: CircularProgressIndicator()),
                  loading: () =>
                      const Center(child: CircularProgressIndicator()),
                  error: (message) => Center(child: Text('Error: $message')),
                  loaded: (taxModel, serviceChargeValue) {
                    final items = [
                      TaxModel(
                          name: 'Biaya Layanan',
                          type: TaxType.layanan,
                          value: serviceChargeValue),
                      taxModel,
                    ];

                    return CustomTabBar(
                      tabTitles: const ['Layanan', 'Pajak'],
                      initialTabIndex: 0,
                      tabViews: [
                        // LAYANAN TAB
                        SizedBox(
                          child: GridView.builder(
                            shrinkWrap: true,
                            itemCount: 2, // Add button + 1 service charge item
                            physics: const NeverScrollableScrollPhysics(),
                            padding: const EdgeInsets.symmetric(horizontal: 16),
                            gridDelegate:
                                const SliverGridDelegateWithFixedCrossAxisCount(
                              childAspectRatio: 0.85,
                              crossAxisCount: 3,
                              crossAxisSpacing: 30.0,
                              mainAxisSpacing: 30.0,
                            ),
                            itemBuilder: (context, index) {
                              if (index == 0) {
                                return AddData(
                                  title: 'Edit Perhitungan',
                                  onPressed: () => onAddDataTap(
                                      serviceChargeValue, taxModel.value),
                                );
                              }
                              final item = items.firstWhere(
                                  (element) => element.type.isLayanan);
                              return ManageTaxCard(
                                data: item,
                                onEditTap: () => onEditTap(
                                    item, serviceChargeValue, taxModel.value),
                              );
                            },
                          ),
                        ),

                        // PAJAK TAB
                        SizedBox(
                          child: GridView.builder(
                            shrinkWrap: true,
                            itemCount: 2, // Add button + 1 tax item
                            physics: const NeverScrollableScrollPhysics(),
                            padding: const EdgeInsets.symmetric(horizontal: 16),
                            gridDelegate:
                                const SliverGridDelegateWithFixedCrossAxisCount(
                              childAspectRatio: 0.85,
                              crossAxisCount: 3,
                              crossAxisSpacing: 30.0,
                              mainAxisSpacing: 30.0,
                            ),
                            itemBuilder: (context, index) {
                              if (index == 0) {
                                return AddData(
                                  title: 'Edit Perhitungan',
                                  onPressed: () => onAddDataTap(
                                      serviceChargeValue, taxModel.value),
                                );
                              }
                              final item = items.firstWhere(
                                  (element) => element.type.isPajak);
                              return ManageTaxCard(
                                data: item,
                                onEditTap: () => onEditTap(
                                    item, serviceChargeValue, taxModel.value),
                              );
                            },
                          ),
                        ),
                      ],
                    );
                  },
                );
              },
            ),
          ),
        ),
      ],
    );
  }
}
