import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'rutas.dart';
import '../models/domicilio_model.dart';
import 'mapa_expandible.dart';

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

  @override
  State<HorariosView> createState() => _HorariosViewState();
}

class _HorariosViewState extends State<HorariosView> {
  List<Domicilio> domicilios = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _cargarDomicilios();
  }

  Future<void> _cargarDomicilios() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final String? domiciliosString = prefs.getString('domicilios');

      setState(() {
        if (domiciliosString != null && domiciliosString.isNotEmpty) {
          domicilios = Domicilio.decode(domiciliosString);
        }
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: SafeArea(
        child: Column(
          children: [
            // AppBar personalizado
            Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16),
              decoration: const BoxDecoration(
                color: colorAzul,
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(20),
                  bottomRight: Radius.circular(20),
                ),
              ),
              child: const Text(
                'Mis Rutas',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 32,
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
              ),
            ),
            // Lista de domicilios
            Expanded(
              child: _isLoading
                  ? const Center(child: CircularProgressIndicator(color: colorAzul))
                  : domicilios.isEmpty
                  ? Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.location_on_outlined,
                      size: 100,
                      color: Colors.grey.withOpacity(0.5),
                    ),
                    const SizedBox(height: 20),
                    Text(
                      'No hay domicilios agregados',
                      style: TextStyle(
                        fontSize: 18,
                        color: Colors.grey.withOpacity(0.7),
                      ),
                    ),
                    const SizedBox(height: 10),
                    Text(
                      'Agrega domicilios desde la pestaña Domicilios',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey.withOpacity(0.5),
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              )
                  : ListView.builder(
                padding: const EdgeInsets.all(20),
                itemCount: domicilios.length,
                itemBuilder: (context, index) {
                  final domicilio = domicilios[index];
                  return _buildDomicilioCard(domicilio, index);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDomicilioCard(Domicilio domicilio, int index) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 20),
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.black, width: 4),
          borderRadius: BorderRadius.circular(25),
        ),
        child: Column(
          children: [
            // Contenido principal del domicilio
            Padding(
              padding: const EdgeInsets.all(15),
              child: Column(
                children: [
                  // Info principal
                  Row(
                    children: [
                      const Icon(Icons.home_outlined, size: 60),
                      const SizedBox(width: 10),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              domicilio.nombre,
                              style: const TextStyle(
                                fontSize: 22,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              domicilio.direccionCompleta,
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              '📍 ${domicilio.latitud.toStringAsFixed(4)}, ${domicilio.longitud.toStringAsFixed(4)}',
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  // Fila de horario y botón de mapa
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // Horario (placeholder para API del backend)
                      Expanded(
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
                          decoration: BoxDecoration(
                            color: colorAzul.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Row(
                            children: [
                              Icon(Icons.access_time, color: colorAzul, size: 20),
                              const SizedBox(width: 8),
                              Text(
                                'Horario: ${_obtenerHorarioEstimado(index)}',
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500,
                                  color: colorAzul,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(width: 10),
                      // Botón/flecha para mapa desplegable
                      MapaExpandible(
                        latitud: domicilio.latitud,
                        longitud: domicilio.longitud,
                        nombreDomicilio: domicilio.nombre,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Horario estimado (placeholder para cuando conectes con el backend)
  String _obtenerHorarioEstimado(int index) {
    // Esto es solo un placeholder - aquí irá la llamada a tu API
    final horarios = ['8:00 AM - 9:00 AM', '9:30 AM - 10:30 AM', '11:00 AM - 12:00 PM', '1:00 PM - 2:00 PM', '3:00 PM - 4:00 PM', '5:00 PM - 6:00 PM'];
    return horarios[index % horarios.length];
  }
}