import 'package:flutter/material.dart';

import '../models/school.dart';
import '../services/vanguard_api.dart';
import '../config/api_config.dart';

import '../screens/login_page.dart';
import '../screens/medical_certificates_page.dart';
import '../screens/lessons_page.dart';
import '../screens/orders_detail_page.dart';
import '../screens/account_page.dart';
import '../screens/settings_page.dart';
import '../screens/teacher_panel_page.dart';
import '../services/role_service.dart';
import 'package:url_launcher/url_launcher.dart';

class AppDrawer extends StatelessWidget {
  final String token;
  final School school;
  final String? userFirstName;

  const AppDrawer({
    super.key,
    required this.token,
    required this.school,
    this.userFirstName,
  });

  String get _name => (userFirstName ?? '').trim();
  String get _avatarLetter => _name.isNotEmpty ? _name[0].toUpperCase() : 'U';

  String? get _schoolLogoUrl {
    final raw = (school.logo ?? '').toString().trim();
    if (raw.isEmpty) return null;

    // base: https://app.yogibook.com/public/userarea/
    return '${ApiConfig.scheme}://${ApiConfig.host}/public/userarea/$raw';
  }

  Future<void> _openUrl(BuildContext context, String url) async {
    final uri = Uri.parse(url);
    final ok = await launchUrl(uri, mode: LaunchMode.externalApplication);
    if (!ok && context.mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Impossibile aprire il link.')),
      );
    }
  }

  Future<void> _logout(BuildContext context) async {
    final ok = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        title: const Text('Conferma logout'),
        content: const Text('Vuoi uscire dal tuo account?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('Annulla'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('Logout'),
          ),
        ],
      ),
    );

    if (ok != true) return;

    Navigator.of(context).pop(); // chiude drawer

    try {
      await VanguardApi.logout(token: token);
    } catch (_) {}

    if (!context.mounted) return;

    Navigator.of(context).pushAndRemoveUntil(
      MaterialPageRoute(builder: (_) => const LoginPage()),
      (route) => false,
    );
  }

  @override
  Widget build(BuildContext context) {
    final logoUrl = _schoolLogoUrl;

    return Drawer(
      child: SafeArea(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            _DrawerHeaderWide(
              schoolName: school.name,
              logoUrl: logoUrl,
              fallbackLetter: _avatarLetter,
            ),

            // Sezione insegnante: visibile solo a staff (Admin/teacher).
            FutureBuilder<UserRole>(
              future: RoleService.fetchMyRole(token: token),
              builder: (context, snap) {
                final isStaff = snap.data?.isStaff ?? false;
                if (!isStaff) return const SizedBox.shrink();
                return Column(
                  children: [
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.fromLTRB(16, 10, 16, 4),
                      child: const Text(
                        'INSEGNANTE',
                        style: TextStyle(
                          fontSize: 11,
                          fontWeight: FontWeight.w900,
                          color: Color(0xFF10B981),
                          letterSpacing: 0.5,
                        ),
                      ),
                    ),
                    ListTile(
                      leading: const Icon(Icons.calendar_month_rounded),
                      title: const Text('Pannello classi'),
                      onTap: () {
                        Navigator.of(context).pop();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (_) => TeacherPanelPage(
                              token: token,
                              school: school,
                              userFirstName: userFirstName,
                            ),
                          ),
                        );
                      },
                    ),
                    const Divider(height: 1),
                  ],
                );
              },
            ),

            ListTile(
              leading: const Icon(Icons.medical_information),
              title: const Text('Certificati medici'),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => MedicalCertificatesPage(
                      token: token,
                      school: school,
                      userFirstName: userFirstName,
                    ),
                  ),
                );
              },
            ),

            ListTile(
              leading: const Icon(Icons.event_note_rounded),
              title: const Text('Lezioni'),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder: (_) => LessonsPage(
                      token: token,
                      school: school,
                      userFirstName: userFirstName,
                    ),
                  ),
                );
              },
            ),

            ListTile(
              leading: const Icon(Icons.shopping_bag_rounded),
              title: const Text('Ordini'),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => OrdersDetailPage(
                      token: token,
                      school: school,
                      userFirstName: userFirstName,
                    ),
                  ),
                );
              },
            ),

            ListTile(
              leading: const Icon(Icons.person_rounded),
              title: const Text('Account'),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => AccountPage(
                      token: token,
                      school: school,
                      userFirstName: userFirstName,
                    ),
                  ),
                );
              },
            ),

            ListTile(
              leading: const Icon(Icons.settings_rounded),
              title: const Text('Impostazioni'),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => SettingsPage(
                      token: token,
                      school: school,
                      userFirstName: userFirstName,
                    ),
                  ),
                );
              },
            ),

            const Divider(height: 1),

            ListTile(
              leading: const Icon(Icons.privacy_tip_outlined),
              title: const Text('Cookie e Privacy Policy'),
              onTap: () {
                Navigator.of(context).pop();
                _openUrl(context, 'https://yogasoul.it/cookie-policy/');
              },
            ),

            ListTile(
              leading: const Icon(Icons.description_outlined),
              title: const Text('Condizioni generali'),
              onTap: () {
                Navigator.of(context).pop();
                _openUrl(
                  context,
                  'https://yogasoul.it/condizioni-generali-di-vendita/',
                );
              },
            ),

            const Divider(height: 1),

            ListTile(
              leading: const Icon(Icons.logout),
              title: const Text('Logout'),
              onTap: () => _logout(context),
            ),
          ],
        ),
      ),
    );
  }
}

