from django.db import models
from subscriptions.models import Profile
from crm.models import Lead
from enum import Enum
from lib.choices import choices_the_options 
import uuid

class StatusChoices(Enum):
    OPEN = 'open'
    IN_PROGRESS = 'in_progress'
    REVIEW = 'review'
    COMPLETED = 'completed'

class PriorityChoices(Enum):    
    LOW = 'low'
    NORMAL = 'normal'
    HIGH = 'high'
    URGENT = 'urgent'

class EventTypeChoices(Enum):
    CREATED = 'created'
    UPDATED = 'updated'
    COMPLETED = 'completed'
    REASSIGNED = 'reassigned'

class DivisionChoices(Enum):
    DESIGN = 'design'
    VIDEO = 'video'
    WEBSITE = 'website'

class DesignStatusChoices(Enum):
    OPEN = 'open'
    UNDER_DESIGN = 'under_design'
    COMPLETED = 'completed'

class ClientStatusChoices(Enum):
    APPROVED = 'approved'
    OPEN = 'open'
    UNDER_REVIEW = 'under_review'
    REJECTED = 'rejected'


class Task(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    status = models.CharField(max_length=20, choices=choices_the_options(StatusChoices), default=StatusChoices.OPEN.value)
    priority = models.CharField(max_length=20, choices=choices_the_options(PriorityChoices), default=PriorityChoices.LOW.value)
    due_date = models.DateTimeField(blank=True, null=True)
    assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, related_name='assigned_tasks')
    reporter = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, related_name='reported_tasks')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.title
    
    class Meta:
        ordering = ['-created_at']
        # Removed explicit indexes to avoid OperationalError due to missing index
        # If you need to add indexes, make sure the fields exist and migrations are applied properly.


class TaskManager(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    client_name = models.ForeignKey(Lead, on_delete=models.SET_NULL, null=True, related_name='client_name_tasks')
    date = models.DateField(auto_now_add=True, null=True, blank=True)
    job_order_no = models.CharField(max_length=255, null=True, blank=True)
    activities = models.CharField(max_length=255, null=True, blank=True)
    work_details = models.TextField(null=True, blank=True)
    division = models.CharField(max_length=255, choices=choices_the_options(DivisionChoices), null=True, blank=True)
    allotted_by = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, related_name='allotted_by_tasks')
    allotted_date = models.DateField(null=True, blank=True)
    target_date = models.DateField(null=True, blank=True)
    designed_by = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, related_name='designed_by_tasks')
    designed_status = models.CharField(max_length=255, choices=choices_the_options(DesignStatusChoices), null=True, blank=True)
    completed_date = models.DateField(null=True, blank=True)
    client_status = models.CharField(max_length=255, choices=choices_the_options(ClientStatusChoices), null=True, blank=True)
    remarks = models.TextField(null=True, blank=True)
    billing = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.client_name.company if self.client_name else ""

    class Meta:
        ordering = ['-created_at']

    # Auto generate job order no Format MKTZR-000000
    def generate_job_order_no(self):
        last_task = TaskManager.objects.order_by('-created_at').first()
        if last_task and last_task.job_order_no and last_task.job_order_no.startswith('MKTZR-'):
            try:
                last_number = int(last_task.job_order_no.replace('MKTZR-', ''))
            except ValueError:
                last_number = 0
            new_number = last_number + 1
        else:
            new_number = 1
        return f"MKTZR-{new_number:06d}"

    def client_name_invoice_approval_lead(self):
        """
        Returns True if there is at least one Invoice for this client_name (Lead) with approved=True.
        """
        if not self.client_name:
            return False
        # Import here to avoid circular import
        from crm.models import Quote
        return Quote.objects.filter(lead=self.client_name, is_invoice_converted=True).exists()

    def save(self, *args, **kwargs):
        if not self.job_order_no:
            self.job_order_no = self.generate_job_order_no()
        super().save(*args, **kwargs)