import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../../core/theme/app_theme.dart';
import '../../core/widgets/app_widgets.dart';
import '../../core/services/auth_controller.dart';
import 'models/profile_user.dart';
import 'providers/profile_providers.dart';

class ProfileScreen extends ConsumerWidget {
  const ProfileScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final authRole =
        ref.watch(authControllerProvider).asData?.value.userRole ?? 'citizen';
    final userAsync = ref.watch(currentUserProvider);

    return Scaffold(
      backgroundColor: AppTheme.background,
      body: RefreshIndicator(
        color: AppTheme.primary,
        onRefresh: () async {
          ref.invalidate(currentUserProvider);
          await ref.read(currentUserProvider.future);
        },
        child: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
              child: _ProfileHeroHeader(
                user: userAsync.asData?.value,
                fallbackRole: authRole,
              ),
            ),
            SliverPadding(
              padding: const EdgeInsets.fromLTRB(24, 24, 24, 0),
              sliver: SliverList(
                delegate: SliverChildListDelegate([
                  const AppSectionTitle(title: 'Cuenta'),
                  AppMenuTile(
                    icon: Icons.person_outline,
                    title: 'Editar perfil',
                    subtitle: 'Nombre, correo, teléfono y contraseña',
                    onTap: () => context.push('/edit-profile'),
                  ),
                  if ((userAsync.asData?.value.isAdmin ?? false) ||
                      authRole == 'admin')
                    AppMenuTile(
                      icon: Icons.admin_panel_settings_outlined,
                      title: 'Panel de administración',
                      subtitle: 'Gestiona usuarios, rutas y camiones',
                      onTap: () => context.go('/admin'),
                    ),

                  const SizedBox(height: 16),
                  const AppSectionTitle(title: 'Herramientas'),
                  AppMenuTile(
                    icon: Icons.feedback_outlined,
                    title: 'Buzón de retroalimentación',
                    subtitle: 'Califica el servicio de recolección',
                    onTap: () => context.push('/feedback'),
                  ),

                  const SizedBox(height: 16),
                  const AppSectionTitle(title: 'Soporte'),
                  AppMenuTile(
                    icon: Icons.help_outline,
                    title: 'Ayuda y preguntas frecuentes',
                    subtitle: 'Chatea con nuestro asistente',
                    onTap: () => context.push('/help'),
                  ),
                  AppMenuTile(
                    icon: Icons.bug_report_outlined,
                    title: 'Reportar un problema',
                    subtitle: 'Reporta una unidad o incidente',
                    onTap: () => context.push('/report-issue'),
                  ),
                  AppMenuTile(
                    icon: Icons.info_outline,
                    title: 'Acerca de la app',
                    onTap: () => context.push('/about'),
                  ),

                  const SizedBox(height: 16),
                  AppMenuTile(
                    icon: Icons.logout_rounded,
                    title: 'Cerrar sesión',
                    iconColor: AppTheme.danger,
                    titleColor: AppTheme.danger,
                    trailing: const SizedBox.shrink(),
                    onTap: () => _confirmarCerrarSesion(context, ref),
                  ),

                  const SizedBox(height: 32),
                  const Center(
                    child: Text(
                      'Recolecta v1.0.0\nServicio de Limpia · Celaya, Gto.',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 12,
                        color: AppTheme.textHint,
                        height: 1.6,
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),
                ]),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _confirmarCerrarSesion(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        backgroundColor: AppTheme.surface,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(AppTheme.radiusLg),
        ),
        title: const Text(
          'Cerrar sesión',
          style: TextStyle(
            fontSize: 17,
            fontWeight: FontWeight.w700,
            color: AppTheme.textPrimary,
          ),
        ),
        content: const Text(
          '¿Estás seguro de que deseas cerrar sesión?',
          style: TextStyle(fontSize: 14, color: AppTheme.textSecondary),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            style: TextButton.styleFrom(
              foregroundColor: AppTheme.textSecondary,
            ),
            child: const Text('Cancelar'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(ctx);
              await ref.read(authControllerProvider.notifier).logout();
              if (context.mounted) context.go('/login');
            },
            style: TextButton.styleFrom(foregroundColor: AppTheme.danger),
            child: const Text(
              'Cerrar sesión',
              style: TextStyle(fontWeight: FontWeight.w600),
            ),
          ),
        ],
      ),
    );
  }
}

// ── Hero header con gradiente ─────────────────────────────────────────────────
class _ProfileHeroHeader extends StatelessWidget {
  final ProfileUser? user;
  final String fallbackRole;
  const _ProfileHeroHeader({required this.user, required this.fallbackRole});

  @override
  Widget build(BuildContext context) {
    final role = user?.role ?? fallbackRole;
    final isAdmin = role == 'admin';
    final isDriver = role == 'driver';
    final initials = user?.initials ?? 'U';
    final displayName = user?.displayName ?? 'Usuario';
    final email = user?.email ?? '…';
    final roleLabel = isAdmin
        ? 'Administrador'
        : isDriver
        ? 'Chofer'
        : 'Ciudadano';

    return Container(
      padding: EdgeInsets.fromLTRB(
        24,
        MediaQuery.of(context).padding.top + 20,
        24,
        32,
      ),
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFF4A0E26), Color(0xFF9B1B4A)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(28),
          bottomRight: Radius.circular(28),
        ),
      ),
      child: Column(
        children: [
          // Avatar con iniciales
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.15),
              shape: BoxShape.circle,
              border: Border.all(
                color: Colors.white.withValues(alpha: 0.4),
                width: 2,
              ),
            ),
            child: Center(
              child: Text(
                initials,
                style: const TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.w700,
                  color: Colors.white,
                ),
              ),
            ),
          ),
          const SizedBox(height: 14),
          Text(
            displayName,
            style: const TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w700,
              color: Colors.white,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            email,
            style: TextStyle(
              fontSize: 13,
              color: Colors.white.withValues(alpha: 0.8),
            ),
          ),
          const SizedBox(height: 10),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 5),
            decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.18),
              borderRadius: BorderRadius.circular(AppTheme.radiusFull),
              border: Border.all(
                color: Colors.white.withValues(alpha: 0.3),
              ),
            ),
            child: Text(
              roleLabel,
              style: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
