import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:syncrow_app/features/devices/bloc/flush_sensor_bloc/flush_sensor_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/flush_sensor_bloc/flush_sensor_event.dart';
import 'package:syncrow_app/features/devices/bloc/flush_sensor_bloc/flush_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 FlushPresenceRecords extends StatelessWidget {
  final String deviceId;
  final String code;
  final String title;
  const FlushPresenceRecords(
      {super.key,
      required this.deviceId,
      required this.code,
      required this.title});

  @override
  Widget build(BuildContext context) {
    return DefaultScaffold(
      title: 'Presence Record',
      child: BlocProvider(
        create: (context) => FlushSensorBloc(deviceId: deviceId)
          ..add(FlushSensorGetDeviceReportsEvent(
              deviceUuid: deviceId, code: code)),
        child: BlocBuilder<FlushSensorBloc, FlushSensorState>(
            builder: (context, state) {
          final Map<String, List<DeviceEvent>> groupedRecords = {};

          if (state is FlushSensorLoadingInitialState) {
            return const Center(
              child: DefaultContainer(
                  width: 50, height: 50, child: CircularProgressIndicator()),
            );
          } else if (state is FlushSensorDeviceReportsState) {
            for (var record in state.deviceReport.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 groupedRecords.isEmpty
              ? const Center(
                  child: Text('No records found'),
                )
              : 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: [
                                    SizedBox(
                                      child: ListTile(
                                        leading: Icon(
                                          record.value == "presence"
                                              ? Icons.radio_button_checked
                                              : Icons.radio_button_unchecked,
                                          color: record.value == "presence"
                                              ? Colors.blue
                                              : Colors.grey,
                                        ),
                                        title: Text(
                                          record.value.toString(),
                                          style: const TextStyle(
                                            fontWeight: FontWeight.bold,
                                            fontSize: 18,
                                          ),
                                        ),
                                        subtitle: Text('$formattedTime'),
                                      ),
                                    ),
                                    if (idx != recordsForDate.length - 1)
                                      const Divider(
                                        color: ColorsManager.graysColor,
                                      ),
                                  ],
                                );
                              }).toList(),
                            ],
                          ),
                        ),
                      ],
                    );
                  },
                );
        }),
      ),
    );
  }
}
