import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
import '../models/models.dart';
import '../widgets/widgets.dart' as w;

class AlertsScreen extends StatefulWidget {
  const AlertsScreen({super.key});

  @override
  State<AlertsScreen> createState() => _AlertsScreenState();
}

class _AlertsScreenState extends State<AlertsScreen> {
  // Alerta activa de ejemplo
  final AlertaModel? _alertaActiva = AlertaModel(
    id: 'alerta-001',
    tipo: TipoAlerta.cercana,
    distanciaMetros: 180,
    fecha: DateTime.now(),
    direccionCasa: 'Av. Insurgentes 245',
    leida: false,
  );

  // Historial de ejemplo
  final List<AlertaModel> _historial = [
    AlertaModel(
      id: 'h-001',
      tipo: TipoAlerta.cercana,
      distanciaMetros: 200,
      fecha: DateTime.now().subtract(const Duration(hours: 1)),
      direccionCasa: 'Av. Insurgentes 245',
      leida: true,
    ),
    AlertaModel(
      id: 'h-002',
      tipo: TipoAlerta.cercana,
      distanciaMetros: 200,
      fecha: DateTime.now().subtract(const Duration(days: 2, hours: 2)),
      direccionCasa: 'Av. Insurgentes 245',
      leida: true,
    ),
    AlertaModel(
      id: 'h-003',
      tipo: TipoAlerta.cercana,
      distanciaMetros: 200,
      fecha: DateTime.now().subtract(const Duration(days: 4, hours: 1, minutes: 30)),
      direccionCasa: 'Av. Insurgentes 245',
      leida: true,
    ),
    AlertaModel(
      id: 'h-004',
      tipo: TipoAlerta.cercana,
      distanciaMetros: 200,
      fecha: DateTime.now().subtract(const Duration(days: 7, hours: 3)),
      direccionCasa: 'Av. Insurgentes 245',
      leida: true,
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: AppBar(
        title: const Text('Alertas'),
        actions: [
          TextButton(
            onPressed: () {},
            child: const Text('Limpiar',
                style: TextStyle(color: Colors.white, fontSize: 13)),
          ),
        ],
      ),
      body: RefreshIndicator(
        color: AppTheme.primary,
        onRefresh: () async {
          await Future.delayed(const Duration(milliseconds: 800));
        },
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            // ── Alerta activa ───────────────────────────────────────────
            if (_alertaActiva != null) ...[
              _AlertaActivaCard(alerta: _alertaActiva!),
              const SizedBox(height: 20),
            ],

            // ── Historial ────────────────────────────────────────────────
            if (_historial.isEmpty)
              _EmptyState()
            else ...[
              w.SectionTitle(title: 'Historial de alertas'),
              ..._historial.map((a) => _AlertaHistorialItem(alerta: a)),
            ],
          ],
        ),
      ),
    );
  }
}

// ── Tarjeta de alerta activa ──────────────────────────────────────────────────
class _AlertaActivaCard extends StatelessWidget {
  final AlertaModel alerta;
  const _AlertaActivaCard({required this.alerta});

  @override
  Widget build(BuildContext context) {
    final progreso = (1 - (alerta.distanciaMetros / 400)).clamp(0.0, 1.0);

    return Container(
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(
        color: AppTheme.primaryLight,
        borderRadius: BorderRadius.circular(AppTheme.radiusLg),
        border: Border.all(color: AppTheme.primaryMid),
        boxShadow: AppTheme.softShadow,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Header
          Row(
            children: [
              Container(
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  color: AppTheme.primary,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const Icon(Icons.notifications_active,
                    color: Colors.white, size: 22),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('¡El camión está cerca!',
                        style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.w700,
                            color: AppTheme.primaryDark)),
                    Text(alerta.fechaFormateada,
                        style: const TextStyle(
                            fontSize: 12, color: AppTheme.primary)),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: AppTheme.primary,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: const Text('Ahora',
                    style: TextStyle(
                        fontSize: 11,
                        fontWeight: FontWeight.w600,
                        color: Colors.white)),
              ),
            ],
          ),

          const SizedBox(height: 16),

          // Distancia
          Text(
            'El camión se encuentra a',
            style: const TextStyle(
                fontSize: 13, color: AppTheme.primaryDark),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                alerta.distanciaTexto,
                style: const TextStyle(
                    fontSize: 36,
                    fontWeight: FontWeight.w700,
                    color: AppTheme.primary,
                    height: 1.1),
              ),
              const SizedBox(width: 8),
              Padding(
                padding: const EdgeInsets.only(bottom: 6),
                child: Text(
                  'de tu casa en ${alerta.direccionCasa}',
                  style: const TextStyle(
                      fontSize: 13, color: AppTheme.primaryDark),
                ),
              ),
            ],
          ),

