from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
from django.core.exceptions import ValidationError
import os


class CustomUserManager(BaseUserManager):
    def create_user(self, phone, password=None, **extra_fields):
        if not phone:
            raise ValueError('The Phone number must be set')
        user = self.model(phone=phone, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, phone, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(phone, password, **extra_fields)


class skyonnAdmin(AbstractBaseUser):
    ADMIN_ID_PREFIX = 'SKYA'  # Prefix for AdminId

    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    phone = models.CharField(max_length=15, unique=True)
    phone_number_2 = models.CharField(max_length=15, blank=True, null=True)
    company_email = models.EmailField(null=True)  # Additional email field
    personal_email = models.EmailField(null=True)  # Additional email field
    address = models.TextField(null=True)  # Additional address field
    work_location = models.CharField(max_length=100, null=True)  # Additional work location field
    picture = models.ImageField(upload_to='profile_pics/', null=True)  # Additional picture field
    role = models.CharField(max_length=20)  # Additional role field
    admin_id = models.CharField(max_length=10, unique=True)  # AdminId field

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = CustomUserManager()

    USERNAME_FIELD = 'phone'

    def save(self, *args, **kwargs):
        if not self.admin_id:
            last_admin = skyonnAdmin.objects.order_by('-id').first()
            if last_admin:
                last_id = last_admin.admin_id[4:]  # Extract the serial number part
                new_id = int(last_id) + 1
            else:
                new_id = 1
            self.admin_id = f'{self.ADMIN_ID_PREFIX}{new_id:03d}'
        super().save(*args, **kwargs)

    def _str_(self):
        return self.phone


class SubcompanyDetails(models.Model):
    sub_client_id = models.CharField(max_length=20, null=True)
    parent_company = models.CharField(max_length=100,null=True)
    sub_company = models.CharField(max_length=100,unique=True,null=True)
    GST_No = models.CharField(max_length=50, null=True)
    location_id = models.CharField(max_length=100,null=True)
    address_1 = models.CharField(max_length=200,null=True)
    address_2 = models.CharField(max_length=200,null=True)
    # Street = models.CharField(max_length=200,null=True)
    City = models.CharField(max_length=200, null=True)
    State = models.CharField(max_length=200,null=True)
    Pincode =models.IntegerField(null=True)
    country = models.CharField(max_length=200,null=True)


    def _str_(self):
        return f"{self.parent_company}"


class Contact(models.Model):

    # sub_client_id = models.ForeignKey(SubcompanyDetails,on_delete=models.CASCADE)
    name = models.CharField(max_length=40,null=True)
    designation = models.CharField(max_length=50,null=True)
    department = models.CharField(max_length=50,null=True)
    phone_no = models.CharField(max_length=50, null=True)
    email = models.EmailField(null=True)
    location = models.CharField(max_length=102,null=True)

    def _str_(self):
        return f"{self.name} - {self.department}"

class ClientDetails(models.Model):
    # STATE_CHOICES =(('Andhra Pradesh','andhra Pradesh'),('Arunachal Pradesh','arunachal Pradesh'),('assam','Assam'),
    #                 ('Bihar','bihar'),('Chhattisgarh','chhattisgarh'),('Goa','goa'),('Gujarat','Gujarat'),('Haryana','haryana'),
    #                 ('Himachal Pradesh','himachal Pradesh'),('Jharkhand','jharkhand'),('Karnataka','karnataka'),
    #                 ('Kerala','kerala'),)

    client_id = models.CharField(max_length=20, null=True)
    parent_company = models.CharField(max_length=100,null=True, unique=True)
    GST_No = models.CharField(max_length=50, null=True)
    location_Id = models.CharField(max_length=100,null=True)
    address_1 = models.CharField(max_length=300,blank=True,null=True)
    address_2 = models.CharField(max_length=200,null=True,blank=True)
    # Street=models.CharField(max_length=200,null=True)
    City = models.CharField(max_length=200, null=True)
    state = models.CharField(max_length=300, blank=True, null=True)
    Pincode = models.IntegerField(null=True)
    country = models.CharField(max_length=200,null=True)

    contacts = models.ManyToManyField(Contact, related_name='contacts')

    def _str_(self):
        return f"{self.parent_company} - {self.location_Id}"

class SublocationDetails(models.Model):
    parent_company = models.CharField(max_length=100, null=True)
    department = models.CharField(max_length=100, null=True)
    GST_No = models.CharField(max_length=50, null=True)
    Location = models.CharField(max_length=100, null=True)
    address_1 = models.CharField(max_length=300, blank=True, null=True)
    address_2 = models.CharField(max_length=200, null=True, blank=True)
    City = models.CharField(max_length=200, null=True)
    State = models.CharField(max_length=300, blank=True, null=True)
    Pincode = models.IntegerField(null=True)
    country = models.CharField(max_length=200, null=True)


class Locations(models.Model):
    location = models.CharField(null=True, max_length=50)


class AddContact(models.Model):
    Contact_id = models.CharField(max_length=30, null=True)
    Company = models.CharField(max_length=100, null=True, blank=True)
    Sub_company = models.CharField(max_length=100, null=True, blank=True)
    FirstName = models.CharField(max_length=100, null=True)
    LastName = models.CharField(max_length=50, null=True, blank=True)
    Department = models.CharField(max_length=50, null=True, blank=True)
    Designation = models.CharField(max_length=50, null=True, blank=True)
    Phone_number = models.CharField(max_length=10, unique=True, null=True)
    Email = models.EmailField(unique=True, null=True)

class Client(models.Model):
    parent_company = models.CharField(max_length=255)

    def __str__(self):
        return self.parent_company

def validate_file_extension(value):
    ext = os.path.splitext(value.name)[1]  # Get file extension
    valid_extensions = ['.pdf', '.jpg', '.jpeg']
    if not ext.lower() in valid_extensions:
        raise ValidationError('Unsupported file extension. Allowed extensions are: .pdf, .jpg, .jpeg')

class SPOC(models.Model):
    name = models.CharField(max_length=255,null=True)

class InternalTeam(models.Model):
    FirstName = models.CharField(max_length=100, null=True)
    LastName = models.CharField(max_length=100, null=True)
    Designation = models.CharField(max_length=100, null=True)
    Department = models.CharField(max_length=100, null=True)
    Address_1 = models.CharField(max_length=255, null=True)
    Address_2 = models.CharField(max_length=255, blank=True, null=True)
    City = models.CharField(max_length=100)
    State = models.CharField(max_length=100, null=True)
    Pincode = models.CharField(max_length=6, null=True)
    Country = models.CharField(max_length=100, null=True)
    PhoneNo1 = models.CharField(max_length=15, null=True)
    LandNumber = models.CharField(max_length=25, blank=True, null=True)
    Email1 = models.EmailField(null=True,unique=True)
    Email2 = models.EmailField(max_length=50,null=True)
    Level = models.CharField(max_length=50, null=True)

    FullName = models.CharField(max_length=100, null=True)

    Login = models.EmailField(null=True)
    Password = models.CharField(max_length=50, null=True)
    user_id = models.CharField(max_length=50, null=True)

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

