import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:unit2/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart';
import 'package:unit2/model/offline/offline_profile.dart';
import 'package:unit2/screens/offline/passo/building/add/AddBuildingAndStructure..dart';

import '../../../../../utils/alerts.dart';
import '../../../../../widgets/passo/custom_button.dart';

class BuildingAndStructureOfflinePage extends StatefulWidget {
  final VoidCallback additionalItemsPrevBtn;
  final VoidCallback additionalItemsNextBtn;
  final OfflineProfile offlineProfile;

  const BuildingAndStructureOfflinePage(this.additionalItemsPrevBtn,
      this.additionalItemsNextBtn, this.offlineProfile);

  @override
  _BuildingAndStructureOfflinePage createState() =>
      _BuildingAndStructureOfflinePage();
}

class _BuildingAndStructureOfflinePage
    extends State<BuildingAndStructureOfflinePage> {
  // void deleteItem(int itemId) {
  //   context.read<AdditionalItemBloc>().add(DeleteAdditionalItems(id: itemId));
  // }

  void deleteItem(int itemId) {
    context
        .read<BuildingAndStructureBloc>()
        .add(DeleteBuildingAndStructure(id: itemId));
  }

  final items = [];

  double _totalMarketValue(items) {
    double total = 0;
    items.forEach((row) {
      total += double.parse(row.adjustedMarketValue);
    });
    return total;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: BlocConsumer<BuildingAndStructureBloc, BuildingAndStructureState>(
      listener: (context, state) {
        // TODO: implement listener
      },
      builder: (context, state) {
        if (state is BuildingAndStructureOfflineInitial) {
          return Column(children: [
            Expanded(
                child: SingleChildScrollView(
                    child: Padding(
                        padding: const EdgeInsets.all(15.0),
                        child: Column(children: [
                          Container(
                            margin: const EdgeInsets.only(
                                left: 0, top: 20, right: 0, bottom: 10),
                            child: const Text('BUILDING AND STRUCTURE',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 18),
                                textAlign: TextAlign.left),
                          ),
                          Align(
                            alignment: Alignment.topRight,
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.red,
                              ),
                              onPressed: () {
                                context
                                    .read<BuildingAndStructureBloc>()
                                    .add(ShowBuildingAndStructure());
                              },
                              child: const Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text('ADD NEW'), // <-- Text
                                  SizedBox(
                                    width: 5,
                                  ),
                                  Icon(
                                    // <-- Icon
                                    Icons.add,
                                    size: 24.0,
                                  ),
                                ],
                              ),
                            ),
                          )
                        ]))))
          ]);
        }
        if (state is BuildingAndStructureLoaded) {
          return Column(
            children: [
              Expanded(
                  child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Column(
                    children: [
                      Container(
                        margin: const EdgeInsets.only(
                            left: 0, top: 20, right: 0, bottom: 10),
                        child: const Text('BUILDING AND STRUCTURES',
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 18),
                            textAlign: TextAlign.left),
                      ),
                      Align(
                        alignment: Alignment.topRight,
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.red,
                          ),
                          onPressed: () {
                            context
                                .read<BuildingAndStructureBloc>()
                                .add(ShowBuildingAndStructure());
                          },
                          child: const Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text('ADD ITEM'), // <-- Text
                              SizedBox(
                                width: 5,
                              ),
                              Icon(
                                // <-- Icon
                                Icons.add,
                                size: 24.0,
                              ),
                            ],
                          ),
                        ),
                      ),
                      SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: DataTable(
                          // ignore: prefer_const_literals_to_create_immutables
                          columns: [
                            const DataColumn(
                              label: Text('Building Core'),
                            ),
                            const DataColumn(
                              label: Text('Type'),
                            ),
                            const DataColumn(
                              label: Text('Area'),
                            ),
                            const DataColumn(
                              label: Text('Unit Value'),
                            ),
                            const DataColumn(
                              label: Text('% of BUCC'),
                            ),
                            const DataColumn(
                              label: Text('Base Market Value'),
                            ),
                            const DataColumn(
                              label: Text('% of Depreciation'),
                            ),
                            const DataColumn(
                              label: Text('Depreciation Cost'),
                            ),
                            const DataColumn(
                              label: Text('Market Value'),
                            ),
                            const DataColumn(
                              label: Text('Action'),
                            )
                          ],
                          rows: state.bldgAndStructure.map((dataRow) {
                            return DataRow(
                              cells: [
                                DataCell(Text(dataRow.actualUse!)),
                                DataCell(Text(dataRow.bldgType!)),
                                DataCell(Text(dataRow.bldgArea!)),
                                DataCell(Text(
                                  NumberFormat.currency(
                                          locale: 'en-PH', symbol: "₱")
                                      .format(double.parse(dataRow.unitValue!)),
                                )),
                                const DataCell(Text("100%")),
                                DataCell(Text(
                                  NumberFormat.currency(
                                          locale: 'en-PH', symbol: "₱")
                                      .format(
                                          double.parse(dataRow.marketValue!)),
                                )),
                                DataCell(Text(dataRow.depRate!)),
                                DataCell(Text(
                                  NumberFormat.currency(
                                          locale: 'en-PH', symbol: "₱")
                                      .format(double.parse(dataRow.depAmount!)),
                                )),
                                DataCell(Text(
                                  NumberFormat.currency(
                                          locale: 'en-PH', symbol: "₱")
                                      .format(double.parse(
                                          dataRow.adjustedMarketValue!)),
                                )),
                                DataCell(Row(
                                  children: [
                                    InkWell(
                                      child: Container(
                                        height: 30,
                                        width: 30,
                                        decoration: const BoxDecoration(
                                          shape: BoxShape.circle,
                                          color: Colors.red,
                                        ),
                                        child: const Icon(
                                          Icons.delete,
                                          color: Colors.white,
                                          size: 20.0,
                                        ),
                                      ),
                                      onTap: () {
                                        confirmAlertWithCancel(
                                            context,
                                            () => deleteItem(dataRow.id!),
                                            () => null,
                                            'Delete Item?',
                                            "Are you sure you want to delete this item?");
                                      },
                                    ),
                                  ],
                                ))
                              ],
                            );
                          }).toList(),
                        ),
                      )
                    ],
                  ),
                ),
              )),
              Padding(
                padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      'Total Market Value',
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 17),
                    ),
                    Text(
                      NumberFormat.currency(locale: 'en-PH', symbol: "₱")
                          .format(_totalMarketValue(state.bldgAndStructure)),
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 17),
                    )
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    CustomButton(
                      icon: const Icon(Icons.chevron_left_rounded,
                          color: Colors.white),
                      onPressed: () {
                        {
                          widget.additionalItemsPrevBtn();
                        }
                        ;
                      },
                    ),
                    CustomButton(
                      icon: const Icon(Icons.chevron_right_rounded,
                          color: Colors.white),
                      onPressed: () {
                        {
                          widget.additionalItemsNextBtn();
                        }
                        ;
                      },
                    )
                  ],
                ),
              ),
            ],
          );
        }
        if (state is BuildingAndStructureDeletedState) {
          if (state.success) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              successAlert(context, "Deletion Successful",
                  "Extra item has been deleted successfully", () {
                Navigator.of(context).pop();
                context
                    .read<BuildingAndStructureBloc>()
                    .add(LoadBuildingAndStructure());
              });
            });
          }
        }
        if (state is ShowBldgAndStructuresScreen) {
          return ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 1000.0),
            child: AlertDialog(
              insetPadding: const EdgeInsets.symmetric(
                horizontal: 10.0,
                vertical: 10.0,
              ),
              title: const Text(
                'ADD NEW BLDG & STRUCTURE',
                textAlign: TextAlign.center,
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                      child:
                          AddBuildingAndStructureOffline(widget.offlineProfile))
                ],
              ),
            ),
          );
        }
        return Container();
      },
    ));
  }
}
