import 'package:flutter/material.dart';
import '../../../../../shared/design_system/dashboard_theme.dart';
import '../../pages/connected_dashboard_page.dart';
import '../../pages/advanced_dashboard_page.dart';

/// Widget de navigation pour les différents types de dashboard
class DashboardNavigation extends StatefulWidget {
  final String organizationId;
  final String userId;

  const DashboardNavigation({
    super.key,
    required this.organizationId,
    required this.userId,
  });

  @override
  State<DashboardNavigation> createState() => _DashboardNavigationState();
}

class _DashboardNavigationState extends State<DashboardNavigation> {
  int _currentIndex = 0;

  final List<DashboardTab> _tabs = [
    const DashboardTab(
      title: 'Accueil',
      icon: Icons.home,
      activeIcon: Icons.home,
      type: DashboardType.home,
    ),
    const DashboardTab(
      title: 'Analytics',
      icon: Icons.analytics_outlined,
      activeIcon: Icons.analytics,
      type: DashboardType.analytics,
    ),
    const DashboardTab(
      title: 'Rapports',
      icon: Icons.assessment_outlined,
      activeIcon: Icons.assessment,
      type: DashboardType.reports,
    ),
    const DashboardTab(
      title: 'Paramètres',
      icon: Icons.settings_outlined,
      activeIcon: Icons.settings,
      type: DashboardType.settings,
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _buildCurrentPage(),
      bottomNavigationBar: _buildBottomNavigationBar(),
      floatingActionButton: _buildFloatingActionButton(),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  Widget _buildCurrentPage() {
    switch (_tabs[_currentIndex].type) {
      case DashboardType.home:
        return ConnectedDashboardPage(
          organizationId: widget.organizationId,
          userId: widget.userId,
        );
      case DashboardType.analytics:
        return AdvancedDashboardPage(
          organizationId: widget.organizationId,
          userId: widget.userId,
        );
      case DashboardType.reports:
        return _buildReportsPage();
      case DashboardType.settings:
        return _buildSettingsPage();
    }
  }

  Widget _buildBottomNavigationBar() {
    return Container(
      decoration: BoxDecoration(
        color: DashboardTheme.white,
        boxShadow: [
          BoxShadow(
            color: DashboardTheme.grey900.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: BottomAppBar(
        shape: const CircularNotchedRectangle(),
        notchMargin: 8,
        color: DashboardTheme.white,
        elevation: 0,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: DashboardTheme.spacing8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: _tabs.asMap().entries.map((entry) {
              final index = entry.key;
              final tab = entry.value;
              final isActive = index == _currentIndex;
              
              // Skip the middle item for FAB space
              if (index == 2) {
                return const SizedBox(width: 40);
              }
              
              return _buildNavItem(tab, isActive, index);
            }).toList(),
          ),
        ),
      ),
    );
  }

  Widget _buildNavItem(DashboardTab tab, bool isActive, int index) {
    return GestureDetector(
      onTap: () => setState(() => _currentIndex = index),
      child: Container(
        padding: const EdgeInsets.symmetric(
          vertical: DashboardTheme.spacing12,
          horizontal: DashboardTheme.spacing16,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              isActive ? tab.activeIcon : tab.icon,
              color: isActive ? DashboardTheme.royalBlue : DashboardTheme.grey400,
              size: 24,
            ),
            const SizedBox(height: DashboardTheme.spacing4),
            Text(
              tab.title,
              style: DashboardTheme.bodySmall.copyWith(
                color: isActive ? DashboardTheme.royalBlue : DashboardTheme.grey400,
                fontWeight: isActive ? FontWeight.w600 : FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFloatingActionButton() {
    return Container(
      decoration: BoxDecoration(
        gradient: DashboardTheme.primaryGradient,
        borderRadius: BorderRadius.circular(28),
        boxShadow: DashboardTheme.elevatedShadow,
      ),
      child: FloatingActionButton(
        onPressed: _showQuickActions,
        backgroundColor: Colors.transparent,
        elevation: 0,
        child: const Icon(
          Icons.add,
          color: DashboardTheme.white,
          size: 28,
        ),
      ),
    );
  }

  Widget _buildReportsPage() {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Rapports'),
        backgroundColor: DashboardTheme.royalBlue,
        foregroundColor: DashboardTheme.white,
        automaticallyImplyLeading: false,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.assessment,
              size: 64,
              color: DashboardTheme.grey400,
            ),
            const SizedBox(height: DashboardTheme.spacing16),
            const Text(
              'Page Rapports',
              style: DashboardTheme.titleMedium,
            ),
            const SizedBox(height: DashboardTheme.spacing8),
            Text(
              'Fonctionnalité en cours de développement',
              style: DashboardTheme.bodyMedium.copyWith(
                color: DashboardTheme.grey500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSettingsPage() {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Paramètres'),
        backgroundColor: DashboardTheme.royalBlue,
        foregroundColor: DashboardTheme.white,
        automaticallyImplyLeading: false,
      ),
      body: ListView(
        padding: const EdgeInsets.all(DashboardTheme.spacing16),
        children: [
          _buildSettingsSection(
            'Apparence',
            [
              _buildSettingsTile(
                'Thème',
                'Bleu Roi & Pétrole',
                Icons.palette,
                () {},
              ),
              _buildSettingsTile(
                'Langue',
                'Français',
                Icons.language,
                () {},
              ),
            ],
          ),
          const SizedBox(height: DashboardTheme.spacing24),
          _buildSettingsSection(
            'Notifications',
            [
              _buildSettingsTile(
                'Notifications push',
                'Activées',
                Icons.notifications,
                () {},
              ),
              _buildSettingsTile(
                'Emails',
                'Quotidien',
                Icons.email,
                () {},
              ),
            ],
          ),
          const SizedBox(height: DashboardTheme.spacing24),
          _buildSettingsSection(
            'Données',
            [
              _buildSettingsTile(
                'Synchronisation',
                'Automatique',
                Icons.sync,
                () {},
              ),
              _buildSettingsTile(
                'Cache',
                'Vider le cache',
                Icons.storage,
                () {},
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSettingsSection(String title, List<Widget> children) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: DashboardTheme.titleMedium,
        ),
        const SizedBox(height: DashboardTheme.spacing12),
        Container(
          decoration: DashboardTheme.cardDecoration,
          child: Column(children: children),
        ),
      ],
    );
  }

  Widget _buildSettingsTile(
    String title,
    String subtitle,
    IconData icon,
    VoidCallback onTap,
  ) {
    return ListTile(
      leading: Icon(icon, color: DashboardTheme.royalBlue),
      title: Text(title, style: DashboardTheme.bodyMedium),
      subtitle: Text(subtitle, style: DashboardTheme.bodySmall),
      trailing: const Icon(
        Icons.chevron_right,
        color: DashboardTheme.grey400,
      ),
      onTap: onTap,
    );
  }

  void _showQuickActions() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        decoration: const BoxDecoration(
          color: DashboardTheme.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(DashboardTheme.borderRadiusLarge),
            topRight: Radius.circular(DashboardTheme.borderRadiusLarge),
          ),
        ),
        padding: const EdgeInsets.all(DashboardTheme.spacing20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: DashboardTheme.grey300,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(height: DashboardTheme.spacing20),
            const Text(
              'Actions Rapides',
              style: DashboardTheme.titleMedium,
            ),
            const SizedBox(height: DashboardTheme.spacing20),
            GridView.count(
              crossAxisCount: 3,
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              crossAxisSpacing: DashboardTheme.spacing16,
              mainAxisSpacing: DashboardTheme.spacing16,
              children: [
                _buildQuickActionItem('Nouveau\nMembre', Icons.person_add, DashboardTheme.success),
                _buildQuickActionItem('Créer\nÉvénement', Icons.event_available, DashboardTheme.royalBlue),
                _buildQuickActionItem('Ajouter\nContribution', Icons.payment, DashboardTheme.tealBlue),
                _buildQuickActionItem('Envoyer\nMessage', Icons.message, DashboardTheme.warning),
                _buildQuickActionItem('Générer\nRapport', Icons.assessment, DashboardTheme.info),
                _buildQuickActionItem('Paramètres', Icons.settings, DashboardTheme.grey600),
              ],
            ),
            const SizedBox(height: DashboardTheme.spacing20),
          ],
        ),
      ),
    );
  }

  Widget _buildQuickActionItem(String title, IconData icon, Color color) {
    return GestureDetector(
      onTap: () {
        Navigator.pop(context);
        // TODO: Implémenter l'action
      },
      child: Container(
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(DashboardTheme.borderRadius),
          border: Border.all(color: color.withOpacity(0.3)),
        ),
        padding: const EdgeInsets.all(DashboardTheme.spacing12),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: color, size: 24),
            const SizedBox(height: DashboardTheme.spacing8),
            Text(
              title,
              style: DashboardTheme.bodySmall.copyWith(
                color: color,
                fontWeight: FontWeight.w600,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
}

class DashboardTab {
  final String title;
  final IconData icon;
  final IconData activeIcon;
  final DashboardType type;

  const DashboardTab({
    required this.title,
    required this.icon,
    required this.activeIcon,
    required this.type,
  });
}

enum DashboardType {
  home,
  analytics,
  reports,
  settings,
}
