from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import os
from io import BytesIO

from PIL import Image
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from common.choices import SRI_LANKA_CITY_CHOICES, SRI_LANKA_DISTRICT_CHOICES, COUNTRY_CHOICES


def service_partner_profile_image_upload_path(instance, filename):
    ext = filename.split('.')[-1].lower()
    if ext not in ['jpg', 'jpeg', 'png', 'webp']:
        ext = 'jpg'
    return f'service_partners/user_{instance.user.id if instance.user else "guest"}/profile.{ext}'


def validate_service_partner_profile_image(image):
    allowed_extensions = ['.jpg', '.jpeg', '.png', '.webp']
    ext = os.path.splitext(image.name)[1].lower()

    if ext not in allowed_extensions:
        raise ValidationError("Only JPG, JPEG, PNG, or WEBP images are allowed.")

def validate_resume_or_bio_data_file(file):
    allowed_extensions = ['.pdf', '.doc', '.docx']
    max_size_mb = 5

    ext = os.path.splitext(file.name)[1].lower()

    if ext not in allowed_extensions:
        raise ValidationError(
            'Only PDF, DOC, or DOCX files are allowed.'
        )

    if file.size > max_size_mb * 1024 * 1024:
        raise ValidationError(
            f'File size must not exceed {max_size_mb}MB.'
        )
    
class ServicePartnerProfile(models.Model):
    SERVICE_TYPE_CHOICES = [
        ('driver', 'Driver'),
        ('housekeeper', 'Housekeeper'),
        ('helper', 'Helper'),
        ('translator', 'Translator'),
        ('assistant', 'Local Assistant'),
        ('chef', 'Personal Chef'),
        ('gardener', 'Gardener'),
        ('caregiver', 'Caregiver'),
        ('security_guard', 'Security Guard'),
    ]

    GENDER_CHOICES = [
        ('male', 'Male'),
        ('female', 'Female'),
        ('other', 'Other'),
    ]

    STATUS_CHOICES = [
        ('pending', 'Pending Review'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
        ('inactive', 'Inactive'),
    ]

    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='service_partner_profile',
        null=True,
        blank=True
    )

    profile_code = models.CharField(max_length=20, unique=True, blank=True)

    service_type = models.CharField(max_length=30, choices=SERVICE_TYPE_CHOICES)
    full_name = models.CharField(max_length=200)
    display_name = models.CharField(max_length=100, blank=True)
    gender = models.CharField(max_length=20, choices=GENDER_CHOICES, blank=True)
    date_of_birth = models.DateField(blank=True, null=True)
    age = models.PositiveIntegerField(blank=True, null=True)

    city = models.CharField(
        max_length=120,
        choices=SRI_LANKA_CITY_CHOICES,
        blank=True
    )
    district = models.CharField(
        max_length=120,
        choices=SRI_LANKA_DISTRICT_CHOICES,
        blank=True
    )
    country = models.CharField(max_length=150, choices=COUNTRY_CHOICES, default='Sri Lanka')
    address = models.TextField(blank=True)

    profile_photo = models.ImageField(
        upload_to=service_partner_profile_image_upload_path,
        blank=True,
        null=True,
        validators=[validate_service_partner_profile_image]
    )
    resume_or_bio_data = models.FileField(
        upload_to='service_partners/resumes/',
        blank=True,
        null=True,
        validators=[validate_resume_or_bio_data_file],
        help_text='Upload resume, CV, or biodata document. PDF, DOC, or DOCX only. Maximum file size: 5MB.'
    )

    short_intro = models.CharField(max_length=255)
    about_me = models.TextField(blank=True)

    languages_spoken = models.CharField(
        max_length=255,
        help_text="Example: English, Sinhala, Tamil, Italian"
    )

    phone_number = models.CharField(max_length=50, blank=True)
    whatsapp_number = models.CharField(max_length=50, blank=True)
    email = models.EmailField()

    experience_summary = models.TextField(blank=True)
    skills = models.TextField(blank=True)
    education = models.CharField(max_length=255, blank=True)

    has_license = models.BooleanField(default=False)
    passport_ready = models.BooleanField(default=False)
    willing_to_relocate = models.BooleanField(default=False)
    live_in_available = models.BooleanField(default=False)
    part_time_available = models.BooleanField(default=False)
    full_time_available = models.BooleanField(default=False)

    is_featured = models.BooleanField(default=False)
    is_public = models.BooleanField(default=False)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')

    agreed_to_terms = models.BooleanField(default=False)

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

    class Meta:
        ordering = ['-created_at']
        verbose_name = 'Service Partner Profile'
        verbose_name_plural = 'Service Partner Profiles'

    def save(self, *args, **kwargs):
        from datetime import date

        if self.date_of_birth:
            today = date.today()
            self.age = today.year - self.date_of_birth.year - (
                (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day)
            )

        is_new = self.pk is None

        super().save(*args, **kwargs)

        if is_new and not self.profile_code:
            self.profile_code = f"SVP{self.pk:05d}"
            super().save(update_fields=['profile_code'])

        if self.profile_photo:
            self.compress_profile_photo()

    def compress_profile_photo(self):
        try:
            img = Image.open(self.profile_photo.path)

            if img.mode in ('RGBA', 'P'):
                img = img.convert('RGB')

            max_width = 600
            max_height = 600
            img.thumbnail((max_width, max_height))

            buffer = BytesIO()
            img.save(buffer, format='JPEG', quality=85, optimize=True)

            file_name = os.path.splitext(os.path.basename(self.profile_photo.name))[0] + '.jpg'
            self.profile_photo.save(
                file_name,
                ContentFile(buffer.getvalue()),
                save=False
            )

            super().save(update_fields=['profile_photo'])

        except Exception:
            pass

    def __str__(self):
        return f"{self.full_name} - {self.get_service_type_display()}"
    

