import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/shared_widgets/default_container.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class PreferencesPage extends StatelessWidget {
  final String GDId;
  const PreferencesPage({super.key, required this.GDId});
  @override
  Widget build(BuildContext context) {
    return DefaultScaffold(
        title: 'Preferences',
        child: BlocProvider(
          create: (context) =>
              GarageDoorBloc(GDId: GDId)..add(const GarageDoorInitial()),
          child: BlocBuilder<GarageDoorBloc, GarageDoorSensorState>(
            builder: (context, state) {
              final garageDoorBloc = BlocProvider.of<GarageDoorBloc>(context);

              return state is GarageDoorLoadingState
                  ? const Center(
                      child: DefaultContainer(
                          width: 50,
                          height: 50,
                          child: CircularProgressIndicator()),
                    )
                  : Column(
                      children: [
                        const Row(
                          children: [
                            BodyMedium(
                              text: 'Warnings',
                              fontColor: ColorsManager.grayColor,
                              fontWeight: FontWeight.w700,
                            ),
                          ],
                        ),
                        DefaultContainer(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(
                                height: 50,
                                child: ListTile(
                                    contentPadding: EdgeInsets.zero,
                                    leading: InkWell(
                                      onTap: () {
                                        showDialog(
                                            context: context,
                                            builder: (context) {
                                              return TimeoutDialog(
                                                duration: Duration(
                                                    seconds: garageDoorBloc
                                                        .deviceStatus
                                                        .countdownAlarm),
                                                title: 'Timeout Alarm',
                                                cancelTab: () {
                                                  Navigator.of(context).pop();
                                                },
                                                confirmTab: (selectedSecond) {
                                                  garageDoorBloc.add(
                                                      SetTimeOutValue(
                                                          deviceCode:
                                                              'countdown_alarm',
                                                          duration:
                                                              selectedSecond));
                                                  Navigator.of(context).pop();
                                                },
                                              );
                                            });
                                      },
                                      child: const BodyMedium(
                                        text: 'Alarm when door is open',
                                        fontWeight: FontWeight.normal,
                                      ),
                                    ),
                                    trailing: Container(
                                      width: 100,
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.end,
                                        children: [
                                          Container(
                                            height: 30,
                                            width: 1,
                                            color: ColorsManager.graysColor,
                                          ),
                                          Transform.scale(
                                            scale: .8,
                                            child: CupertinoSwitch(
                                              value: garageDoorBloc.deviceStatus
                                                      .doorState1 !=
                                                  'unclosed_time',
                                              onChanged: (value) {
                                                context
                                                    .read<GarageDoorBloc>()
                                                    .add(
                                                      ToggleAlarmEvent(
                                                        value
                                                            ? 'unclosed_time'
                                                            : 'close_time_alarm',
                                                      ),
                                                    );
                                              },
                                              applyTheme: true,
                                            ),
                                          ),
                                        ],
                                      ),
                                    )),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                        const Row(
                          children: [
                            BodyMedium(
                              text: 'Other Settings',
                              fontColor: ColorsManager.grayColor,
                              fontWeight: FontWeight.w700,
                            ),
                          ],
                        ),
                        DefaultContainer(
                          child: InkWell(
                            onTap: () {
                              showDialog(
                                context: context,
                                builder: (context) {
                                  return SecondDialog(
                                    label2: 'Close',
                                    initialSelectedLabel: garageDoorBloc
                                        .secondSelected
                                        .toString(),
                                    cancelTab: () {
                                      Navigator.of(context).pop();
                                    },
                                    confirmTab: (v) {
                                      garageDoorBloc
                                          .add(SelectSecondsEvent(seconds: v));
                                      Navigator.of(context).pop();
                                    },
                                    title: 'Control',
                                    label1: 'Open',
                                    onTapLabel1: (selected) {},
                                  );
                                },
                              );
                            },
                            child: Container(
                              padding: EdgeInsets.only(top: 12, bottom: 12),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  const BodyMedium(
                                    text: 'Opening and Closing Time',
                                    fontWeight: FontWeight.normal,
                                  ),
                                  Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: [
                                      BodyMedium(
                                        fontColor: ColorsManager.textGray,
                                        text:
                                            '${garageDoorBloc.secondSelected.toString()} Seconds',
                                        fontWeight: FontWeight.normal,
                                        fontSize: 13,
                                      ),
                                      const Icon(
                                        Icons.arrow_forward_ios,
                                        size: 15,
                                        color: ColorsManager.textGray,
                                      )
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        )
                      ],
                    );
            },
          ),
        ));
  }
}
//Timeout

class SecondDialog extends StatefulWidget {
  final String label1;
  final String label2;
  final String title;

  final Function(String)? onTapLabel1;
  final Function()? cancelTab;
  final Function(int selectedSecond)? confirmTab;

  final String? initialSelectedLabel;

  SecondDialog({
    required this.label1,
    required this.label2,
    required this.title,
    this.onTapLabel1,
    required this.cancelTab,
    required this.confirmTab,
    this.initialSelectedLabel,
  });

  @override
  _SecondDialogState createState() => _SecondDialogState();
}

class _SecondDialogState extends State<SecondDialog> {
  late int selectedSecond;

  @override
  void initState() {
    super.initState();
    selectedSecond = int.tryParse(widget.initialSelectedLabel ?? '10') ?? 10;
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      contentPadding: EdgeInsets.zero,
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          const SizedBox(
            height: 10,
          ),
          BodyLarge(
            text: widget.title,
            fontWeight: FontWeight.w700,
            fontColor: ColorsManager.primaryColor,
            fontSize: 16,
          ),
          const Padding(
            padding: EdgeInsets.only(left: 15, right: 15),
            child: Divider(
              color: ColorsManager.textGray,
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 15, right: 15, bottom: 10),
            child: Column(
              children: [
                Center(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        width: 100,
                        child: CupertinoPicker(
                          itemExtent: 40.0,
                          scrollController: FixedExtentScrollController(
                            initialItem: selectedSecond - 10,
                          ),
                          onSelectedItemChanged: (int index) {
                            setState(() {
                              selectedSecond = index + 10;
                            });
                          },
                          children: List<Widget>.generate(111, (int index) {
                            return Center(
                              child: BodyLarge(
                                text: (index + 10).toString().padLeft(2, '0'),
                                style: const TextStyle(
                                    fontWeight: FontWeight.w400,
                                    fontSize: 30,
                                    color: Colors.blue),
                              ),
                            );
                          }),
                        ),
                      ),
                      const Text('Sec'),
                    ],
                  ),
                )
              ],
            ),
          ),
          Row(
            children: [
              Expanded(
                child: Container(
                  decoration: const BoxDecoration(
                      border: Border(
                    right: BorderSide(
                      color: ColorsManager.textGray,
                      width: 0.5,
                    ),
                    top: BorderSide(
                      color: ColorsManager.textGray,
                      width: 1.0,
                    ),
                  )),
                  child: SizedBox(
                    child: InkWell(
                      onTap: widget.cancelTab,
                      child: const Padding(
                        padding: EdgeInsets.all(15),
                        child: Center(
                          child: Text(
                            'Cancel',
                            style: TextStyle(
                                color: ColorsManager.textGray,
                                fontSize: 14,
                                fontWeight: FontWeight.w400),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              Expanded(
                  child: Container(
                decoration: const BoxDecoration(
                    border: Border(
                  left: BorderSide(
                    color: ColorsManager.textGray,
                    width: 0.5,
                  ),
                  top: BorderSide(
                    color: ColorsManager.textGray,
                    width: 1.0,
                  ),
                )),
                child: InkWell(
                    onTap: () {
                      widget.confirmTab?.call(selectedSecond);
                    },
                    child: const Padding(
                      padding: EdgeInsets.all(15),
                      child: Center(
                        child: Text(
                          'Confirm',
                          style: TextStyle(
                              color: ColorsManager.primaryColor,
                              fontSize: 14,
                              fontWeight: FontWeight.w400),
                        ),
                      ),
                    )),
              ))
            ],
          )
        ],
      ),
    );
  }
}

class TimeoutDialog extends StatefulWidget {
  final String title;
  final Function(String)? onTapLabel1;
  final Function()? cancelTab;
  final Function(Duration timeSelected)? confirmTab;
  final Duration? duration;

  TimeoutDialog({
    required this.title,
    this.onTapLabel1,
    required this.cancelTab,
    required this.confirmTab,
    this.duration,
  });

  @override
  _TimeoutDialogState createState() => _TimeoutDialogState();
}

class _TimeoutDialogState extends State<TimeoutDialog> {
  late int selectedSecond;
  Duration duration = Duration.zero;
  int countNum = 0;
  @override
  void initState() {
    super.initState();
    duration = widget.duration!;
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      contentPadding: EdgeInsets.zero,
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          const SizedBox(
            height: 10,
          ),
          BodyLarge(
            text: widget.title,
            fontWeight: FontWeight.w700,
            fontColor: ColorsManager.primaryColor,
            fontSize: 16,
          ),
          const Padding(
            padding: EdgeInsets.only(left: 15, right: 15),
            child: Divider(
              color: ColorsManager.textGray,
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 15, right: 15, bottom: 10),
            child: Column(
              children: [
                Center(
                  child: Container(
                    height: 150,
                    width: MediaQuery.of(context).size.width * 1,
                    child: CupertinoTimerPicker(
                      initialTimerDuration: duration,
                      mode: CupertinoTimerPickerMode.hm,
                      onTimerDurationChanged: (Duration newDuration) {
                        duration = newDuration;
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Row(
            children: [
              Expanded(
                child: Container(
                  decoration: const BoxDecoration(
                      border: Border(
                    right: BorderSide(
                      color: ColorsManager.textGray,
                      width: 0.5,
                    ),
                    top: BorderSide(
                      color: ColorsManager.textGray,
                      width: 1.0,
                    ),
                  )),
                  child: SizedBox(
                    child: InkWell(
                      onTap: widget.cancelTab,
                      child: const Padding(
                        padding: EdgeInsets.all(15),
                        child: Center(
                          child: Text(
                            'Cancel',
                            style: TextStyle(
                                color: ColorsManager.textGray,
                                fontSize: 14,
                                fontWeight: FontWeight.w400),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              Expanded(
                  child: Container(
                decoration: const BoxDecoration(
                    border: Border(
                  left: BorderSide(
                    color: ColorsManager.textGray,
                    width: 0.5,
                  ),
                  top: BorderSide(
                    color: ColorsManager.textGray,
                    width: 1.0,
                  ),
                )),
                child: InkWell(
                    onTap: () {
                      widget.confirmTab?.call(duration);
                    },
                    child: const Padding(
                      padding: EdgeInsets.all(15),
                      child: Center(
                        child: Text(
                          'Confirm',
                          style: TextStyle(
                              color: ColorsManager.primaryColor,
                              fontSize: 14,
                              fontWeight: FontWeight.w400),
                        ),
                      ),
                    )),
              ))
            ],
          )
        ],
      ),
    );
  }

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