class _DrawerHeaderWide extends StatelessWidget {
  final String schoolName;
  final String? logoUrl;
  final String fallbackLetter;

  const _DrawerHeaderWide({
    required this.schoolName,
    required this.logoUrl,
    required this.fallbackLetter,
  });

  @override
  Widget build(BuildContext context) {
    const green = Color(0xFF10B981);

    return Container(
      // Header largo quanto il drawer
      padding: const EdgeInsets.fromLTRB(16, 14, 16, 14),
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFF4F6FA), Color(0xFFEFF7F3)],
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Menu',
            style: TextStyle(fontSize: 22, fontWeight: FontWeight.w900),
          ),
          const SizedBox(height: 12),

          // ✅ BOX LOGO LARGO + PIÙ ALTO + IN RATIO (non taglia)
          Container(
            width: double.infinity,
            height: 140, // <-- aumenta qui (es. 140/160/180)
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
              boxShadow: const [
                BoxShadow(
                  blurRadius: 18,
                  color: Color(0x12000000),
                  offset: Offset(0, 10),
                ),
              ],
              border: Border.all(color: const Color(0x14000000)),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: logoUrl == null
                  ? _LogoFallback(letter: fallbackLetter)
                  : Padding(
                      padding: const EdgeInsets.all(10), // respiro per logo
                      child: Image.network(
                        logoUrl!,
                        width: double.infinity, // ✅ solo larghezza “imposta”
                        fit: BoxFit.contain, // ✅ mantiene ratio, non taglia
                        errorBuilder: (_, __, ___) =>
                            _LogoFallback(letter: fallbackLetter),
                      ),
                    ),
            ),
          ),

          const SizedBox(height: 10),

          // Nome scuola sotto
          Text(
            schoolName,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(
              color: Colors.black87,
              fontWeight: FontWeight.w900,
              fontSize: 22,
            ),
          ),

          const SizedBox(height: 6),

          // badge piccolo opzionale, fa “design”
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
            decoration: BoxDecoration(
              color: green.withOpacity(0.12),
              borderRadius: BorderRadius.circular(999),
            ),
            child: const Text(
              'Scuola selezionata',
              style: TextStyle(
                color: green,
                fontWeight: FontWeight.w900,
                fontSize: 11,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _LogoFallback extends StatelessWidget {
  final String letter;
  const _LogoFallback({required this.letter});

  @override
  Widget build(BuildContext context) {
    const green = Color(0xFF10B981);

    return Container(
      width: double.infinity,
      height: double.infinity,
      alignment: Alignment.center,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFE7F8F1), Color(0xFFF4F6FA)],
        ),
      ),
      child: Container(
        width: 44,
        height: 44,
        decoration: const BoxDecoration(color: green, shape: BoxShape.circle),
        alignment: Alignment.center,
        child: Text(
          letter,
          style: const TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w900,
            fontSize: 16,
          ),
        ),
      ),
    );
  }
}
