import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:syncrow_app/features/devices/bloc/door_sensor_bloc/door_sensor_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/door_sensor_bloc/door_sensor_event.dart';
import 'package:syncrow_app/features/devices/bloc/door_sensor_bloc/door_sensor_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 DoorRecordsScreen extends StatelessWidget {
  final String DSId;
  const DoorRecordsScreen({super.key, required this.DSId});

  @override
  Widget build(BuildContext context) {
    return DefaultScaffold(
      title: 'Records',
      child: BlocProvider(
        create: (context) =>
            DoorSensorBloc(DSId: DSId)..add(const ReportLogsInitial()),
        child: BlocBuilder<DoorSensorBloc, DoorSensorState>(
          builder: (context, state) {
            final doorSensorBloc = BlocProvider.of<DoorSensorBloc>(context);

            if (state is DoorSensorLoadingState) {
              return const Center(
                child: DefaultContainer(
                    width: 50, height: 50, child: CircularProgressIndicator()),
              );
            } else if (state is UpdateState) {
              // Group records by formatted date
              final Map<String, List<DeviceEvent>> groupedRecords = {};

              // Iterate over the data list in DeviceReport
              for (var record in doorSensorBloc.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];
                }
              }

              // Build the ListView with grouped data
              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: [
                      // Date header
                      Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Text(
                          date,
                          style: const TextStyle(
                            color: ColorsManager.grayColor,
                            fontSize: 13,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ),
                      // List of records for the specific date
                      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'),
                                    ),
                                  ),
                                  // Only add Divider if it's not the last item
                                  if (idx != recordsForDate.length - 1)
                                    const Divider(
                                      color: ColorsManager.graysColor,
                                    ),
                                ],
                              );
                            }).toList(),
                          ],
                        ),
                      ),
                    ],
                  );
                },
              );
            }
            return const Center(child: Text('No data available.'));
          },
        ),
      ),
    );
  }
}
