import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_state.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
// import 'package:syncrow_app/features/devices/view/widgets/water_heater/Inching_widget.dart';
// import 'package:syncrow_app/features/devices/view/widgets/water_heater/circulate_list_view.dart';
// import 'package:syncrow_app/features/devices/view/widgets/water_heater/circulate_widget.dart';
import 'package:syncrow_app/features/shared_widgets/create_schedule.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/features/shared_widgets/text_widgets/body_small.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
import 'package:syncrow_app/utils/resource_manager/font_manager.dart';
import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_event.dart';

class WHTimerScheduleScreen extends StatelessWidget {
  final DeviceModel device;
  final String deviceCode;
  final String switchCode;
  const WHTimerScheduleScreen(
      {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) => WaterHeaterBloc(switchCode: switchCode, whId: device.uuid ?? '')
          ..add(GetCounterEvent(deviceCode: deviceCode))
          ..add(GetScheduleEvent()),
        child: BlocBuilder<WaterHeaterBloc, WaterHeaterState>(
          builder: (context, state) {
            final waterHeaterBloc = BlocProvider.of<WaterHeaterBloc>(context);
            Duration duration = Duration.zero;
            int countNum = 0;
            if (state is UpdateTimerState) {
              countNum = state.seconds;
            } else if (state is TimerRunInProgress) {
              countNum = state.remainingTime;
            } else if (state is TimerRunComplete) {
              countNum = 0;
            } else if (state is LoadingNewSate) {
              countNum = 0;
            }
            return PopScope(
                canPop: false,
                onPopInvoked: (didPop) {
                  if (!didPop) {
                    waterHeaterBloc.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: [
                          waterHeaterBloc.createSchedule == true &&
                                  waterHeaterBloc.selectedTabIndex == 1
                              ? TextButton(
                                  onPressed: () {
                                    waterHeaterBloc.add(ScheduleSave());
                                  },
                                  child: const Text('Save'))
                              : waterHeaterBloc.selectedTabIndex == 1
                                  ? IconButton(
                                      onPressed: () {
                                        // waterHeaterBloc.toggleCreateSchedule();
                                        waterHeaterBloc
                                            .add(const ToggleCreateScheduleEvent(index: 1));
                                      },
                                      icon: const Icon(Icons.add),
                                    )
                                  : const SizedBox(),
                          waterHeaterBloc.createCirculate == true &&
                                  waterHeaterBloc.selectedTabIndex == 2
                              ? TextButton(
                                  onPressed: () {
                                    waterHeaterBloc.add(ScheduleSave());
                                  },
                                  child: const Text('Save'))
                              : waterHeaterBloc.selectedTabIndex == 2
                                  ? IconButton(
                                      onPressed: () {
                                        waterHeaterBloc.add(ToggleCreateCirculate());
                                      },
                                      icon: const Icon(Icons.add),
                                    )
                                  : const SizedBox(),
                        ],
                      ),
                      child: state is WHLoadingState
                          ? 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)),
                                      ),
                                    ),
                                    child: TabBar(
                                      indicatorPadding: EdgeInsets.zero,
                                      padding: EdgeInsets.zero,
                                      labelPadding: EdgeInsets.zero,
                                      onTap: (value) {
                                        if (value == 0) {
                                          if (waterHeaterBloc.createSchedule == true) {
                                            // waterHeaterBloc
                                            //     .toggleCreateSchedule();
                                            waterHeaterBloc
                                                .add(const ToggleCreateScheduleEvent(index: 1));
                                          }
                                          waterHeaterBloc.add(ToggleSelectedEvent(index: value));
                                          // waterHeaterBloc
                                          //     .toggleSelectedIndex(value);
                                        } else if (value == 2) {
                                          if (waterHeaterBloc.createCirculate == true) {
                                            waterHeaterBloc
                                                .add(ToggleCreateCirculateEvent(index: value));
                                            // waterHeaterBloc
                                            //     .toggleCreateCirculate();
                                          }
                                          waterHeaterBloc.add(ToggleSelectedEvent(index: value));
                                          // waterHeaterBloc
                                          //     .toggleSelectedIndex(value);
                                        } else {
                                          if (waterHeaterBloc.createSchedule == true) {
                                            waterHeaterBloc.add(ToggleSelectedEvent(index: value));
                                            // waterHeaterBloc
                                            //     .toggleCreateSchedule();
                                          }
                                          waterHeaterBloc.createCirculate = false;
                                          waterHeaterBloc.createSchedule = false;
                                          waterHeaterBloc.add(ToggleSelectedEvent(index: value));
                                          // waterHeaterBloc
                                          //     .toggleSelectedIndex(value);
                                        }
                                      },
                                      indicatorColor: Colors.white,
                                      dividerHeight: 0,
                                      indicatorSize: TabBarIndicatorSize.tab,
                                      indicator: const ShapeDecoration(
                                        color: ColorsManager.slidingBlueColor,
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.all(Radius.circular(20)),
                                        ),
                                      ),
                                      isScrollable: false,
                                      labelColor: Colors.white, // Text color when selected
                                      unselectedLabelColor:
                                          ColorsManager.blackColor, // Text color when not selected
                                      tabs: [
                                        Tab(
                                          icon: Padding(
                                            padding: const EdgeInsets.only(top: 10.0),
                                            child: SvgPicture.asset(
                                              Assets.scheduleTimeIcon,
                                              color: waterHeaterBloc.selectedTabIndex == 0
                                                  ? Colors.white
                                                  : ColorsManager
                                                      .blackColor, // Change icon color based on selectedIndex
                                            ),
                                          ),
                                          child: Container(
                                            padding: const EdgeInsets.symmetric(vertical: 5),
                                            child: BodySmall(
                                              text: 'Countdown',
                                              style: context.bodySmall.copyWith(
                                                color: waterHeaterBloc.selectedTabIndex == 0
                                                    ? Colors.white
                                                    : ColorsManager
                                                        .blackColor, // Text color based on selectedTabIndex
                                                fontSize: 10,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            ),
                                          ),
                                        ),
                                        Tab(
                                          icon: Padding(
                                            padding: const EdgeInsets.only(top: 10),
                                            child: SvgPicture.asset(
                                              Assets.scheduleCelenderIcon,
                                              color: waterHeaterBloc.selectedTabIndex == 1
                                                  ? Colors.white
                                                  : ColorsManager.blackColor,
                                            ),
                                          ),
                                          child: Container(
                                            padding: const EdgeInsets.symmetric(vertical: 5),
                                            child: Text(
                                              'Schedule',
                                              style: context.bodySmall.copyWith(
                                                color: waterHeaterBloc.selectedTabIndex == 1
                                                    ? Colors.white
                                                    : ColorsManager.blackColor,
                                                fontSize: 12,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            ),
                                          ),
                                        ),
                                        // Tab(
                                        //   icon: Padding(
                                        //     padding: const EdgeInsets.only(top: 10),
                                        //     child: SvgPicture.asset(
                                        //       Assets.scheduleCirculateIcon,
                                        //       color: waterHeaterBloc.selectedTabIndex == 2
                                        //           ? Colors.white
                                        //           : ColorsManager.blackColor,
                                        //     ),
                                        //   ),
                                        //   child: Container(
                                        //     padding: const EdgeInsets.symmetric(vertical: 5),
                                        //     child: Text(
                                        //       'Circulate',
                                        //       style: context.bodySmall.copyWith(
                                        //         color: waterHeaterBloc.selectedTabIndex == 2
                                        //             ? Colors.white
                                        //             : ColorsManager.blackColor,
                                        //         fontSize: 12,
                                        //         fontWeight: FontWeight.w400,
                                        //       ),
                                        //     ),
                                        //   ),
                                        // ),
                                        // Tab(
                                        //   icon: Padding(
                                        //     padding: const EdgeInsets.only(top: 10),
                                        //     child: SvgPicture.asset(
                                        //       Assets.scheduleInchingIcon,
                                        //       color: waterHeaterBloc.selectedTabIndex == 3
                                        //           ? Colors.white
                                        //           : ColorsManager.blackColor,
                                        //     ),
                                        //   ),
                                        //   child: Container(
                                        //     padding: const EdgeInsets.symmetric(vertical: 5),
                                        //     child: Text(
                                        //       'Inching',
                                        //       style: context.bodySmall.copyWith(
                                        //         color: waterHeaterBloc.selectedTabIndex == 3
                                        //             ? Colors.white
                                        //             : ColorsManager.blackColor,
                                        //         fontSize: 12,
                                        //         fontWeight: FontWeight.w400,
                                        //       ),
                                        //     ),
                                        //   ),
                                        // ),
                                      ],
                                    )),
                                Expanded(
                                  child: TabBarView(
                                    physics:
                                        const NeverScrollableScrollPhysics(), // Disable swiping
                                    children: [
                                      Center(
                                        child: Container(
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: [
                                              countNum > 0
                                                  ? BodyLarge(
                                                      text: _formatDuration(countNum),
                                                      fontColor: ColorsManager.slidingBlueColor,
                                                      fontSize: 40,
                                                    )
                                                  : CupertinoTimerPicker(
                                                      mode: CupertinoTimerPickerMode.hm,
                                                      onTimerDurationChanged:
                                                          (Duration newDuration) {
                                                        duration = newDuration;
                                                      },
                                                    ),
                                              GestureDetector(
                                                  onTap: () {
                                                    if (state is LoadingNewSate) {
                                                      return;
                                                    }
                                                    if (countNum > 0) {
                                                      waterHeaterBloc.add(SetCounterValue(
                                                          deviceCode: deviceCode,
                                                          duration: Duration.zero));
                                                    } else if (duration != Duration.zero) {
                                                      waterHeaterBloc.add(SetCounterValue(
                                                          deviceCode: deviceCode,
                                                          duration: duration));
                                                    }
                                                  },
                                                  child: SvgPicture.asset(countNum > 0
                                                      ? Assets.pauseIcon
                                                      : Assets.playIcon)),
                                            ],
                                          ),
                                        ),
                                      ),
                                      SizedBox(
                                        child: waterHeaterBloc.createSchedule == true
                                            ? CreateSchedule(
                                                onToggleChanged: (bool isOn) {
                                                  waterHeaterBloc.toggleSchedule = isOn;
                                                },
                                                onDateTimeChanged: (DateTime dateTime) {
                                                  waterHeaterBloc.selectedTime = dateTime;
                                                },
                                                days: waterHeaterBloc.days,
                                                selectDays: (List<String> selectedDays) {
                                                  waterHeaterBloc.selectedDays = selectedDays;
                                                },
                                              )
                                            : Padding(
                                                padding: const EdgeInsets.only(top: 10),
                                                child: Column(
                                                  children: [
                                                    Expanded(
                                                      child: ScheduleListView(
                                                        listSchedule: waterHeaterBloc
                                                            .listSchedule, // Pass the schedule list here
                                                        onDismissed: (scheduleId) {
                                                          waterHeaterBloc.listSchedule.removeWhere(
                                                              (schedule) =>
                                                                  schedule.scheduleId ==
                                                                  scheduleId);
                                                          waterHeaterBloc.add(
                                                              DeleteScheduleEvent(id: scheduleId));
                                                        },
                                                        onToggleSchedule: (scheduleId, isEnabled) {
                                                          waterHeaterBloc.add(ToggleScheduleEvent(
                                                            id: scheduleId,
                                                            toggle: isEnabled,
                                                          ));
                                                        },
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                      ),
                                      // Center(
                                      //   child: Column(
                                      //     crossAxisAlignment: CrossAxisAlignment.center,
                                      //     mainAxisAlignment: MainAxisAlignment.center,
                                      //     children: [
                                      //       waterHeaterBloc.createCirculate == true
                                      //           ? CirculateWidget(
                                      //               endDuration: () {
                                      //                 waterHeaterBloc.add(SelectTimeEvent(
                                      //                     context: context, isEffective: false));
                                      //               },
                                      //               startDuration: () {
                                      //                 waterHeaterBloc.add(SelectTimeEvent(
                                      //                     context: context, isEffective: false));
                                      //               },
                                      //               isStartEndTime: true,
                                      //               startTime: DateTime.now(),
                                      //               endTime: DateTime.now(),
                                      //               days: waterHeaterBloc.days,
                                      //               selectedDays: [],
                                      //               onToggleStartEndTime: (c) {},
                                      //               onTimeChanged: (x, f) {},
                                      //               onDaySelected: (p0) {},
                                      //             )
                                      //           : CirculateListView(
                                      //               listSchedule: [], // Pass the schedule list here
                                      //               onDismissed: (scheduleId) {
                                      //                 waterHeaterBloc.listSchedule.removeWhere(
                                      //                     (schedule) =>
                                      //                         schedule.scheduleId == scheduleId);
                                      //                 waterHeaterBloc
                                      //                     .add(DeleteScheduleEvent(id: scheduleId));
                                      //               },
                                      //               onToggleSchedule: (scheduleId, isEnabled) {
                                      //                 waterHeaterBloc.add(ToggleScheduleEvent(
                                      //                   id: scheduleId,
                                      //                   toggle: isEnabled,
                                      //                 ));
                                      //               },
                                      //             )
                                      //     ],
                                      //   ),
                                      // ),
                                      // Column(
                                      //   children: [
                                      //     SizedBox(height: 20),
                                      //     Container(
                                      //       child: InchingWidget(),
                                      //     ),
                                      //   ],
                                      // )
                                    ],
                                  ),
                                ),
                              ],
                            ),
                    )));
          },
        ),
      ),
    );
  }

  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';
  }
}
