from django.db import models


class Lead(models.Model):
    SOURCE_CHOICES = [
        ('inquiry_form', 'Inquiry Form'),
        ('property_inquiry', 'Property Inquiry'),
        ('contact_form', 'Contact Form'),
        ('exit_popup', 'Exit Popup'),
        ('newsletter', 'Newsletter'),
        ('chatbot', 'Chatbot'),
        ('whatsapp', 'WhatsApp'),
        ('phone', 'Phone Call'),
        ('landing_page', 'Landing Page'),
        ('other', 'Other'),
    ]

    STATUS_CHOICES = [
        ('new', 'New'),
        ('contacted', 'Contacted'),
        ('qualified', 'Qualified'),
        ('viewing_scheduled', 'Viewing Scheduled'),
        ('negotiating', 'Negotiating'),
        ('won', 'Won — Closed'),
        ('lost', 'Lost'),
        ('spam', 'Spam'),
    ]

    name = models.CharField(max_length=120)
    email = models.EmailField(blank=True)
    phone = models.CharField(max_length=30, blank=True)
    message = models.TextField(blank=True)

    # Optional context
    property = models.ForeignKey('properties.Property', on_delete=models.SET_NULL, blank=True, null=True, related_name='leads')
    landing_page = models.ForeignKey('landing_pages.LandingPage', on_delete=models.SET_NULL, blank=True, null=True, related_name='leads')

    # Property interest (when not tied to a specific property)
    interested_in = models.CharField(max_length=200, blank=True, help_text='e.g. "3-bed in Lekki"')
    budget_min = models.DecimalField(max_digits=14, decimal_places=2, blank=True, null=True)
    budget_max = models.DecimalField(max_digits=14, decimal_places=2, blank=True, null=True)

    source = models.CharField(max_length=30, choices=SOURCE_CHOICES, default='inquiry_form')
    status = models.CharField(max_length=30, choices=STATUS_CHOICES, default='new')

    # Tracking
    ip_address = models.GenericIPAddressField(blank=True, null=True)
    user_agent = models.CharField(max_length=255, blank=True)
    referrer = models.URLField(blank=True, max_length=500)

    # Internal
    assigned_to = models.ForeignKey('auth.User', on_delete=models.SET_NULL, blank=True, null=True, related_name='leads')
    notes = models.TextField(blank=True)

    created_at = models.DateTimeField(auto_now_add=True)
    contacted_at = models.DateTimeField(blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        target = self.property.title if self.property else self.interested_in or 'general'
        return f"{self.name} — {target}"
