import uuid
from django.db import models
from enum import Enum
from .collection import CollectionData
from lib.choices import choices_the_options
from subscriptions.models import Profile, SalesPersons

class LeadSource(Enum):
    CAMPAIGN = 'campaign'
    WEBSITE = 'website'
    SOCIAL_MEDIA = 'social_media'
    REFERRAL = 'referral'
    COLD_CALL = 'cold_call'
    COLLECTION = 'collection'

class LeadStatus(Enum):
    NEW = 'new'
    CONTACTED = 'contacted'
    QUALIFIED = 'qualified'
    LOST = 'lost'
    CONVERTED = 'converted'     

class Lead(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.CharField(max_length=255)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(blank=True, null=True)
    phone = models.CharField(max_length=20, blank=True, null=True)
    mobile = models.CharField(max_length=20, blank=True, default='')
    lead_source = models.CharField(
        max_length=50,
        choices=choices_the_options(LeadSource),
        default=LeadSource.COLLECTION.value
    )
    lead_status = models.CharField(
        max_length=50,
        choices=choices_the_options(LeadStatus),
        default=LeadStatus.NEW.value
    )
    collections = models.ForeignKey(
        CollectionData, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True, 
        related_name='leads'
    )
    address = models.TextField(null=True, blank=True)
    city = models.CharField(max_length=255, null=True, blank=True)
    state = models.CharField(max_length=255, null=True, blank=True)
    zip_code = models.CharField(max_length=255, null=True, blank=True)
    country = models.CharField(max_length=255)
    is_converted = models.BooleanField(default=False)
    converted_date = models.DateTimeField(null=True, blank=True)
    assigned_to = models.ForeignKey(
        SalesPersons, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True, 
        related_name='assigned_leads'
    )
    created_by = models.ForeignKey(
        Profile, 
        on_delete=models.PROTECT, 
        related_name='created_leads'
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.first_name} {self.last_name} - {self.company or 'No Company'}"
    
    def convert_to_customer(self):
        """Marks this lead as converted and creates a Customer profile"""
        from django.utils import timezone
        if not self.is_converted:
            self.is_converted = True
            self.lead_status = LeadStatus.CONVERTED.value
            self.converted_date = timezone.now()
            self.save()
            # Add customer creation logic here
            return True
        return False
    
    class Meta:
        ordering = ['-created_at']