import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:syncrow_app/features/devices/bloc/garage_door_bloc/garage_door_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/garage_door_bloc/garage_door_event.dart';
import 'package:syncrow_app/features/devices/bloc/garage_door_bloc/garage_door_state.dart';
import 'package:syncrow_app/features/devices/model/device_report_model.dart';
import 'package:syncrow_app/features/shared_widgets/default_container.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class GarageRecordsScreen extends StatelessWidget {
  final String GDId;
  const GarageRecordsScreen({super.key, required this.GDId});

  @override
  Widget build(BuildContext context) {
    return DefaultScaffold(
      title: 'Records',
      child: BlocProvider(
        create: (context) =>
            GarageDoorBloc(GDId: GDId)..add(const ReportLogsInitial()),
        child: BlocBuilder<GarageDoorBloc, GarageDoorSensorState>(
            builder: (context, state) {
          final garageDoorBloc = BlocProvider.of<GarageDoorBloc>(context);
          final Map<String, List<DeviceEvent>> groupedRecords = {};

          if (state is GarageDoorLoadingState) {
            return const Center(
              child: DefaultContainer(
                  width: 50, height: 50, child: CircularProgressIndicator()),
            );
          } else if (state is UpdateState) {
            for (var record in garageDoorBloc.recordGroups.data!) {
              final DateTime eventDateTime =
                  DateTime.fromMillisecondsSinceEpoch(record.eventTime!);
              final String formattedDate =
                  DateFormat('EEEE, dd/MM/yyyy').format(eventDateTime);

              // Group by formatted date
              if (groupedRecords.containsKey(formattedDate)) {
                groupedRecords[formattedDate]!.add(record);
              } else {
                groupedRecords[formattedDate] = [record];
              }
            }
          }
          return ListView.builder(
            itemCount: groupedRecords.length,
            itemBuilder: (context, index) {
              final String date = groupedRecords.keys.elementAt(index);
              final List<DeviceEvent> recordsForDate = groupedRecords[date]!;

              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(bottom: 5, top: 10),
                    child: Text(
                      date,
                      style: const TextStyle(
                        color: ColorsManager.grayColor,
                        fontSize: 13,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                  DefaultContainer(
                    child: Column(
                      children: [
                        ...recordsForDate.asMap().entries.map((entry) {
                          final int idx = entry.key;
                          final DeviceEvent record = entry.value;
                          final DateTime eventDateTime =
                              DateTime.fromMillisecondsSinceEpoch(
                                  record.eventTime!);
                          final String formattedTime =
                              DateFormat('HH:mm:ss').format(eventDateTime);

                          return Column(
                            children: [
                              Container(
                                child: ListTile(
                                  leading: Icon(
                                    record.value == 'true'
                                        ? Icons.radio_button_checked
                                        : Icons.radio_button_unchecked,
                                    color: record.value == 'true'
                                        ? Colors.blue
                                        : Colors.grey,
                                  ),
                                  title: Text(
                                    record.value == 'true'
                                        ? "Opened"
                                        : "Closed",
                                    style: const TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18,
                                    ),
                                  ),
                                  subtitle: Text('$formattedTime'),
                                ),
                              ),
                              if (idx != recordsForDate.length - 1)
                                const Divider(
                                  color: ColorsManager.graysColor,
                                ),
                            ],
                          );
                        }).toList(),
                      ],
                    ),
                  ),
                ],
              );
            },
          );
        }),
      ),
    );
  }
}
