import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart';
import 'package:unit2/model/passo/barangay.dart';
import 'package:unit2/model/passo/memoranda.dart';
import 'package:unit2/sevices/offline/offline_passo/admin/api_services/barangay_api_services.dart';
import 'package:unit2/sevices/offline/offline_passo/admin/api_services/memoranda_api_services.dart';

import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart';
import '../../../../theme-data.dart/colors.dart';
import '../../../../utils/urls.dart';
import 'package:http/http.dart';

class MemorandaAdminPage extends StatefulWidget {
  const MemorandaAdminPage();

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

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

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

                // Loop through the list of City objects and insert them into the local database.
                Response response = await get(Uri.parse(
                    'http://${Url.instance.host()}${Url.instance.getMemoranda()}'));

                print(response.body);
                if (response.statusCode == 200) {
                  final List result = jsonDecode(response.body)['data'];

                  result.map(((e) => Memoranda.fromJson(e))).toList();

                  final memos =
                      result.map((json) => Memoranda.fromJson(json)).toList();
                  for (Memoranda memo in memos) {
                    await SQLServices.instance.createMemoranda(memo);
                  }
                }

                context.read<MemorandaAdminBloc>().add(LoadMemoranda());
              } catch (e) {
                // Handle any errors that might occur during the API call or database insertion.
                print("Error: $e");
              }
            },
            child: const Text('SYNC'),
          ),
        ],
      ),
      body: BlocConsumer<MemorandaAdminBloc, MemorandaAdminState>(
        listener: (context, state) {
          // TODO: implement listener
        },
        builder: (context, state) {
          if (state is MemorandaLoaded) {
            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('ID'),
                              ),
                              const DataColumn(
                                label: Text('Code'),
                              ),
                              const DataColumn(
                                label: Text('Memoranda'),
                              ),
                            ],
                            rows: state.memo.map((dataRow) {
                              return DataRow(
                                cells: [
                                  DataCell(Text(dataRow.id.toString() ??
                                      'N/A')), // Use a default value if cityCode is null
                                  DataCell(Text(dataRow.code ??
                                      'N/A')), // Use a default value if cityDescription is null
                                  DataCell(Text(dataRow.memoranda ?? 'N/A')),
                                ],
                              );
                            }).toList(),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              )
            ]);
          }
          return Container();
        },
      ),
    );
  }
}
