from django.db import models
from category.models import category
from location.models import Location
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.utils.html import format_html

class Property(models.Model):
    # Información Básica (Obligatoria)
    property_name = models.CharField(_('nombre de la propiedad'), max_length=200)
    slug = models.SlugField(_('slug'), max_length=200, unique=True)
    description = models.TextField(_('descripción'), blank=True)
    PURPOSE_CHOICES = [
        ('rent', _('Para rentar')),
        ('sale', _('Para vender')),
    ]
    
    purpose = models.CharField(
        _('tipo de transacción'),
        max_length=10,
        choices=PURPOSE_CHOICES,
        default='rent'
    )
    price = models.IntegerField(_('precio'))
    category = models.ForeignKey(category, verbose_name=_('tipo de propiedad'), on_delete=models.CASCADE)
    main_image = models.ImageField(_('imagen principal'), upload_to='photos/properties', null=True, blank=True)
    created_date = models.DateTimeField(_('fecha de creación'), auto_now_add=True)
    modified_date = models.DateTimeField(_('fecha de modificación'), auto_now=True)
    
    # Ubicación (Obligatoria)
    address = models.CharField(_('dirección exacta'), max_length=200)
    location = models.ForeignKey(Location, verbose_name=_('zona/barrio'), on_delete=models.CASCADE) 
    floor = models.IntegerField(_('piso'), blank=True, null=True)
    maps_url = models.URLField(_('URL de Google Maps'), blank=True)
    
    # Características Principales (Obligatoria)
    area = models.IntegerField(_('área (m²)'), default=36)
    bedrooms = models.IntegerField(_('habitaciones'), default=1)
    bathrooms = models.IntegerField(_('baños'), default=1)
    is_furnished = models.BooleanField(_('amoblado'), default=False)
    
    # Estado y Disponibilidad
    is_available = models.BooleanField(_('disponible'), default=True)
    is_featured = models.BooleanField(_('destacado'), default=False)
    is_verified = models.BooleanField(_('verificado'), default=False)
    
    # Características Adicionales (Opcionales)
    FEATURES = (
        ('balcony', _('Balcón/Terraza')),
        ('pool', _('Piscina')),
        ('gym', _('Gimnasio')),
        ('parking', _('Parqueadero')),
        ('elevator', _('Ascensor')),
        ('security', _('Seguridad 24/7')),
        ('concierge', _('Conserje')),
        ('green_areas', _('Zonas verdes')),
    )
    features = models.JSONField(_('características'), default=list, blank=True)
    
    # Servicios Incluidos (Opcionales)
    SERVICES = (
        ('wifi', _('WiFi')),
        ('ac', _('Aire acondicionado')),
        ('hot_water', _('Agua caliente')),
        ('cleaning', _('Limpieza semanal')),
        ('maintenance', _('Mantenimiento')),
    )
    services = models.JSONField(_('servicios incluidos'), default=list, blank=True)
    
    # Reglas (Opcionales)
    RULES = (
        ('pets', _('Mascotas permitidas')),
        ('smoking', _('Permitido fumar')),
        ('parties', _('Fiestas permitidas')),
    )
    rules = models.JSONField(_('reglas'), default=list, blank=True)
    
    # Multimedia (Opcional)
    video_url = models.URLField(_('URL de video'), blank=True)
    virtual_tour_url = models.URLField(_('URL de tour virtual'), blank=True)
    
    # Información Adicional (Opcional)
    notes = models.TextField(_('notas internas'), blank=True)
    
    def get_url(self):
        return reverse('property_detail', args=[self.category.slug, self.slug])

    # Agregar estos métodos a tu clase Property

    def get_features_display(self):
        """Retorna las características con sus valores traducidos"""
        features_dict = dict(self.FEATURES)
        return [features_dict.get(feature, feature) for feature in self.features]

    def get_services_display(self):
        """Retorna los servicios con sus valores traducidos"""
        services_dict = dict(self.SERVICES)
        return [services_dict.get(service, service) for service in self.services]

    def get_rules_display(self):
        """Retorna las reglas con sus valores traducidos"""
        rules_dict = dict(self.RULES)
        return [rules_dict.get(rule, rule) for rule in self.rules]

    class Meta:
        verbose_name = _('propiedad')
        verbose_name_plural = _('propiedades')
        ordering = ['-is_featured', '-created_date']

    def __str__(self):
        return f"{self.property_name} - {self.location}"


class PropertyGallery(models.Model):
    property = models.ForeignKey(Property, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField(_('imagen'), upload_to='property_images/')
    is_featured = models.BooleanField(_('destacada'), default=False)
    order = models.PositiveIntegerField(_('orden'), default=0)
    
    class Meta:
        verbose_name = _('imagen de propiedad')
        verbose_name_plural = _('imágenes de propiedad')
        ordering = ['order']
    
    def __str__(self):
        return f"Imagen de {self.property.property_name}"
    
    def image_thumbnail(self):
        return format_html('<img src="{}" width="50" height="50" />', self.image.url)
    image_thumbnail.short_description = 'Miniatura'
