import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'rutas.dart';
import '../services/notification_service.dart';

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

  @override
  State<AdminView> createState() => _AdminViewState();
}

class _AdminViewState extends State<AdminView> {
  bool _camionActivo = true;
  String _rutaActual = 'RUTA-01 - Zona Centro';
  String _horaActual = _getHoraActual();
  final TextEditingController _minutosController = TextEditingController();
  int _minutosRetraso = 0;

  @override
  void initState() {
    super.initState();
    _actualizarHora();
    _cargarEstado();
  }

  @override
  void dispose() {
    _minutosController.dispose();
    super.dispose();
  }

  Future<void> _cargarEstado() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _camionActivo = !(prefs.getBool('ruta_suspendida') ?? false);
      _minutosRetraso = prefs.getInt('retraso_minutos') ?? 0;
      _minutosController.text = _minutosRetraso.toString();
    });
  }

  static String _getHoraActual() {
    final now = DateTime.now();
    int hora = now.hour > 12 ? now.hour - 12 : now.hour;
    if (hora == 0) hora = 12;
    final minuto = now.minute.toString().padLeft(2, '0');
    final periodo = now.hour >= 12 ? 'PM' : 'AM';
    return '$hora:$minuto $periodo';
  }

  void _actualizarHora() {
    Future.delayed(const Duration(seconds: 1), () {
      if (mounted) {
        setState(() {
          _horaActual = _getHoraActual();
        });
        _actualizarHora();
      }
    });
  }

  void _incrementarMinutos() {
    setState(() {
      _minutosRetraso++;
      _minutosController.text = _minutosRetraso.toString();
    });
  }

  void _decrementarMinutos() {
    if (_minutosRetraso > 0) {
      setState(() {
        _minutosRetraso--;
        _minutosController.text = _minutosRetraso.toString();
      });
    }
  }

  Future<void> _notificarRetraso() async {
    if (_minutosRetraso == 0) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Ingresa los minutos de retraso'), backgroundColor: Colors.orange),
      );
      return;
    }

    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt('retraso_minutos', _minutosRetraso);

    await NotificationService.showNotification(
      title: '⏰ Retraso en la ruta',
      body: 'El camión ha sufrido un retraso de $_minutosRetraso minutos en todas las rutas.',
    );

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Retraso de $_minutosRetraso minutos aplicado'), backgroundColor: Colors.orange),
    );
  }

  Future<void> _suspenderRuta() async {
    final prefs = await SharedPreferences.getInstance();
    final nuevaSuspension = !_camionActivo;

    await prefs.setBool('ruta_suspendida', nuevaSuspension);

    if (nuevaSuspension) {
      await NotificationService.showNotification(
        title: '⛔ Ruta suspendida',
        body: 'El servicio de recolección ha sido suspendido por hoy.',
      );
    } else {
      await prefs.remove('retraso_minutos');
      await NotificationService.showNotification(
        title: '✅ Ruta reactivada',
        body: 'El servicio de recolección ha sido reactivado.',
      );
    }

    setState(() {
      _camionActivo = !_camionActivo;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: colorAzul,
        title: const Text('Administración', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 28)),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white, size: 30),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            _buildEstadoCamion(),
            const SizedBox(height: 20),
            _buildInfoRuta(),
            const SizedBox(height: 30),
            const Divider(thickness: 2, color: Colors.grey),
            const SizedBox(height: 20),
            const Text('RETRASAR RUTA', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: colorAzul)),
            const SizedBox(height: 15),
            _buildSelectorMinutos(),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _notificarRetraso,
              style: ElevatedButton.styleFrom(backgroundColor: Colors.orange, minimumSize: const Size(double.infinity, 50), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15))),
              child: const Text('NOTIFICAR RETRASO', style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold)),
            ),
            const SizedBox(height: 30),
            ElevatedButton(
              onPressed: _suspenderRuta,
              style: ElevatedButton.styleFrom(backgroundColor: _camionActivo ? Colors.red : Colors.green, minimumSize: const Size(double.infinity, 55), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15))),
              child: Text(_camionActivo ? 'SUSPENDER RUTA' : 'REACTIVAR RUTA', style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold)),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEstadoCamion() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 4), borderRadius: BorderRadius.circular(25)),
      child: Row(
        children: [
          Icon(Icons.local_shipping, size: 60, color: _camionActivo ? Colors.green : Colors.red),
          const SizedBox(width: 15),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('Estado del camión', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500)),
              const SizedBox(height: 4),
              Text(_camionActivo ? 'ACTIVO' : 'INACTIVO', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: _camionActivo ? Colors.green : Colors.red)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildInfoRuta() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 4), borderRadius: BorderRadius.circular(25)),
      child: Column(
        children: [
          Row(
            children: [
              const Icon(Icons.route, size: 40),
              const SizedBox(width: 10),
              Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [const Text('Ruta actual', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)), Text(_rutaActual, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold))])),
            ],
          ),
          const SizedBox(height: 15),
          Row(
            children: [
              const Icon(Icons.access_time, size: 40),
              const SizedBox(width: 10),
              Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [const Text('Hora actual', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)), Text(_horaActual, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: colorAzul))])),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSelectorMinutos() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 4), borderRadius: BorderRadius.circular(25)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconButton(onPressed: _decrementarMinutos, icon: const Icon(Icons.remove_circle, size: 50), color: colorAzul),
          const SizedBox(width: 10),
          SizedBox(width: 80, child: TextField(controller: _minutosController, keyboardType: TextInputType.number, textAlign: TextAlign.center, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), decoration: const InputDecoration(border: OutlineInputBorder(), hintText: '0'), onChanged: (value) { setState(() { _minutosRetraso = int.tryParse(value) ?? 0; }); })),
          const SizedBox(width: 10),
          IconButton(onPressed: _incrementarMinutos, icon: const Icon(Icons.add_circle, size: 50), color: colorAzul),
          const SizedBox(width: 10),
          const Text('min', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }
}