class ServicePartnerInterest(models.Model):
    STATUS_CHOICES = [
        ('interested', 'Interested'),
        ('reviewing', 'Reviewing'),
        ('contacted', 'Contacted'),
        ('arranging', 'Arranging'),
        ('closed', 'Closed'),
    ]

    foreigner = models.ForeignKey(
        'expat_life.ForeignerProfile',
        on_delete=models.CASCADE,
        related_name='service_partner_interests'
    )
    partner = models.ForeignKey(
        'service_partner_app.ServicePartnerProfile',
        on_delete=models.CASCADE,
        related_name='service_partner_interests'
    )
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='interested')
    message = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name = 'Service Partner Interest'
        verbose_name_plural = 'Service Partner Interests'
        constraints = [
            models.UniqueConstraint(
                fields=['foreigner', 'partner'],
                name='unique_foreigner_service_partner_interest'
            )
        ]

    def __str__(self):
        return f"{self.foreigner.user.username} -> {self.partner.display_name or self.partner.full_name}"
    
class ServicePartnerGuidanceResource(models.Model):
    LANGUAGE_CHOICES = [
        ('en', 'English'),
        ('si', 'Sinhala'),
        ('ta', 'Tamil'),
    ]

    language = models.CharField(
        max_length=2,
        choices=LANGUAGE_CHOICES,
        default='en',
        unique=True
    )

    title = models.CharField(
        max_length=200,
        default="Ensolanka Service Partner Guidance Playbook"
    )

    full_playbook_pdf = models.FileField(
        upload_to='service_partner_guidance/playbooks/%Y/%m/',
        blank=True,
        null=True,
        help_text="Upload the full service partner guidance playbook PDF."
    )

    summary_overview_pdf = models.FileField(
        upload_to='service_partner_guidance/summaries/%Y/%m/',
        blank=True,
        null=True,
        help_text="Upload the summary overview or quick guidance PDF."
    )

    audio_guide_file = models.FileField(
        upload_to='service_partner_guidance/audio/%Y/%m/',
        blank=True,
        null=True,
        help_text="Upload the audio guidance file, such as MP3."
    )

    youtube_video_link = models.URLField(
        blank=True,
        null=True,
        help_text="Optional YouTube or video guidance link."
    )

    description = models.TextField(
        blank=True,
        help_text="Brief description about this service partner guidance resource."
    )

    is_active = models.BooleanField(default=True)

    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['language']
        verbose_name = "Service Partner Guidance Resource"
        verbose_name_plural = "Service Partner Guidance Resources"

    def __str__(self):
        return f"{self.get_language_display()} - {self.title}"