from django.db import models
from django.core.validators import RegexValidator


class Office(models.Model):
    """
    Office locations for dynamic address handling in quotes and invoices
    """
    LOCATION_CHOICES = [
        ('calicut', 'Calicut'),
        ('kasargod', 'Kasargod'),
        ('dubai', 'Dubai'),
        ('qatar', 'Qatar'),
    ]

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, unique=True)
    location_code = models.CharField(
        max_length=20,
        choices=LOCATION_CHOICES,
        unique=True,
        help_text="Unique code for the office location"
    )
    address = models.TextField(help_text="Complete office address")
    phone = models.CharField(
        max_length=20,
        validators=[RegexValidator(
            regex=r'^[\+]?[1-9][\d]{0,15}$',
            message="Enter a valid phone number"
        )]
    )
    email = models.EmailField()
    website = models.URLField(blank=True, null=True)
    gstin = models.CharField(max_length=15, blank=True,
                             null=True, help_text="GSTIN number for the office")

    is_active = models.BooleanField(default=True)
    is_default = models.BooleanField(
        default=False,
        help_text="Default office for new quotes/invoices"
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['name']
        verbose_name = "Office"
        verbose_name_plural = "Offices"

    def __str__(self):
        return f"{self.name} ({self.get_location_code_display()})"

    def save(self, *args, **kwargs):
        # Ensure only one default office exists
        if self.is_default:
            Office.objects.filter(is_default=True).update(is_default=False)
        super().save(*args, **kwargs)

    @classmethod
    def get_default_office(cls):
        """Get the default office or the first active office"""
        try:
            return cls.objects.filter(is_active=True, is_default=True).first()
        except cls.DoesNotExist:
            return cls.objects.filter(is_active=True).first()

    @classmethod
    def get_office_by_location(cls, location_code):
        """Get office by location code"""
        try:
            return cls.objects.get(location_code=location_code, is_active=True)
        except cls.DoesNotExist:
            return cls.get_default_office()

    def get_company_info(self):
        print(self.location_code, "locations")
        print(self.address, "address")
        """Get company info in the format expected by InvoiceGenerator"""
        # Enforce strict, PDF-friendly address formatting by location
        formatted_address = self.address
        if self.location_code == 'kasargod':
            formatted_address = (
                'Fathima Arcade, Second Floor\n'
                'New Bus Stand, Kasaragod\n'
                'Building No: 18/339/A7\n'
                'Pin Code: 671121, Kerala, India\n'
                '9995 555 861 / marketizrksd@gmail.com\n'
                'GSTIN: 32ACEFM3907A1ZV\n'
                'www.marketizr.in'
            )
        elif self.location_code == 'calicut':
            formatted_address = (
                'Marketizr Business Expertise, \n'
                '1st Floor KINFRA Advanced Technology Park,\n'
                'Poovannor Palli,Ramanattukara\n'
                'Kozhikode,Kerala 673631\n'
                '9995 555 861 / marketizrksd@gmail.com\n'
                'GSTIN: 32ACEFM3907A1ZV\n'
                'www.marketizr.in'
            )
        print(formatted_address, "formatted_address")

        return {
            'name': 'marketizr',
            'tagline': 'Business Expertise',
            'address': formatted_address,
            'phone': self.phone,
            'email': self.email,
            'website': self.website or 'www.marketizr.in',
            'gstin': self.gstin or '',
        }
