import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.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/device_appbar.dart';
import 'package:syncrow_app/features/devices/view/widgets/garage_door/garage_preferences_settings.dart';
import 'package:syncrow_app/features/devices/view/widgets/garage_door/garage_records_screen.dart';
import 'package:syncrow_app/features/devices/view/widgets/garage_door/schedule_garage_screen.dart';
import 'package:syncrow_app/features/devices/view/widgets/garage_door/timer_page.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_small.dart';
import 'package:syncrow_app/generated/assets.dart';

// class GarageDoorScreen extends StatelessWidget {
//   final DeviceModel? device;

//   const GarageDoorScreen({super.key, this.device});

//   @override
//   Widget build(BuildContext context) {
//     return DefaultScaffold(
//       appBar: DeviceAppbar(
//         deviceName: device!.name!,
//         deviceUuid: device!.uuid!,
//       ),
//       title: 'Garage Door Opener',
//       child: BlocProvider(
//         create: (context) => GarageDoorBloc(GDId: device?.uuid ?? '')
//           ..add(const GarageDoorInitial()),
//         child: BlocBuilder<GarageDoorBloc, GarageDoorSensorState>(
//           builder: (context, state) {
//             final garageBloc = BlocProvider.of<GarageDoorBloc>(context);
//             bool isDoorOpen = false;
//             int selectedTime = 0;
//             print('state=$state');
//             if (state is UpdateState) {
//               isDoorOpen = garageBloc.toggleDoor;
//               selectedTime = garageBloc.secondSelected;
//             }
//             return state is GarageDoorLoadingState
//                 ? const Center(
//                     child: DefaultContainer(
//                         width: 50,
//                         height: 50,
//                         child: CircularProgressIndicator()),
//                   )
//                 : RefreshIndicator(
//                     onRefresh: () async {
//                       garageBloc.add(const GarageDoorInitial());
//                     },
//                     child: ListView(
//                       children: [
//                         SizedBox(
//                           height: MediaQuery.sizeOf(context).height * 0.8,
//                           child: Column(
//                             children: [
//                               Expanded(
//                                 flex: 5,
//                                 child: InkWell(
//                                   overlayColor: WidgetStateProperty.all(
//                                       Colors.transparent),
//                                   onTap: () {},
//                                   child: Row(
//                                     mainAxisAlignment: MainAxisAlignment.center,
//                                     crossAxisAlignment:
//                                         CrossAxisAlignment.center,
//                                     children: [
//                                       Container(
//                                           decoration: BoxDecoration(
//                                             borderRadius:
//                                                 BorderRadius.circular(890),
//                                             boxShadow: [
//                                               BoxShadow(
//                                                 color: Colors.white
//                                                     .withOpacity(0.1),
//                                                 blurRadius: 24,
//                                                 offset: const Offset(-5, -5),
//                                                 blurStyle: BlurStyle.outer,
//                                               ),
//                                               BoxShadow(
//                                                 color: Colors.black
//                                                     .withOpacity(0.11),
//                                                 blurRadius: 25,
//                                                 offset: const Offset(5, 5),
//                                                 blurStyle: BlurStyle.outer,
//                                               ),
//                                               BoxShadow(
//                                                 color: Colors.black
//                                                     .withOpacity(0.13),
//                                                 blurRadius: 30,
//                                                 offset: const Offset(5, 5),
//                                                 blurStyle: BlurStyle.inner,
//                                               ),
//                                             ],
//                                           ),
//                                           child: InkWell(
//                                             onTap: () {
//                                               garageBloc.add(ToggleDoorEvent(
//                                                   toggle:
//                                                       garageBloc.toggleDoor));
//                                             },
//                                             child: GradientWidget(
//                                               doorStatus: isDoorOpen,
//                                               seconds: selectedTime,
//                                               // doorStatus: garageBloc.toggleDoor,
//                                               // seconds:garageBloc.secondSelected,
//                                             ),
//                                           )),
//                                     ],
//                                   ),
//                                 ),
//                               ),
//                               Expanded(
//                                   flex: 3,
//                                   child: Column(
//                                     children: [
//                                       Flexible(
//                                         child: Row(
//                                           children: [
//                                             Expanded(
//                                               child: DefaultContainer(
//                                                 onTap: () {
//                                                   Navigator.of(context).push(
//                                                     MaterialPageRoute(
//                                                         builder: (context) =>
//                                                             TimerScheduleScreen(
//                                                               device: device!,
//                                                               switchCode:
//                                                                   'switch_1',
//                                                               deviceCode:
//                                                                   'countdown_1',
//                                                             )),
//                                                   );
//                                                 },
//                                                 child: Column(
//                                                   crossAxisAlignment:
//                                                       CrossAxisAlignment.center,
//                                                   mainAxisAlignment:
//                                                       MainAxisAlignment.center,
//                                                   children: [
//                                                     ConstrainedBox(
//                                                       constraints:
//                                                           const BoxConstraints(
//                                                               maxHeight: 46,
//                                                               maxWidth: 50),
//                                                       child: SvgPicture.asset(
//                                                           Assets
//                                                               .garageSchedule),
//                                                     ),
//                                                     const Flexible(
//                                                         child: SizedBox(
//                                                       height: 15,
//                                                     )),
//                                                     const Flexible(
//                                                       child: FittedBox(
//                                                         child: BodySmall(
//                                                           text: 'Schedule',
//                                                           textAlign:
//                                                               TextAlign.center,
//                                                         ),
//                                                       ),
//                                                     ),
//                                                   ],
//                                                 ),
//                                               ),
//                                             ),
//                                             const SizedBox(
//                                               width: 10,
//                                             ),
//                                             Expanded(
//                                               child: DefaultContainer(
//                                                 onTap: () {
//                                                   Navigator.of(context).push(
//                                                     MaterialPageRoute(
//                                                         builder: (context) =>
//                                                             TimerPage(
//                                                               device: device!,
//                                                               switchCode:
//                                                                   'switch_1',
//                                                               deviceCode:
//                                                                   'countdown_1',
//                                                             )),
//                                                   );
//                                                 },
//                                                 child: Column(
//                                                   crossAxisAlignment:
//                                                       CrossAxisAlignment.center,
//                                                   mainAxisAlignment:
//                                                       MainAxisAlignment.center,
//                                                   children: [
//                                                     ConstrainedBox(
//                                                       constraints:
//                                                           const BoxConstraints(
//                                                               maxHeight: 46,
//                                                               maxWidth: 50),
//                                                       child: SvgPicture.asset(
//                                                           Assets
//                                                               .garageCountdown),
//                                                     ),
//                                                     const Flexible(
//                                                         child: SizedBox(
//                                                       height: 15,
//                                                     )),
//                                                     const Flexible(
//                                                       child: FittedBox(
//                                                         child: BodySmall(
//                                                           text: 'Countdown',
//                                                           textAlign:
//                                                               TextAlign.center,
//                                                         ),
//                                                       ),
//                                                     ),
//                                                   ],
//                                                 ),
//                                               ),
//                                             ),
//                                           ],
//                                         ),
//                                       ),
//                                       const SizedBox(
//                                         height: 10,
//                                       ),
//                                       Flexible(
//                                         child: Row(
//                                           children: [
//                                             Expanded(
//                                               child: DefaultContainer(
//                                                 onTap: () {
//                                                   Navigator.of(context).push(
//                                                     MaterialPageRoute(
//                                                         builder: (context) =>
//                                                             GarageRecordsScreen(
//                                                                 GDId: device!
//                                                                     .uuid!)),
//                                                   );
//                                                 },
//                                                 child: Column(
//                                                   crossAxisAlignment:
//                                                       CrossAxisAlignment.center,
//                                                   mainAxisAlignment:
//                                                       MainAxisAlignment.center,
//                                                   children: [
//                                                     ConstrainedBox(
//                                                       constraints:
//                                                           const BoxConstraints(
//                                                               maxHeight: 46,
//                                                               maxWidth: 50),
//                                                       child: SvgPicture.asset(
//                                                           Assets
//                                                               .doorRecordsIcon),
//                                                     ),
//                                                     const Flexible(
//                                                         child: SizedBox(
//                                                       height: 15,
//                                                     )),
//                                                     const Flexible(
//                                                       child: FittedBox(
//                                                         child: BodySmall(
//                                                           text: 'Records',
//                                                           textAlign:
//                                                               TextAlign.center,
//                                                         ),
//                                                       ),
//                                                     ),
//                                                   ],
//                                                 ),
//                                               ),
//                                             ),
//                                             const SizedBox(
//                                               width: 10,
//                                             ),
//                                             Expanded(
//                                               child: DefaultContainer(
//                                                 onTap: () {
//                                                   Navigator.of(context).push(
//                                                     MaterialPageRoute(
//                                                         builder: (context) =>
//                                                             PreferencesPage(
//                                                                 GDId: device!
//                                                                     .uuid!)),
//                                                   );
//                                                 },
//                                                 child: Column(
//                                                   crossAxisAlignment:
//                                                       CrossAxisAlignment.center,
//                                                   mainAxisAlignment:
//                                                       MainAxisAlignment.center,
//                                                   children: [
//                                                     ConstrainedBox(
//                                                       constraints:
//                                                           const BoxConstraints(
//                                                               maxHeight: 46,
//                                                               maxWidth: 50),
//                                                       child: SvgPicture.asset(Assets
//                                                           .garagePreferencesIcon),
//                                                     ),
//                                                     const Flexible(
//                                                         child: SizedBox(
//                                                       height: 15,
//                                                     )),
//                                                     const Flexible(
//                                                       child: FittedBox(
//                                                         child: BodySmall(
//                                                           text: 'Preferences',
//                                                           textAlign:
//                                                               TextAlign.center,
//                                                         ),
//                                                       ),
//                                                     ),
//                                                   ],
//                                                 ),
//                                               ),
//                                             ),
//                                           ],
//                                         ),
//                                       )
//                                     ],
//                                   )),
//                             ],
//                           ),
//                         ),
//                       ],
//                     ),
//                   );
//           },
//         ),
//       ),
//     );
//   }
// }

