import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.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_model.dart';
import 'package:syncrow_app/features/devices/view/widgets/garage_door/create_schedule_garage.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/features/shared_widgets/schedule_list.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
import 'package:syncrow_app/utils/resource_manager/font_manager.dart';

class TimerScheduleScreen extends StatelessWidget {
  final DeviceModel device;
  final String deviceCode;
  final String switchCode;
  const TimerScheduleScreen(
      {required this.device,
      required this.deviceCode,
      required this.switchCode,
      super.key});

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: SystemUiOverlayStyle(
        statusBarColor: ColorsManager.primaryColor.withOpacity(0.5),
        statusBarIconBrightness: Brightness.light,
      ),
      child: BlocProvider(
        create: (context) =>
            GarageDoorBloc(GDId: device.uuid ?? '')..add(GetScheduleEvent()),
        child: BlocBuilder<GarageDoorBloc, GarageDoorSensorState>(
          builder: (context, state) {
            final garageBloc = BlocProvider.of<GarageDoorBloc>(context);
            return PopScope(
                canPop: false,
                onPopInvoked: (didPop) {
                  if (!didPop) {
                    garageBloc.add(OnClose());
                    Navigator.pop(context);
                  }
                },
                child: DefaultTabController(
                    length: 2,
                    child: DefaultScaffold(
                      appBar: AppBar(
                        backgroundColor: Colors.transparent,
                        centerTitle: true,
                        title: const BodyLarge(
                          text: 'Schedule',
                          fontColor: ColorsManager.primaryColor,
                          fontWeight: FontsManager.bold,
                        ),
                        actions: [
                          garageBloc.createSchedule == true
                              ? TextButton(
                                  onPressed: () {
                                    garageBloc.add(ScheduleSaveapp());
                                  },
                                  child: const Text('Save'))
                              : IconButton(
                                  onPressed: () {
                                    garageBloc.add(
                                        const ToggleCreateScheduleEvent(
                                            index: 1));
                                  },
                                  icon: const Icon(Icons.add),
                                )
                        ],
                      ),
                      child: state is GarageDoorLoadingState
                          ? const Center(child: CircularProgressIndicator())
                          : Column(
                              children: [
                                Container(
                                  width: MediaQuery.of(context).size.width,
                                  decoration: const ShapeDecoration(
                                    color: ColorsManager.onPrimaryColor,
                                    shape: RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(30)),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: SizedBox(
                                    child: garageBloc.createSchedule == true
                                        ? CreateGarageSchedule(
                                            onToggleChanged: (bool value) {
                                              garageBloc.toggleSchedule = value;
                                            },
                                            onDateTimeChanged:
                                                (DateTime dateTime) {
                                              garageBloc.selectedTime =
                                                  dateTime;
                                            },
                                            days: garageBloc.days,
                                            selectDays:
                                                (List<String> selectedDays) {
                                              garageBloc.selectedDays =
                                                  selectedDays;
                                            },
                                          )
                                        : Padding(
                                            padding:
                                                const EdgeInsets.only(top: 10),
                                            child: ScheduleListView(
                                              listSchedule:
                                                  garageBloc.listSchedule,
                                              onDismissed: (scheduleId) {
                                                garageBloc.listSchedule
                                                    .removeWhere((schedule) =>
                                                        schedule.scheduleId ==
                                                        scheduleId);
                                                garageBloc.add(
                                                    DeleteScheduleEvent(
                                                        id: scheduleId));
                                              },
                                              onToggleSchedule:
                                                  (scheduleId, isEnabled) {
                                                garageBloc
                                                    .add(ToggleScheduleEvent(
                                                  id: scheduleId,
                                                  toggle: isEnabled,
                                                ));
                                              },
                                            ),
                                          ),
                                  ),
                                ),
                              ],
                            ),
                    )));
          },
        ),
      ),
    );
  }

  String _formatDuration(int seconds) {
    final hours = (seconds ~/ 3600).toString().padLeft(2, '0');
    final minutes = ((seconds % 3600) ~/ 60).toString().padLeft(2, '0');
    final secs = (seconds % 60).toString().padLeft(2, '0');
    return '$hours:$minutes:$secs';
  }
}
