import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';
import 'package:syncrow_app/features/devices/bloc/sos_bloc/sos_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/sos_bloc/sos_event.dart';
import 'package:syncrow_app/features/devices/bloc/sos_bloc/sos_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/generated/assets.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class SosRecordsScreen extends StatefulWidget {
  final String sosId;
  const SosRecordsScreen({super.key, required this.sosId});

  @override
  State<SosRecordsScreen> createState() => _SosRecordsScreenState();
}

class _SosRecordsScreenState extends State<SosRecordsScreen> {
  // int _selectedIndex = 0;
  @override
  Widget build(BuildContext context) {
    return DefaultScaffold(
      title: 'Records',
      child: BlocProvider(
        create: (context) => SosBloc(sosId: widget.sosId)..add(const ReportLogsInitial()),
        child: BlocBuilder<SosBloc, SosState>(
          builder: (context, state) {
            final waterSensorBloc = BlocProvider.of<SosBloc>(context);
            final Map<String, List<DeviceEvent>> groupedRecords = {};

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

            return DefaultTabController(
              length: 2,
              child: Column(
                children: [
                  // Container(
                  //   width: MediaQuery.of(context).size.width,
                  //   decoration: const ShapeDecoration(
                  //     color: ColorsManager.onPrimaryColor,
                  //     shape: RoundedRectangleBorder(
                  //       borderRadius: BorderRadius.all(Radius.circular(30)),
                  //     ),
                  //   ),
                  //   child: TabBar(
                  //     onTap: (value) {
                  //       setState(() {
                  //         _selectedIndex = value;
                  //       });
                  //     },
                  //     indicatorColor: Colors.white,
                  //     dividerHeight: 0,
                  //     indicatorSize: TabBarIndicatorSize.tab,
                  //     indicator: const ShapeDecoration(
                  //       color: ColorsManager.slidingBlueColor,
                  //       shape: RoundedRectangleBorder(
                  //         borderRadius: BorderRadius.all(Radius.circular(20)),
                  //       ),
                  //     ),
                  //     tabs: [
                  //       Tab(
                  //         child: Container(
                  //           padding: const EdgeInsets.symmetric(vertical: 10),
                  //           child: BodySmall(
                  //             text: 'Record',
                  //             style: context.bodySmall.copyWith(
                  //               color:
                  //                   _selectedIndex == 0 ? Colors.white : ColorsManager.blackColor,
                  //               fontSize: 12,
                  //               fontWeight: FontWeight.w400,
                  //             ),
                  //           ),
                  //         ),
                  //       ),
                  //       Tab(
                  //         child: Container(
                  //           padding: const EdgeInsets.symmetric(vertical: 10),
                  //           child: Text(
                  //             'Automation Log',
                  //             style: context.bodySmall.copyWith(
                  //               color:
                  //                   _selectedIndex == 1 ? Colors.white : ColorsManager.blackColor,
                  //               fontSize: 12,
                  //               fontWeight: FontWeight.w400,
                  //             ),
                  //           ),
                  //         ),
                  //       ),
                  //     ],
                  //   ),
                  // ),
                  Expanded(
                    child: TabBarView(
                      physics: const NeverScrollableScrollPhysics(),
                      children: [
                        groupedRecords.isEmpty
                            ? Center(
                                child: SvgPicture.asset(
                                  Assets.emptyLog,
                                  fit: BoxFit.fill,
                                ),
                              )
                            : 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.all(16.0),
                                        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: [
                                                  ListTile(
                                                    leading: SvgPicture.asset(
                                                      record.value == 'true'
                                                          ? Assets.leakDetectedIcon
                                                          : Assets.leakNormalIcon,
                                                      height: 25,
                                                      width: 25,
                                                    ),
                                                    title: const Text(
                                                      "SOS Alert Triggered",
                                                      style: const TextStyle(
                                                        fontWeight: FontWeight.bold,
                                                        fontSize: 18,
                                                      ),
                                                    ),
                                                    subtitle: Text(formattedTime),
                                                  ),
                                                  if (idx != recordsForDate.length - 1)
                                                    const Divider(
                                                      color: ColorsManager.graysColor,
                                                    ),
                                                ],
                                              );
                                            }).toList(),
                                          ],
                                        ),
                                      ),
                                    ],
                                  );
                                },
                              ),
                        Container(
                          height: 10,
                          width: 20,
                          child: Center(
                            child: SvgPicture.asset(
                              Assets.emptyLog,
                              fit: BoxFit.fill,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}
