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/water_leak_bloc/water_leak_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/water_leak_bloc/water_leak_event.dart';
import 'package:syncrow_app/features/devices/bloc/water_leak_bloc/water_leak_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 WaterLeakRecordsScreen extends StatefulWidget {
  final String WLId;
  const WaterLeakRecordsScreen({super.key, required this.WLId});

  @override
  State<WaterLeakRecordsScreen> createState() => _WaterLeakRecordsScreenState();
}

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

            if (state is WaterLeakLoadingState) {
              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 Record',
                  //             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
                            ? const Center(child: Text('No data available.'))
                            : 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: Text(
                                                      record.value == 'true'
                                                          ? "Leak Detected"
                                                          : "Normal",
                                                      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: const Center(child: Text('No data available.')),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}