// class GradientWidget extends StatefulWidget {
//   const GradientWidget({required this.seconds, required this.doorStatus});
//   final int seconds;
//   final bool doorStatus;

//   @override
//   State<GradientWidget> createState() => _GradientWidgetState();
// }

// class _GradientWidgetState extends State<GradientWidget>
//     with SingleTickerProviderStateMixin {
//   late ScrollController _scrollController;
//   late AnimationController _animationController;
//   late Animation<double> _itemExtentAnimation;

//   @override
//   void initState() {
//     super.initState();
//     _scrollController = ScrollController();
//     _animationController = AnimationController(
//       vsync: this,
//       duration: Duration(seconds: widget.seconds),
//     );
//     _itemExtentAnimation = Tween<double>(
//             begin: widget.doorStatus ? 0 : 15, end: widget.doorStatus ? 15 : 0)
//         .animate(
//       CurvedAnimation(
//         parent: _animationController,
//         curve: Curves.easeInOut,
//       ),
//     )..addListener(() {
//         setState(() {});
//       });

//     WidgetsBinding.instance.addPostFrameCallback((_) {
//       if (widget.doorStatus) {
//         _openAnimation();
//       } else {
//         _closeAnimation();
//       }
//     });
//   }

//   void _openAnimation() {
//     _animationController.forward();
//   }

