from django.db import models
from django.conf import settings
from decimal import Decimal


class Lead(models.Model):
    STATUS_CHOICES = [
        ('New', 'New'),
        ('Qualified', 'Qualified'),
        ('Requirements_Submitted', 'Requirements Submitted'),
        ('Internal_Review', 'Internal Review'),
        ('Client_Meeting', 'Client Meeting Scheduled'),
        ('Costing_In_Progress', 'Costing In Progress'),
        ('Proposal_Ready', 'Proposal Ready'),
        ('Pending_Approval', 'Pending Approval'),
        ('Approved', 'Approved'),
        ('Rejected', 'Rejected'),
        ('On_Hold', 'On Hold'),
    ]

    SERVICE_CHOICES = [
        ('Tech', 'Technology'),
        ('Cyber', 'Cybersecurity'),
        ('Legal', 'Legal'),
        ('Mixed', 'Mixed Services'),
    ]

    SOURCE_CHOICES = [
        ('referral', 'Referral'),
        ('cold_outreach', 'Cold Outreach'),
        ('website', 'Website'),
        ('social_media', 'Social Media'),
        ('event', 'Event / Conference'),
        ('other', 'Other'),
    ]

    PRIORITY_CHOICES = [
        ('Low', 'Low'),
        ('Medium', 'Medium'),
        ('High', 'High'),
        ('Urgent', 'Urgent'),
    ]

    title = models.CharField(max_length=255)
    client_name = models.CharField(max_length=255)
    client_email = models.EmailField(blank=True)
    client_phone = models.CharField(max_length=20, blank=True)
    client_whatsapp = models.CharField(max_length=20, blank=True)
    service_type = models.CharField(max_length=10, choices=SERVICE_CHOICES)
    lead_source = models.CharField(max_length=20, choices=SOURCE_CHOICES, default='other')
    requirements = models.TextField(blank=True, help_text='Rich text HTML')
    proposed_budget = models.DecimalField(
        max_digits=12, decimal_places=2, default=Decimal('0.00'),
        help_text='Client proposed budget in PKR'
    )
    deadline = models.DateField(null=True, blank=True)
    priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default='Medium')
    status = models.CharField(max_length=25, choices=STATUS_CHOICES, default='New')

    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        null=True, related_name='created_leads'
    )
    assigned_pm = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        null=True, blank=True, related_name='assigned_leads'
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        app_label = 'leads'
        ordering = ['-created_at']

    def __str__(self):
        return f'{self.client_name} — {self.title}'


class LeadAttachment(models.Model):
    lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='attachments')
    file = models.FileField(upload_to='lead_attachments/')
    file_name = models.CharField(max_length=255, blank=True)
    file_size = models.PositiveIntegerField(default=0, help_text='Size in bytes')
    uploaded_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
    )
    uploaded_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        app_label = 'leads'
        ordering = ['-uploaded_at']

    def __str__(self):
        return f'{self.file_name} ({self.lead.title})'

    def save(self, *args, **kwargs):
        if self.file and not self.file_name:
            self.file_name = self.file.name
        if self.file:
            self.file_size = self.file.size
        super().save(*args, **kwargs)


class LeadActivity(models.Model):
    """Immutable audit log for lead changes"""
    lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='activities')
    actor = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
    )
    action = models.CharField(max_length=100)
    details = models.TextField(blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        app_label = 'leads'
        ordering = ['-timestamp']
        verbose_name_plural = 'Lead Activities'

    def __str__(self):
        return f'{self.lead.title} — {self.action}'


class Meeting(models.Model):
    TYPE_CHOICES = [
        ('internal', 'Internal Meeting'),
        ('client', 'Client Meeting'),
    ]

    MODE_CHOICES = [
        ('in_person', 'In Person'),
        ('video', 'Video Call'),
        ('phone', 'Phone Call'),
    ]

    OUTCOME_CHOICES = [
        ('proceed', 'Proceed'),
        ('revise', 'Revise Requirements'),
        ('drop', 'Drop'),
        ('pending', 'Pending'),
    ]

    lead = models.ForeignKey(
        Lead, on_delete=models.CASCADE, null=True, blank=True,
        related_name='meetings'
    )
    project = models.ForeignKey(
        'projects.Project', on_delete=models.CASCADE, null=True, blank=True,
        related_name='meetings'
    )
    title = models.CharField(max_length=255)
    meeting_type = models.CharField(max_length=10, choices=TYPE_CHOICES)
    date = models.DateField()
    time = models.TimeField()
    mode = models.CharField(max_length=10, choices=MODE_CHOICES, default='video')
    agenda = models.TextField(blank=True)
    participants = models.ManyToManyField(
        settings.AUTH_USER_MODEL, blank=True, related_name='meetings_attended'
    )
    notes = models.TextField(blank=True)
    outcome = models.CharField(max_length=10, choices=OUTCOME_CHOICES, default='pending')
    is_completed = models.BooleanField(default=False)

    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        null=True, related_name='created_meetings'
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        app_label = 'leads'
        ordering = ['-date', '-time']

    def __str__(self):
        return f'{self.title} ({self.get_meeting_type_display()})'
