// domicilios.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:geolocator/geolocator.dart';
import 'rutas.dart';
import '../models/domicilio_model.dart';
import '../services/geolocation_service.dart';

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

  @override
  State<DomiciliosView> createState() => _DomiciliosViewState();
}

class _DomiciliosViewState extends State<DomiciliosView> {
  List<Domicilio> domicilios = [];
  bool _isLoading = true;
  bool _isLoadingLocation = false;

  final TextEditingController nombreController = TextEditingController();
  final TextEditingController coloniaController = TextEditingController();
  final TextEditingController calleController = TextEditingController();
  final TextEditingController numeroController = TextEditingController();

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

  @override
  void dispose() {
    nombreController.dispose();
    coloniaController.dispose();
    calleController.dispose();
    numeroController.dispose();
    super.dispose();
  }

  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;
      });
    }
  }

  Future<void> _guardarDomicilios() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final String domiciliosString = Domicilio.encode(domicilios);
      await prefs.setString('domicilios', domiciliosString);
    } catch (e) {
      print('Error al guardar: $e');
    }
  }

  Future<bool> _showLocationPermissionDialog() async {
    if (await GeolocationService.hasPermission()) {
      return true;
    }

    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text('Permiso de ubicación'),
        content: const Text(
          'Necesitamos acceder a tu ubicación para asignar tu domicilio a la ruta correcta.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('Cancelar'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('Aceptar', style: TextStyle(color: colorAzul)),
          ),
        ],
      ),
    );

    if (result == true) {
      LocationPermission newPermission = await GeolocationService.requestPermission();
      return newPermission == LocationPermission.always ||
          newPermission == LocationPermission.whileInUse;
    }
    return false;
  }

  Future<void> _obtenerUbicacionYAgregar() async {
    setState(() {
      _isLoadingLocation = true;
    });

    final serviceEnabled = await GeolocationService.isLocationServiceEnabled();
    if (!serviceEnabled) {
      setState(() {
        _isLoadingLocation = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Activa el GPS para agregar un domicilio'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    final hasPermission = await _showLocationPermissionDialog();
    if (!hasPermission) {
      setState(() {
        _isLoadingLocation = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Necesitamos tu ubicación'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    final simplePosition = await GeolocationService.getCurrentLocation();

    setState(() {
      _isLoadingLocation = false;
    });

    if (simplePosition == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('No se pudo obtener tu ubicación.'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    _mostrarDialogoAgregarConUbicacion(simplePosition.latitude, simplePosition.longitude);
  }

  void _mostrarDialogoAgregarConUbicacion(double lat, double lng) {
    nombreController.clear();
    coloniaController.clear();
    calleController.clear();
    numeroController.clear();

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
          child: Container(
            padding: const EdgeInsets.all(20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text('Añadir domicilio', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: colorAzul)),
                const SizedBox(height: 10),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(color: Colors.green.withOpacity(0.1), borderRadius: BorderRadius.circular(12)),
                  child: Row(
                    children: [
                      Icon(Icons.location_on, color: Colors.green[700], size: 24),
                      const SizedBox(width: 10),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('📍 Ubicación obtenida', style: TextStyle(fontSize: 12, color: Colors.green[700])),
                            Text('Lat: ${lat.toStringAsFixed(6)}'),
                            Text('Lng: ${lng.toStringAsFixed(6)}'),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 15),
                _buildCampoTexto(controller: nombreController, hint: 'Nombre del domicilio', icon: Icons.home_outlined),
                const SizedBox(height: 15),
                _buildCampoTexto(controller: coloniaController, hint: 'Colonia', icon: Icons.location_city_outlined),
                const SizedBox(height: 15),
                _buildCampoTexto(controller: calleController, hint: 'Calle', icon: Icons.streetview),
                const SizedBox(height: 15),
                _buildCampoTexto(controller: numeroController, hint: 'Número', icon: Icons.numbers, keyboardType: TextInputType.number),
                const SizedBox(height: 25),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        style: OutlinedButton.styleFrom(side: BorderSide(color: colorAzul, width: 2), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15))),
                        onPressed: () => Navigator.pop(context),
                        child: const Text('Cancelar', style: TextStyle(color: colorAzul)),
                      ),
                    ),
                    const SizedBox(width: 15),
                    Expanded(
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(backgroundColor: colorAzul, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15))),
                        onPressed: () => _agregarDomicilio(latitud: lat, longitud: lng),
                        child: const Text('Agregar', style: TextStyle(color: Colors.white)),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildCampoTexto({
    required TextEditingController controller,
    required String hint,
    required IconData icon,
    TextInputType keyboardType = TextInputType.text,
  }) {
    return TextField(
      controller: controller,
      keyboardType: keyboardType,
      decoration: InputDecoration(
        hintText: hint,
        prefixIcon: Icon(icon, color: colorAzul),
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(15)),
        enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: BorderSide(color: colorAzul.withOpacity(0.5))),
        focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: colorAzul, width: 2)),
      ),
    );
  }

  void _agregarDomicilio({required double latitud, required double longitud}) async {
    if (nombreController.text.trim().isEmpty ||
        coloniaController.text.trim().isEmpty ||
        calleController.text.trim().isEmpty ||
        numeroController.text.trim().isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Llena todos los campos'), backgroundColor: Colors.red),
      );
      return;
    }

    final nuevoDomicilio = Domicilio(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      nombre: nombreController.text.trim(),
      colonia: coloniaController.text.trim(),
      calle: calleController.text.trim(),
      numero: numeroController.text.trim(),
      latitud: latitud,
      longitud: longitud,
    );

    setState(() {
      domicilios.add(nuevoDomicilio);
    });

    await _guardarDomicilios();
    Navigator.pop(context);

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Domicilio agregado'), backgroundColor: colorAzul),
    );
  }

  void _eliminarDomicilio(int index) async {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Eliminar domicilio'),
        content: Text('¿Eliminar "${domicilios[index].nombre}"?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancelar')),
          TextButton(
            onPressed: () async {
              setState(() => domicilios.removeAt(index));
              await _guardarDomicilios();
              Navigator.pop(context);
            },
            child: const Text('Eliminar', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Column(
        children: [
          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('Domicilios', style: TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.bold), textAlign: TextAlign.center),
          ),
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator(color: colorAzul))
                : domicilios.isEmpty
                ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.home_outlined, size: 100, color: Colors.grey.withOpacity(0.5)),
                  const SizedBox(height: 20),
                  Text('No hay domicilios', style: TextStyle(fontSize: 18, color: Colors.grey.withOpacity(0.7))),
                  const SizedBox(height: 10),
                  Text('Toca el botón + para agregar', style: TextStyle(fontSize: 14, color: Colors.grey.withOpacity(0.5))),
                ],
              ),
            )
                : ListView.builder(
              padding: const EdgeInsets.all(20),
              itemCount: domicilios.length,
              itemBuilder: (context, index) {
                final d = domicilios[index];
                return Padding(
                  padding: const EdgeInsets.only(bottom: 20),
                  child: Container(
                    padding: const EdgeInsets.all(15),
                    decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 4), borderRadius: BorderRadius.circular(25)),
                    child: Row(
                      children: [
                        const Icon(Icons.home_outlined, size: 60),
                        const SizedBox(width: 10),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(d.nombre, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
                              Text(d.direccionCompleta, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                              Text('📍 ${d.latitud.toStringAsFixed(4)}, ${d.longitud.toStringAsFixed(4)}', style: TextStyle(fontSize: 12, color: Colors.grey[600])),
                            ],
                          ),
                        ),
                        IconButton(onPressed: () => _eliminarDomicilio(index), icon: const Icon(Icons.delete_outline, size: 40), color: Colors.red),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(20),
            child: _isLoadingLocation
                ? Container(width: double.infinity, height: 100, decoration: BoxDecoration(color: colorAzul, borderRadius: BorderRadius.circular(20)), child: const Center(child: CircularProgressIndicator(color: Colors.white)))
                : GestureDetector(
              onTap: _obtenerUbicacionYAgregar,
              child: Container(width: double.infinity, height: 100, decoration: BoxDecoration(color: colorAzul, borderRadius: BorderRadius.circular(20)), child: const Icon(Icons.add, color: Colors.white, size: 80)),
            ),
          ),
        ],
      ),
    );
  }
}