//   void _closeAnimation() {
//     _animationController.reverse();
//   }

//   @override
//   void dispose() {
//     _scrollController.dispose();
//     _animationController.dispose();
//     super.dispose();
//   }

//   @override
//   Widget build(BuildContext context) {
//     return Container(
//       width: 300,
//       height: 300,
//       padding: EdgeInsets.only(right: 10),
//       child: Stack(
//         children: [
//           SvgPicture.asset(
//             Assets.openGarageIcon,
//             fit: BoxFit.fill,
//           ),
//           Column(
//             crossAxisAlignment: CrossAxisAlignment.center,
//             mainAxisAlignment: MainAxisAlignment.center,
//             children: [
//               Expanded(child: Container()),
//               Expanded(
//                 flex: 2,
//                 child: Center(
//                   child: Container(
//                     height: 104,
//                     child: ListView.builder(
//                       itemExtent: _itemExtentAnimation.value,
//                       controller: _scrollController,
//                       itemCount: 4,
//                       itemBuilder: (context, index) {
//                         return Center(child: GradientWidget1());
//                       },
//                     ),
//                   ),
//                 ),
//               ),
//             ],
//           ),
//         ],
//       ),
//     );
//   }
// }

// class GradientWidget1 extends StatelessWidget {
//   @override
//   Widget build(BuildContext context) {
//     return Container(
//       width: 97,
//       height: 15,
//       decoration: const BoxDecoration(
//         gradient: LinearGradient(
//           begin: Alignment.topCenter,
//           end: Alignment.bottomCenter,
//           colors: [
//             Color(0xFF017297),
//             Color(0xFF024C67),
//           ],
//           stops: [0.0, 1.0],
//         ),
//       ),
//     );
//   }
// }

