from django.db import models
from django.utils.text import slugify
from django.core.validators import FileExtensionValidator


class Station(models.Model):
    """Modèle pour les stations services"""
    nom = models.CharField(max_length=200, verbose_name="Nom de la station")
    adresse = models.TextField(verbose_name="Adresse complète")
    ville = models.CharField(max_length=100)
    region = models.CharField(max_length=100)
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    telephone = models.CharField(max_length=20, blank=True)
    email = models.EmailField(blank=True)
    image = models.ImageField(upload_to='stations/', blank=True, null=True)
    services = models.ManyToManyField('Service', related_name='stations', blank=True)
    horaires = models.TextField(blank=True, verbose_name="Horaires d'ouverture")
    est_active = models.BooleanField(default=True)
    date_ouverture = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Station Service"
        verbose_name_plural = "Stations Services"
        ordering = ['ville', 'nom']

    def __str__(self):
        return f"{self.nom} - {self.ville}"


class Service(models.Model):
    """Modèle pour les services proposés"""
    CATEGORIE_CHOICES = [
        ('carburant', 'Carburant'),
        ('lubrifiant', 'Lubrifiant'),
        ('entretien', 'Entretien Auto'),
        ('lavage', 'Lavage'),
        ('boutique', 'Boutique'),
        ('gaz', 'Gaz Butane'),
        ('autre', 'Autre'),
    ]

    nom = models.CharField(max_length=200)
    slug = models.SlugField(unique=True, blank=True)
    categorie = models.CharField(max_length=20, choices=CATEGORIE_CHOICES)
    description = models.TextField()
    description_courte = models.CharField(max_length=255, blank=True)
    icone = models.CharField(max_length=50, blank=True, help_text="Nom de l'icône")
    image = models.ImageField(upload_to='services/', blank=True, null=True)
    ordre = models.IntegerField(default=0, help_text="Ordre d'affichage")
    est_actif = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Service"
        verbose_name_plural = "Services"
        ordering = ['ordre', 'nom']

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.nom)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.nom


class Actualite(models.Model):
    """Modèle pour les actualités"""
    TYPE_CHOICES = [
        ('prix', 'Prix à la pompe'),
        ('recrutement', 'Recrutement'),
        ('appel_offre', 'Appel d\'offres'),
        ('communique', 'Communiqué'),
        ('engagement', 'Engagement social'),
        ('projet', 'Projet'),
        ('autre', 'Autre'),
    ]

    titre = models.CharField(max_length=300)
    slug = models.SlugField(unique=True, blank=True)
    type_actualite = models.CharField(max_length=20, choices=TYPE_CHOICES)
    resume = models.TextField(max_length=500, help_text="Résumé court")
    contenu = models.TextField()
    image_principale = models.ImageField(upload_to='actualites/', blank=True, null=True)
    image_alt = models.CharField(max_length=200, blank=True)
    fichier_joint = models.FileField(
        upload_to='actualites/fichiers/',
        blank=True,
        null=True,
        validators=[FileExtensionValidator(['pdf', 'doc', 'docx'])]
    )
    est_epingle = models.BooleanField(default=False, verbose_name="Épingler")
    est_publie = models.BooleanField(default=True)
    date_publication = models.DateTimeField()
    auteur = models.CharField(max_length=100, default="Bilal Oil")
    vues = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Actualité"
        verbose_name_plural = "Actualités"
        ordering = ['-est_epingle', '-date_publication']

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.titre)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.titre


class PrixCarburant(models.Model):
    """Modèle pour les prix des carburants"""
    TYPE_CARBURANT_CHOICES = [
        ('essence', 'Essence'),
        ('gasoil', 'Gasoil'),
        ('super', 'Super'),
        ('gpl', 'GPL'),
    ]

    type_carburant = models.CharField(max_length=20, choices=TYPE_CARBURANT_CHOICES)
    prix = models.DecimalField(max_digits=8, decimal_places=2, verbose_name="Prix (FCFA)")
    date_application = models.DateField()
    date_fin = models.DateField(null=True, blank=True)
    est_actuel = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Prix Carburant"
        verbose_name_plural = "Prix Carburants"
        ordering = ['-date_application', 'type_carburant']
        unique_together = ['type_carburant', 'date_application']

    def __str__(self):
        return f"{self.get_type_carburant_display()} - {self.prix} FCFA"


class Contact(models.Model):
    """Modèle pour les demandes de contact"""
    nom_complet = models.CharField(max_length=200)
    email = models.EmailField()
    telephone = models.CharField(max_length=20, blank=True)
    entreprise = models.CharField(max_length=200, blank=True)
    sujet = models.CharField(max_length=300)
    message = models.TextField()
    est_traite = models.BooleanField(default=False)
    reponse = models.TextField(blank=True)
    date_traitement = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Demande de Contact"
        verbose_name_plural = "Demandes de Contact"
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.nom_complet} - {self.sujet}"


class Statistique(models.Model):
    """Modèle pour les statistiques de l'entreprise"""
    libelle = models.CharField(max_length=200, help_text="Ex: Stations Services")
    valeur = models.CharField(max_length=50, help_text="Ex: 50+")
    icone = models.CharField(max_length=50, blank=True)
    unite = models.CharField(max_length=20, blank=True, help_text="Ex: +, %, K")
    ordre = models.IntegerField(default=0)
    est_actif = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Statistique"
        verbose_name_plural = "Statistiques"
        ordering = ['ordre']

    def __str__(self):
        return f"{self.libelle}: {self.valeur}{self.unite}"