import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:nethive_neo/providers/visual_state_provider.dart';
import 'package:nethive_neo/providers/user_provider.dart';
import 'package:nethive_neo/pages/videos/premium_dashboard_page.dart';
import 'package:nethive_neo/pages/videos/gestor_videos_page.dart';
import 'package:nethive_neo/theme/theme.dart';
import 'package:nethive_neo/helpers/globals.dart';
import 'package:gap/gap.dart';
import 'package:go_router/go_router.dart';

class VideosLayout extends StatefulWidget {
  const VideosLayout({Key? key}) : super(key: key);

  @override
  State<VideosLayout> createState() => _VideosLayoutState();
}

class _VideosLayoutState extends State<VideosLayout> {
  int _selectedMenuIndex = 0;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  final List<MenuItem> _menuItems = [
    MenuItem(
      title: 'Dashboard',
      icon: Icons.dashboard,
      index: 0,
    ),
    MenuItem(
      title: 'Gestor de Videos',
      icon: Icons.video_library,
      index: 1,
    ),
    MenuItem(
      title: 'Configuración',
      icon: Icons.settings,
      index: 2,
    ),
  ];

  @override
  Widget build(BuildContext context) {
    final isMobile = MediaQuery.of(context).size.width <= 800;

    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: AppTheme.of(context).primaryBackground,
      drawer: isMobile ? _buildDrawer() : null,
      body: Row(
        children: [
          if (!isMobile) _buildSideMenu(),
          Expanded(
            child: Column(
              children: [
                _buildHeader(isMobile),
                Expanded(child: _buildContent()),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader(bool isMobile) {
    final isDark = AppTheme.themeMode == ThemeMode.dark;
    final isLightBackground = !isDark;

    return Container(
      padding: EdgeInsets.all(isMobile ? 16 : 24),
      decoration: BoxDecoration(
        color: AppTheme.of(context).secondaryBackground,
        border: Border(
          bottom: BorderSide(
            color: AppTheme.of(context).primaryColor.withOpacity(0.1),
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          if (isMobile)
            IconButton(
              icon: const Icon(Icons.menu),
              color: AppTheme.of(context).primaryText,
              onPressed: () => _scaffoldKey.currentState?.openDrawer(),
            ),
          // Logo de EnergyMedia
          Image.asset(
            isMobile
                ? 'assets/images/favicon.png'
                : isLightBackground
                    ? 'assets/images/logo_nh.png'
                    : 'assets/images/logo_nh_b.png',
            height: isMobile ? 32 : 75,
            fit: BoxFit.contain,
          ),
          const Spacer(),
          Text(
            _menuItems[_selectedMenuIndex].title,
            style: AppTheme.of(context).bodyText1.override(
                  fontFamily: 'Poppins',
                  color: AppTheme.of(context).secondaryText,
                ),
          ),
        ],
      ),
    );
  }

  Widget _buildSideMenu() {
    return Container(
      width: 280,
      decoration: BoxDecoration(
        color: AppTheme.of(context).secondaryBackground,
        border: Border(
          right: BorderSide(
            color: AppTheme.of(context).primaryColor.withOpacity(0.1),
            width: 1,
          ),
        ),
      ),
      child: Column(
        children: [
          // Header con gradiente premium
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(32),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  const Color(0xFF4EC9F5),
                  const Color(0xFFFFB733),
                ],
              ),
              boxShadow: [
                BoxShadow(
                  color: AppTheme.of(context).primaryColor.withOpacity(0.3),
                  blurRadius: 20,
                  offset: const Offset(0, 5),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Logo de EnergyMedia
                Image.asset(
                  'assets/images/logo_nh_b.png',
                  height: 50,
                  fit: BoxFit.contain,
                ),
                const Gap(12),
                Text(
                  'Content Manager',
                  style: AppTheme.of(context).bodyText2.override(
                        fontFamily: 'Poppins',
                        color: const Color(0xFF0B0B0D).withOpacity(0.8),
                        fontSize: 13,
                      ),
                ),
              ],
            ),
          ),

          // Menu Items
          Expanded(
            child: ListView(
              padding: const EdgeInsets.symmetric(vertical: 24, horizontal: 16),
              children: _menuItems.map((item) {
                final isSelected = _selectedMenuIndex == item.index;
                return Padding(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: _buildPremiumMenuItem(
                    icon: item.icon,
                    title: item.title,
                    isSelected: isSelected,
                    onTap: () {
                      setState(() => _selectedMenuIndex = item.index);
                    },
                  ),
                );
              }).toList(),
            ),
          ),

          // Theme Toggle en la parte inferior
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(
                  color: AppTheme.of(context).primaryColor.withOpacity(0.1),
                  width: 1,
                ),
              ),
            ),
            child: Consumer<VisualStateProvider>(
              builder: (context, visualProvider, _) {
                return _buildThemeToggle(visualProvider);
              },
            ),
          ),

          // Botón de Logout
          Container(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
            child: _buildLogoutButton(),
          ),
        ],
      ),
    );
  }

  Widget _buildPremiumMenuItem({
    required IconData icon,
    required String title,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    return MouseRegion(
      cursor: SystemMouseCursors.click,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        decoration: BoxDecoration(
          gradient: isSelected
              ? LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    const Color(0xFF4EC9F5),
                    const Color(0xFFFFB733),
                  ],
                )
              : null,
          borderRadius: BorderRadius.circular(12),
          boxShadow: isSelected
              ? [
                  BoxShadow(
                    color: AppTheme.of(context).primaryColor.withOpacity(0.3),
                    blurRadius: 12,
                    offset: const Offset(0, 4),
                  ),
                ]
              : null,
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onTap,
            borderRadius: BorderRadius.circular(12),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
              child: Row(
                children: [
                  Icon(
                    icon,
                    color: isSelected
                        ? const Color(0xFF0B0B0D)
                        : AppTheme.of(context).secondaryText,
                    size: 24,
                  ),
                  const Gap(16),
                  Expanded(
                    child: Text(
                      title,
                      style: AppTheme.of(context).bodyText1.override(
                            fontFamily: 'Poppins',
                            color: isSelected
                                ? const Color(0xFF0B0B0D)
                                : AppTheme.of(context).primaryText,
                            fontWeight:
                                isSelected ? FontWeight.bold : FontWeight.w500,
                          ),
                    ),
                  ),
                  if (isSelected)
                    Container(
                      width: 6,
                      height: 6,
                      decoration: BoxDecoration(
                        color: const Color(0xFF0B0B0D),
                        shape: BoxShape.circle,
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildThemeToggle(VisualStateProvider visualProvider) {
    final isDark = AppTheme.themeMode == ThemeMode.dark;

    return Container(
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: AppTheme.of(context).tertiaryBackground,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Expanded(
            child: _buildThemeButton(
              icon: Icons.light_mode,
              label: 'Claro',
              isSelected: !isDark,
              onTap: () {
                visualProvider.changeThemeMode(ThemeMode.light, context);
              },
            ),
          ),
          const Gap(4),
          Expanded(
            child: _buildThemeButton(
              icon: Icons.dark_mode,
              label: 'Oscuro',
              isSelected: isDark,
              onTap: () {
                visualProvider.changeThemeMode(ThemeMode.dark, context);
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildThemeButton({
    required IconData icon,
    required String label,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.symmetric(vertical: 12),
        decoration: BoxDecoration(
          gradient: isSelected
              ? LinearGradient(
                  colors: [
                    const Color(0xFF4EC9F5),
                    const Color(0xFFFFB733),
                  ],
                )
              : null,
          borderRadius: BorderRadius.circular(8),
          boxShadow: isSelected
              ? [
                  BoxShadow(
                    color: AppTheme.of(context).primaryColor.withOpacity(0.3),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ]
              : null,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              color: isSelected
                  ? const Color(0xFF0B0B0D)
                  : AppTheme.of(context).secondaryText,
              size: 20,
            ),
            const Gap(4),
            Text(
              label,
              style: TextStyle(
                color: isSelected
                    ? const Color(0xFF0B0B0D)
                    : AppTheme.of(context).secondaryText,
                fontSize: 11,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                fontFamily: 'Poppins',
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDrawer() {
    return Drawer(
      backgroundColor: AppTheme.of(context).secondaryBackground,
      child: Column(
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  const Color(0xFF4EC9F5),
                  const Color(0xFFFFB733),
                ],
              ),
            ),
            child: SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Logo de EnergyMedia
                  Image.asset(
                    'assets/images/logo_nh.png',
                    height: 45,
                    fit: BoxFit.contain,
                  ),
                  const Gap(12),
                  Text(
                    'Content Manager',
                    style: AppTheme.of(context).bodyText2.override(
                          fontFamily: 'Poppins',
                          color: const Color(0xFF0B0B0D).withOpacity(0.8),
                        ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: ListView(
              padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
              children: _menuItems.map((item) {
                final isSelected = _selectedMenuIndex == item.index;
                return Padding(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: _buildPremiumMenuItem(
                    icon: item.icon,
                    title: item.title,
                    isSelected: isSelected,
                    onTap: () {
                      setState(() => _selectedMenuIndex = item.index);
                      Navigator.pop(context);
                    },
                  ),
                );
              }).toList(),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(
                  color: AppTheme.of(context).primaryColor.withOpacity(0.1),
                  width: 1,
                ),
              ),
            ),
            child: Consumer<VisualStateProvider>(
              builder: (context, visualProvider, _) {
                return _buildThemeToggle(visualProvider);
              },
            ),
          ),

          // Botón de Logout en drawer
          Container(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
            child: _buildLogoutButton(),
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    switch (_selectedMenuIndex) {
      case 0:
        return const PremiumDashboardPage();
      case 1:
        return const GestorVideosPage();
      case 2:
        return _buildWorkInProgress();
      default:
        return const PremiumDashboardPage();
    }
  }

  Widget _buildWorkInProgress() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.construction,
            size: 64,
            color: AppTheme.of(context).tertiaryText,
          ),
          const Gap(16),
          Text(
            'Trabajo en Progreso',
            style: AppTheme.of(context).title2.override(
                  fontFamily: 'Poppins',
                  color: AppTheme.of(context).primaryText,
                  fontWeight: FontWeight.bold,
                ),
          ),
          const Gap(8),
          Text(
            'Esta sección estará disponible próximamente',
            style: AppTheme.of(context).bodyText1.override(
                  fontFamily: 'Poppins',
                  color: AppTheme.of(context).tertiaryText,
                ),
          ),
        ],
      ),
    );
  }

  Widget _buildLogoutButton() {
    return MouseRegion(
      cursor: SystemMouseCursors.click,
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () async {
            final userState = Provider.of<UserState>(context, listen: false);

            // Mostrar diálogo de confirmación
            final confirm = await showDialog<bool>(
              context: context,
              builder: (context) => AlertDialog(
                backgroundColor: AppTheme.of(context).secondaryBackground,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
                title: Text(
                  '¿Cerrar Sesión?',
                  style: AppTheme.of(context).title3.override(
                        fontFamily: 'Poppins',
                        color: AppTheme.of(context).primaryText,
                        fontWeight: FontWeight.bold,
                      ),
                ),
                content: Text(
                  '¿Estás seguro de que deseas cerrar sesión?',
                  style: AppTheme.of(context).bodyText1.override(
                        fontFamily: 'Poppins',
                        color: AppTheme.of(context).secondaryText,
                      ),
                ),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: Text(
                      'Cancelar',
                      style: TextStyle(
                        color: AppTheme.of(context).secondaryText,
                        fontFamily: 'Poppins',
                      ),
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(
                      gradient: const LinearGradient(
                        colors: [
                          Color(0xFFFF2D2D),
                          Color(0xFFFF7A3D),
                        ],
                      ),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: TextButton(
                      onPressed: () => Navigator.of(context).pop(true),
                      child: const Text(
                        'Cerrar Sesión',
                        style: TextStyle(
                          color: Colors.white,
                          fontFamily: 'Poppins',
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );

            if (confirm == true) {
              // Cerrar sesión
              await supabase.auth.signOut();
              userState.logout();

              // Navegar al login
              if (mounted) {
                context.go('/login');
              }
            }
          },
          borderRadius: BorderRadius.circular(12),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
            decoration: BoxDecoration(
              color: AppTheme.of(context).error.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: AppTheme.of(context).error.withOpacity(0.3),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.logout,
                  color: AppTheme.of(context).error,
                  size: 24,
                ),
                const Gap(16),
                Expanded(
                  child: Text(
                    'Cerrar Sesión',
                    style: AppTheme.of(context).bodyText1.override(
                          fontFamily: 'Poppins',
                          color: AppTheme.of(context).error,
                          fontWeight: FontWeight.w500,
                        ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class MenuItem {
  final String title;
  final IconData icon;
  final int index;

  MenuItem({
    required this.title,
    required this.icon,
    required this.index,
  });
}