class GarageDoorScreen extends StatelessWidget {
  final DeviceModel? device;

  const GarageDoorScreen({super.key, this.device});

  @override
  Widget build(BuildContext context) {
    return DefaultScaffold(
      appBar: DeviceAppbar(
        deviceName: device!.name!,
        deviceUuid: device!.uuid!,
      ),
      title: 'Garage Door Opener',
      child: BlocProvider(
        create: (context) => GarageDoorBloc(GDId: device?.uuid ?? '')
          ..add(const GarageDoorInitial()),
        child: _GarageDoorContent(device: device),
      ),
    );
  }
}

class _GarageDoorContent extends StatelessWidget {
  final DeviceModel? device;

  const _GarageDoorContent({this.device});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<GarageDoorBloc, GarageDoorSensorState>(
      builder: (context, state) {
        if (state is GarageDoorLoadingState) {
          return const _LoadingIndicator();
        }

        return RefreshIndicator(
          onRefresh: () async {
            context.read<GarageDoorBloc>().add(const GarageDoorInitial());
          },
          child: _MainContent(device: device, state: state),
        );
      },
    );
  }
}

class _LoadingIndicator extends StatelessWidget {
  const _LoadingIndicator();

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: DefaultContainer(
          width: 50, height: 50, child: CircularProgressIndicator()),
    );
  }
}

class _MainContent extends StatelessWidget {
  final DeviceModel? device;
  final GarageDoorSensorState? state;

  const _MainContent({this.device, this.state});

