import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart';
import 'package:unit2/sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart';
import 'package:unit2/theme-data.dart/colors.dart';

import '../../../../model/passo/city.dart';
import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart';

class MunicipalitiesAdminPage extends StatefulWidget {
  const MunicipalitiesAdminPage();

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

class _MunicipalitiesAdminPage extends State<MunicipalitiesAdminPage> {
  final items = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: primary,
        title: const Text("Municipaities"),
        centerTitle: true,
        actions: [
          TextButton(
            style: TextButton.styleFrom(
              textStyle: const TextStyle(fontSize: 15),
            ),
            onPressed: () async {
              try {
                final result =
                    await MunicipalityAdminApiServices.instance.fetch();

                // Assuming result is a List of JSON objects, convert them to City objects.
                final cities =
                    result.map((json) => City.fromJson(json)).toList();

                // Loop through the list of City objects and insert them into the local database.
                for (City city in cities) {
                  print(city.cityDescription);
                  print(city.cityCode);
                  await SQLServices.instance.createMunicipalities(city);
                }

                context
                    .read<MunicipalitiesAdminBloc>()
                    .add(LoadMunicipalities());
              } catch (e) {
                // Handle any errors that might occur during the API call or database insertion.
                print("Error: $e");
              }
            },
            child: const Text('SYNC'),
          ),
        ],
      ),
      body: BlocConsumer<MunicipalitiesAdminBloc, MunicipalitiesAdminState>(
        listener: (context, state) {
          // TODO: implement listener
        },
        builder: (context, state) {
          if (state is MunicipalitiesLoaded) {
            return Column(children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Padding(
                    padding: EdgeInsets.all(15.0),
                    child: Column(
                      children: [
                        SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: DataTable(
                            // ignore: prefer_const_literals_to_create_immutables
                            columns: [
                              const DataColumn(
                                label: Text('City Code'),
                              ),
                              const DataColumn(
                                label: Text('Description'),
                              ),
                            ],
                            rows: state.city.map((dataRow) {
                              return DataRow(
                                cells: [
                                  DataCell(Text(dataRow.cityCode ??
                                      'N/A')), // Use a default value if cityCode is null
                                  DataCell(Text(dataRow.cityDescription ??
                                      'N/A')), // Use a default value if cityDescription is null
                                ],
                              );
                            }).toList(),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              )
            ]);
          }

          return Container();
        },
      ),
    );
  }
}
