import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart';
import 'package:unit2/model/passo/class_components%20_offline.dart';
import 'package:unit2/model/passo/class_components.dart';
import 'package:unit2/sevices/offline/offline_passo/admin/api_services/class_components_api_services.dart';
import 'package:unit2/sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:http/http.dart';
import '../../../../model/passo/city.dart';
import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart';
import '../../../../utils/urls.dart';

class ClassComponentsAdminPage extends StatefulWidget {
  const ClassComponentsAdminPage();

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

class _ClassComponentsAdminPage extends State<ClassComponentsAdminPage> {
  final items = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: primary,
        title: const Text("Class Components"),
        centerTitle: true,
        actions: [
          TextButton(
            style: TextButton.styleFrom(
              textStyle: const TextStyle(fontSize: 15),
            ),
            onPressed: () async {
              try {
                Response response = await get(Uri.parse(
                    'http://${Url.instance.host()}/api/rptass_app/class_components/'));

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

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

                  final classes = result
                      .map((json) => ClassComponents.fromJson(json))
                      .toList();

                  // Loop through the list of City objects and insert them into the local database.
                  for (ClassComponents classs in classes) {
                    await SQLServices.instance.createClassComponents(
                        ClassComponentsOffline(
                            componentName: classs.componentName,
                            minBaseUnitvalPercent: classs.minBaseUnitvalPercent,
                            maxBaseUnitvalPercent: classs.maxBaseUnitvalPercent,
                            minUnitvalSqrmtr: classs.minUnitvalSqrmtr,
                            maxUnitvalSqrmtr: classs.maxUnitvalSqrmtr,
                            minAddBaseunitval: classs.minAddBaseunitval,
                            maxAddBaseunitval: classs.maxAddBaseunitval,
                            minDeductBaserate: classs.minAddBaseunitval,
                            maxDeductBaserate: classs.maxDeductBaserate,
                            minLinearMeter: classs.minLinearMeter,
                            maxLinearMeter: classs.maxLinearMeter,
                            minSpacing: classs.minSpacing,
                            maxSpacing: classs.maxSpacing,
                            roughFinish: classs.roughFinish,
                            highFinish: classs.highFinish,
                            withoutBucc: classs.withoutBucc == true ? 1 : 0));
                  }
                }

                context
                    .read<ClassComponentsAdminBloc>()
                    .add(LoadClassComponents());

                // Assuming result is a List of JSON objects, convert them to City objects.
              } catch (e) {
                // Handle any errors that might occur during the API call or database insertion.
                print("Error: $e");
              }
            },
            child: const Text('SYNC'),
          ),
        ],
      ),
      body: BlocConsumer<ClassComponentsAdminBloc, ClassComponentsAdminState>(
        listener: (context, state) {
          // TODO: implement listener
        },
        builder: (context, state) {
          if (state is ClassComponentsAdminLoaded) {
            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('Components Name'),
                              ),
                              const DataColumn(
                                label: Text('with BUCC?'),
                              ),
                            ],
                            rows: state.classes.map((dataRow) {
                              return DataRow(
                                cells: [
                                  DataCell(
                                      Text(dataRow.componentName ?? 'N/A')),
                                  // Use a default value if cityCode is null
                                  DataCell(Text(dataRow.withoutBucc
                                          .toString() ??
                                      'N/A')), // Use a default value if cityDescription is null
                                ],
                              );
                            }).toList(),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              )
            ]);
          }

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