  @override
  Widget build(BuildContext context) {
    final garageBloc = BlocProvider.of<GarageDoorBloc>(context);
    final isDoorOpen = garageBloc.toggleDoor;
    final selectedTime = garageBloc.secondSelected;

    return ListView(
      children: [
        SizedBox(
          height: MediaQuery.sizeOf(context).height * 0.8,
          child: Column(
            children: [
              Expanded(
                flex: 5,
                child: _GarageDoorControl(
                  isDoorOpen: isDoorOpen,
                  selectedTime: selectedTime,
                ),
              ),
              Expanded(
                flex: 3,
                child: _ActionGrid(device: device),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class _GarageDoorControl extends StatelessWidget {
  final bool isDoorOpen;
  final int selectedTime;

  const _GarageDoorControl({
    required this.isDoorOpen,
    required this.selectedTime,
  });

  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        onTap: () => context.read<GarageDoorBloc>().add(
              ToggleDoorEvent(toggle: !isDoorOpen),
            ),
        child: _AnimatedGarageDoor(
          isOpen: isDoorOpen,
          duration: Duration(seconds: selectedTime),
        ),
      ),
    );
  }
}

class _AnimatedGarageDoor extends StatefulWidget {
  final bool isOpen;
  final Duration duration;

  const _AnimatedGarageDoor({
    required this.isOpen,
    required this.duration,
  });

  @override
  State<_AnimatedGarageDoor> createState() => _AnimatedGarageDoorState();
}

class _AnimatedGarageDoorState extends State<_AnimatedGarageDoor>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: widget.duration,
    )..addListener(() => setState(() {}));

    widget.isOpen ? _controller.forward() : _controller.reverse();
  }

  @override
  void didUpdateWidget(covariant _AnimatedGarageDoor oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isOpen != oldWidget.isOpen) {
      widget.isOpen ? _controller.forward() : _controller.reverse();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 290,
      height: 280,
      decoration: _buildContainerDecoration(),
      child: Stack(
        children: [
          SvgPicture.asset(Assets.openGarageIcon, fit: BoxFit.fill),
          _DoorPanels(animationValue: _controller.value),
        ],
      ),
    );
  }

  BoxDecoration _buildContainerDecoration() {
    return BoxDecoration(
      borderRadius: BorderRadius.circular(890),
      boxShadow: [
        BoxShadow(
          color: Colors.white.withOpacity(0.1),
          blurRadius: 24,
          offset: const Offset(-5, -5),
          blurStyle: BlurStyle.outer,
        ),
        BoxShadow(
          color: Colors.black.withOpacity(0.11),
          blurRadius: 25,
          offset: const Offset(5, 5),
          blurStyle: BlurStyle.outer,
        ),
        BoxShadow(
          color: Colors.black.withOpacity(0.13),
          blurRadius: 30,
          offset: const Offset(5, 5),
          blurStyle: BlurStyle.inner,
        ),
      ],
    );
  }
}

class _DoorPanels extends StatelessWidget {
  final double animationValue;

  const _DoorPanels({required this.animationValue});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Spacer(),
        Expanded(
          flex: 1,
          child: Center(
            child: Column(
              children: List.generate(
                4,
                (index) => Transform.translate(
                  offset: Offset(0, -animationValue * 15 * index),
                  child: const GradientBar(),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class GradientBar extends StatelessWidget {
  const GradientBar({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 97,
      height: 15,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Color(0xFF017297), Color(0xFF024C67)],
        ),
      ),
    );
  }
}

class _ActionGrid extends StatelessWidget {
  final DeviceModel? device;

  const _ActionGrid({this.device});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Flexible(
          child: Row(
            children: [
              _ActionButton(
                icon: Assets.garageSchedule,
                label: 'Schedule',
                onTap: () => Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => TimerScheduleScreen(
                      device: device!,
                      switchCode: 'switch_1',
                      deviceCode: 'countdown_1',
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 10),
              _ActionButton(
                icon: Assets.garageCountdown,
                label: 'Countdown',
                onTap: () => Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => TimerPage(
                      device: device!,
                      switchCode: 'switch_1',
                      deviceCode: 'countdown_1',
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 10),
        Flexible(
          child: Row(
            children: [
              _ActionButton(
                icon: Assets.doorRecordsIcon,
                label: 'Records',
                onTap: () => Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => GarageRecordsScreen(GDId: device!.uuid!),
                  ),
                ),
              ),
              const SizedBox(width: 10),
              _ActionButton(
                icon: Assets.garagePreferencesIcon,
                label: 'Preferences',
                onTap: () => Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => PreferencesPage(GDId: device!.uuid!),
                  ),
                ),
              ),
            ],
          ),
        )
      ],
    );
  }
}

class _ActionButton extends StatelessWidget {
  final String icon;
  final String label;
  final VoidCallback onTap;

  const _ActionButton({
    required this.icon,
    required this.label,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: DefaultContainer(
        onTap: onTap,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ConstrainedBox(
              constraints: const BoxConstraints(maxHeight: 46, maxWidth: 50),
              child: SvgPicture.asset(icon),
            ),
            const SizedBox(height: 15),
            FittedBox(
              child: BodySmall(text: label, textAlign: TextAlign.center),
            ),
          ],
        ),
      ),
    );
  }
}