          const SizedBox(height: 14),

          // Tiempo estimado
          Row(
            children: [
              const Text('Llegada estimada:',
                  style: TextStyle(
                      fontSize: 12, color: AppTheme.primaryDark)),
              const SizedBox(width: 6),
              Text(
                alerta.tiempoEstimadoTexto,
                style: const TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w700,
                    color: AppTheme.primary),
              ),
            ],
          ),

          const SizedBox(height: 8),

          // Barra de progreso
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: LinearProgressIndicator(
              value: progreso,
              backgroundColor: AppTheme.primaryMid.withOpacity(0.4),
              valueColor: const AlwaysStoppedAnimation<Color>(AppTheme.primary),
              minHeight: 7,
            ),
          ),

          const SizedBox(height: 4),

          Row(
            children: const [
              Text('Lejos',
                  style: TextStyle(fontSize: 10, color: AppTheme.primary)),
              Spacer(),
              Text('Tu casa',
                  style: TextStyle(fontSize: 10, color: AppTheme.primary)),
            ],
          ),

          const SizedBox(height: 14),

          // Botón ver en mapa
          GestureDetector(
            onTap: () {},
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(vertical: 10),
              decoration: BoxDecoration(
                color: AppTheme.primary,
                borderRadius: BorderRadius.circular(AppTheme.radiusSm),
              ),
              child: const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.map_outlined, color: Colors.white, size: 16),
                  SizedBox(width: 6),
                  Text('Ver en el mapa',
                      style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                          color: Colors.white)),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// ── Ítem de historial ─────────────────────────────────────────────────────────
class _AlertaHistorialItem extends StatelessWidget {
  final AlertaModel alerta;
  const _AlertaHistorialItem({required this.alerta});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
      decoration: BoxDecoration(
        color: AppTheme.surface,
        borderRadius: BorderRadius.circular(AppTheme.radiusMd),
        border: Border.all(color: AppTheme.border, width: 0.5),
        boxShadow: AppTheme.softShadow,
      ),
      child: Row(
        children: [
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(
              color: AppTheme.background,
              borderRadius: BorderRadius.circular(10),
            ),
            child: const Icon(Icons.notifications_outlined,
                color: AppTheme.textSecondary, size: 18),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Camión a ${alerta.distanciaTexto}',
                  style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: AppTheme.textPrimary),
                ),
                const SizedBox(height: 2),
                Text(alerta.fechaFormateada,
                    style: const TextStyle(
                        fontSize: 12, color: AppTheme.textSecondary)),
              ],
            ),
          ),
          _EtiquetaDia(texto: alerta.etiquetaFecha),
        ],
      ),
    );
  }
}

// ── Etiqueta de día ───────────────────────────────────────────────────────────
class _EtiquetaDia extends StatelessWidget {
  final String texto;
  const _EtiquetaDia({required this.texto});

  @override
  Widget build(BuildContext context) {
    final esHoy = texto == 'Hoy';
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: esHoy ? AppTheme.primaryLight : AppTheme.background,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Text(
        texto,
        style: TextStyle(
          fontSize: 11,
          fontWeight: FontWeight.w600,
          color: esHoy ? AppTheme.primaryDark : AppTheme.textSecondary,
        ),
      ),
    );
  }
}

// ── Estado vacío ──────────────────────────────────────────────────────────────
class _EmptyState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 60),
      child: Column(
        children: [
          Container(
            width: 72,
            height: 72,
            decoration: BoxDecoration(
              color: AppTheme.primaryLight,
              shape: BoxShape.circle,
            ),
            child: const Icon(Icons.notifications_outlined,
                color: AppTheme.primary, size: 34),
          ),
          const SizedBox(height: 16),
          const Text('Sin alertas por ahora',
              style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: AppTheme.textPrimary)),
          const SizedBox(height: 6),
          const Text(
            'Te notificaremos cuando el camión\nesté cerca de tu casa.',
            textAlign: TextAlign.center,
            style: TextStyle(
                fontSize: 13, color: AppTheme.textSecondary, height: 1.5),
          ),
        ],
      ),
    );
  }
}
