from django.utils import timezone
from django.db import models
from django_ckeditor_5.fields import CKEditor5Field

from .validators import validate_image_size


class Category(models.Model):
    name = models.CharField(max_length=255, unique=True)
    image = models.ImageField(null=True, blank=True, upload_to="category/images/")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"


class Guideline(models.Model):
    COUNTRY_CHOICES = [
        ("afghanistan", "Afghanistan"),
        ("albania", "Albania"),
        ("algeria", "Algeria"),
        ("andorra", "Andorra"),
        ("angola", "Angola"),
        ("antigua_barbuda", "Antigua and Barbuda"),
        ("argentina", "Argentina"),
        ("armenia", "Armenia"),
        ("australia", "Australia"),
        ("austria", "Austria"),
        ("azerbaijan", "Azerbaijan"),
        ("bahamas", "Bahamas"),
        ("bahrain", "Bahrain"),
        ("bangladesh", "Bangladesh"),
        ("barbados", "Barbados"),
        ("belarus", "Belarus"),
        ("belgium", "Belgium"),
        ("belize", "Belize"),
        ("benin", "Benin"),
        ("bhutan", "Bhutan"),
        ("bolivia", "Bolivia"),
        ("bosnia_herzegovina", "Bosnia and Herzegovina"),
        ("botswana", "Botswana"),
        ("brazil", "Brazil"),
        ("brunei", "Brunei"),
        ("bulgaria", "Bulgaria"),
        ("burkina_faso", "Burkina Faso"),
        ("burundi", "Burundi"),
        ("cabo_verde", "Cabo Verde"),
        ("cambodia", "Cambodia"),
        ("cameroon", "Cameroon"),
        ("canada", "Canada"),
        ("central_african_republic", "Central African Republic"),
        ("chad", "Chad"),
        ("chile", "Chile"),
        ("china", "China"),
        ("colombia", "Colombia"),
        ("comoros", "Comoros"),
        ("congo", "Congo"),
        ("costa_rica", "Costa Rica"),
        ("croatia", "Croatia"),
        ("cuba", "Cuba"),
        ("cyprus", "Cyprus"),
        ("czechia", "Czechia"),
        ("denmark", "Denmark"),
        ("djibouti", "Djibouti"),
        ("dominica", "Dominica"),
        ("dominican_republic", "Dominican Republic"),
        ("ecuador", "Ecuador"),
        ("egypt", "Egypt"),
        ("el_salvador", "El Salvador"),
        ("equatorial_guinea", "Equatorial Guinea"),
        ("eritrea", "Eritrea"),
        ("estonia", "Estonia"),
        ("eswatini", "Eswatini"),
        ("ethiopia", "Ethiopia"),
        ("fiji", "Fiji"),
        ("finland", "Finland"),
        ("france", "France"),
        ("gabon", "Gabon"),
        ("gambia", "Gambia"),
        ("georgia", "Georgia"),
        ("germany", "Germany"),
        ("ghana", "Ghana"),
        ("greece", "Greece"),
        ("grenada", "Grenada"),
        ("guatemala", "Guatemala"),
        ("guinea", "Guinea"),
        ("guinea_bissau", "Guinea-Bissau"),
        ("guyana", "Guyana"),
        ("haiti", "Haiti"),
        ("honduras", "Honduras"),
        ("hungary", "Hungary"),
        ("iceland", "Iceland"),
        ("india", "India"),
        ("indonesia", "Indonesia"),
        ("iran", "Iran"),
        ("iraq", "Iraq"),
        ("ireland", "Ireland"),
        ("israel", "Israel"),
        ("italy", "Italy"),
        ("jamaica", "Jamaica"),
        ("japan", "Japan"),
        ("jordan", "Jordan"),
        ("kazakhstan", "Kazakhstan"),
        ("kenya", "Kenya"),
        ("kiribati", "Kiribati"),
        ("korea_north", "North Korea"),
        ("korea_south", "South Korea"),
        ("kuwait", "Kuwait"),
        ("kyrgyzstan", "Kyrgyzstan"),
        ("laos", "Laos"),
        ("latvia", "Latvia"),
        ("lebanon", "Lebanon"),
        ("lesotho", "Lesotho"),
        ("liberia", "Liberia"),
        ("libya", "Libya"),
        ("liechtenstein", "Liechtenstein"),
        ("lithuania", "Lithuania"),
        ("luxembourg", "Luxembourg"),
        ("madagascar", "Madagascar"),
        ("malawi", "Malawi"),
        ("malaysia", "Malaysia"),
        ("maldives", "Maldives"),
        ("mali", "Mali"),
        ("malta", "Malta"),
        ("marshall_islands", "Marshall Islands"),
        ("mauritania", "Mauritania"),
        ("mauritius", "Mauritius"),
        ("mexico", "Mexico"),
        ("micronesia", "Micronesia"),
        ("moldova", "Moldova"),
        ("monaco", "Monaco"),
        ("mongolia", "Mongolia"),
        ("montenegro", "Montenegro"),
        ("morocco", "Morocco"),
        ("mozambique", "Mozambique"),
        ("myanmar", "Myanmar"),
        ("namibia", "Namibia"),
        ("nauru", "Nauru"),
        ("nepal", "Nepal"),
        ("netherlands", "Netherlands"),
        ("new_zealand", "New Zealand"),
        ("nicaragua", "Nicaragua"),
        ("niger", "Niger"),
        ("nigeria", "Nigeria"),
        ("north_macedonia", "North Macedonia"),
        ("norway", "Norway"),
        ("oman", "Oman"),
        ("pakistan", "Pakistan"),
        ("palau", "Palau"),
        ("palestine", "Palestine State"),
        ("panama", "Panama"),
        ("papua_new_guinea", "Papua New Guinea"),
        ("paraguay", "Paraguay"),
        ("peru", "Peru"),
        ("philippines", "Philippines"),
        ("poland", "Poland"),
        ("portugal", "Portugal"),
        ("qatar", "Qatar"),
        ("romania", "Romania"),
        ("russia", "Russia"),
        ("rwanda", "Rwanda"),
        ("saint_kitts_nevis", "Saint Kitts and Nevis"),
        ("saint_lucia", "Saint Lucia"),
        ("saint_vincent_grenadines", "Saint Vincent and the Grenadines"),
        ("samoa", "Samoa"),
        ("san_marino", "San Marino"),
        ("sao_tome_principe", "Sao Tome and Principe"),
        ("saudi_arabia", "Saudi Arabia"),
        ("senegal", "Senegal"),
        ("serbia", "Serbia"),
        ("seychelles", "Seychelles"),
        ("sierra_leone", "Sierra Leone"),
        ("singapore", "Singapore"),
        ("slovakia", "Slovakia"),
        ("slovenia", "Slovenia"),
        ("solomon_islands", "Solomon Islands"),
        ("somalia", "Somalia"),
        ("south_africa", "South Africa"),
        ("south_sudan", "South Sudan"),
        ("spain", "Spain"),
        ("sri_lanka", "Sri Lanka"),
        ("sudan", "Sudan"),
        ("suriname", "Suriname"),
        ("sweden", "Sweden"),
        ("switzerland", "Switzerland"),
        ("syria", "Syria"),
        ("taiwan", "Taiwan"),
        ("tajikistan", "Tajikistan"),
        ("tanzania", "Tanzania"),
        ("thailand", "Thailand"),
        ("timor_leste", "Timor-Leste"),
        ("togo", "Togo"),
        ("tonga", "Tonga"),
        ("trinidad_tobago", "Trinidad and Tobago"),
        ("tunisia", "Tunisia"),
        ("turkey", "Turkey"),
        ("turkmenistan", "Turkmenistan"),
        ("tuvalu", "Tuvalu"),
        ("uganda", "Uganda"),
        ("ukraine", "Ukraine"),
        ("uae", "United Arab Emirates"),
        ("uk", "United Kingdom"),
        ("usa", "United States"),
        ("uruguay", "Uruguay"),
        ("uzbekistan", "Uzbekistan"),
        ("vanuatu", "Vanuatu"),
        ("venezuela", "Venezuela"),
        ("vietnam", "Vietnam"),
        ("yemen", "Yemen"),
        ("zambia", "Zambia"),
        ("zimbabwe", "Zimbabwe"),
        ("custom", "Custom Country"),
    ]

    STUDY_LEVEL_CHOICES = [
        ("undergraduate", "Undergraduate"),
        ("postgraduate", "Postgraduate"),
        ("phd", "PhD/Doctorate"),
        ("diploma", "Diploma/Certificate"),
        ("foundation", "Foundation Program"),
        ("language", "Language Course"),
        ("all", "All Levels"),
    ]

    STATUS_CHOICES = [
        ("draft", "Draft"),
        ("published", "Published"),
        ("archived", "Archived"),
    ]

    # Basic Information
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    country = models.CharField(max_length=50, choices=COUNTRY_CHOICES)
    study_level = models.CharField(max_length=50, choices=STUDY_LEVEL_CHOICES)

    # Content
    short_description = models.TextField(
        max_length=500, help_text="Brief overview (max 500 characters)"
    )
    overview = CKEditor5Field(
        help_text="Comprehensive overview of studying in this country"
    )

    # Requirements
    eligibility_criteria = CKEditor5Field(
        help_text="Academic and other eligibility requirements"
    )
    language_requirements = CKEditor5Field(
        help_text="English language proficiency requirements"
    )
    financial_requirements = CKEditor5Field(
        help_text="Financial proof and requirements"
    )

    # Application Process
    application_process = CKEditor5Field(help_text="Step-by-step application guide")
    deadline_information = CKEditor5Field(
        help_text="Application deadlines and timelines"
    )
    visa_process = CKEditor5Field(help_text="Student visa application process")

    # Costs & Funding
    tuition_fees = CKEditor5Field(help_text="Typical tuition fees and costs")
    living_costs = CKEditor5Field(help_text="Cost of living information")
    scholarship_info = CKEditor5Field(help_text="Available scholarships and funding")

    # Additional Information
    working_while_studying = CKEditor5Field(
        blank=True, null=True, help_text="Work rights and opportunities"
    )
    post_study_options = CKEditor5Field(
        blank=True, null=True, help_text="Post-study work and settlement options"
    )
    useful_resources = CKEditor5Field(
        blank=True, null=True, help_text="Helpful links and resources"
    )

    # Media
    featured_image = models.ImageField(
        upload_to="guidelines/featured-images/",
        blank=True,
        null=True,
        help_text="Main image for this guideline",
    )
    country_flag = models.ImageField(
        upload_to="guidelines/country-flags/",
        blank=True,
        null=True,
        help_text="Flag of the country",
    )

    # Metadata
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="draft")
    is_featured = models.BooleanField(default=False)
    order = models.PositiveIntegerField(default=0)
    views_count = models.PositiveIntegerField(default=0)

    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    published_date = models.DateTimeField(blank=True, null=True)

    # SEO
    meta_title = models.CharField(max_length=255, blank=True, null=True)
    meta_description = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["order", "-published_date", "title"]
        verbose_name = "Destination"
        verbose_name_plural = "Destinations"
        indexes = [
            models.Index(fields=["status", "published_date"]),
            models.Index(fields=["country", "study_level"]),
            models.Index(fields=["is_featured", "status"]),
        ]

    def __str__(self):
        return f"{self.title} - {self.get_country_display()}"

    def save(self, *args, **kwargs):
        if self.status == "published" and not self.published_date:
            self.published_date = timezone.now()
        super().save(*args, **kwargs)


class OwnerInfo(models.Model):
    phone = models.CharField(max_length=20)
    support_email = models.EmailField(max_length=254)
    owner_name = models.CharField(max_length=255)
    brand_name = models.CharField(max_length=255)
    bin = models.CharField(max_length=255)
    hotline = models.CharField(max_length=255)
    business_address = models.TextField()
    secondary_business_address = models.TextField()
    logo = models.ImageField(
        upload_to="base/owner-info/logo",
        validators=[validate_image_size],
        null=True,
        blank=True,
    )
    secondary_logo = models.ImageField(
        upload_to="base/owner-info/secondary_logo",
        validators=[validate_image_size],
        null=True,
        blank=True,
    )
    facebook = models.URLField(null=True, blank=True)
    instagram = models.URLField(null=True, blank=True)
    linkedin = models.URLField(null=True, blank=True)
    twitter = models.URLField(null=True, blank=True)
    secondary_link = models.URLField(null=True, blank=True)

    def __str__(self):
        return self.brand_name

    class Meta:
        verbose_name = "Owner Information"
        verbose_name_plural = "Owner Information"


class FAQ(models.Model):
    question = models.CharField(max_length=255)
    answer = CKEditor5Field()

    def __str__(self):
        return self.question

    class Meta:
        verbose_name = "FAQ"
        verbose_name_plural = "FAQs"


class Message(models.Model):
    email = models.EmailField()
    subject = models.CharField(max_length=255)
    message = models.TextField()
    phone = models.CharField(max_length=11, null=True, blank=True)

    def __str__(self):
        return f"{self.email}"

    class Meta:
        verbose_name = "Message"
        verbose_name_plural = "Messages"


class Page(models.Model):
    name = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=255, unique=True)
    title = models.CharField(max_length=255, blank=True, null=True)
    description = CKEditor5Field(blank=True, null=True)
    meta_description = models.TextField(blank=True, null=True)
    is_active = models.BooleanField(default=True)
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ["order", "name"]

    def __str__(self):
        return self.name


class PageSectionType(models.Model):
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.name

 
class PageSection(models.Model):
    CONTENT_ALIGNMENT = [
        ("left", "Left"),
        ("center", "Center"),
        ("right", "Right"),
    ]

    page = models.ForeignKey(
        Page,
        related_name="sections",
        on_delete=models.CASCADE,
        null=True,
        blank=True,
    )
    section_type = models.ForeignKey(
        PageSectionType,
        related_name="page_sections",
        on_delete=models.PROTECT,
    )
    name = models.CharField(max_length=255, help_text="Internal name for reference")
    title = models.CharField(max_length=255, blank=True, null=True)
    subtitle = models.CharField(max_length=255, blank=True, null=True)
    description = CKEditor5Field(blank=True, null=True)

    # Visual elements
    icon = models.TextField(blank=True, null=True)
    image = models.ImageField(
        upload_to="page-sections/images/",
        validators=[validate_image_size],
        blank=True,
        null=True,
    )
    background_image = models.ImageField(
        upload_to="page-sections/backgrounds/",
        validators=[validate_image_size],
        blank=True,
        null=True,
    )

    # Layout and styling
    content_alignment = models.CharField(
        max_length=10, choices=CONTENT_ALIGNMENT, default="left"
    )
    background_color = models.CharField(
        max_length=7, blank=True, null=True, help_text="Hex color code"
    )
    text_color = models.CharField(
        max_length=7, blank=True, null=True, help_text="Hex color code"
    )
    is_visible = models.BooleanField(default=True)
    order = models.PositiveIntegerField(default=0)

    # Flexible data storage
    key_points = models.JSONField(blank=True, default=list)
    metadata = models.JSONField(
        blank=True, default=dict, help_text="Additional configuration data"
    )

    class Meta:
        ordering = ["page", "order", "name"]
        unique_together = ["page", "name"]

    def __str__(self):
        if self.page:
            return f"{self.page.name} - {self.name}"
        return self.name


class PageSectionItem(models.Model):
    section = models.ForeignKey(
        PageSection, related_name="items", on_delete=models.CASCADE
    )
    title = models.CharField(max_length=255, blank=True, null=True)
    subtitle = models.CharField(max_length=255, blank=True, null=True)
    description = CKEditor5Field(blank=True, null=True)

    # Visual elements
    icon = models.TextField(blank=True, null=True)
    image = models.ImageField(
        upload_to="page-section-items/images/",
        validators=[validate_image_size],
        blank=True,
        null=True,
    )

    # Flexible data storage
    key_points = models.JSONField(blank=True, default=list)
    metadata = models.JSONField(
        blank=True, default=dict, help_text="Additional item data"
    )

    # Ordering and visibility
    order = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)

    # Optional links
    button_text = models.CharField(max_length=100, blank=True, null=True)
    button_url = models.CharField(max_length=500, blank=True, null=True)

    class Meta:
        ordering = ["section", "order", "title"]

    def __str__(self):
        if self.title:
            return f"{self.section.name} - {self.title}"
        return f"{self.section.name} - Item {self.id}"


class Tag(models.Model):
    name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.name


class AdvertiseContent(models.Model):
    TYPE_CHOICES = (
        ('popup', 'Popup'),
        ('single', 'Single'),
        ('slider', 'Slider'),
    )

    name = models.CharField(max_length=255)
    type = models.CharField(max_length=20, choices=TYPE_CHOICES)
    created_at = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.name} ({self.type})"


class AdvertiseImage(models.Model):
    advertise_content = models.ForeignKey(
        AdvertiseContent,
        related_name='images',
        on_delete=models.CASCADE
    )
    image = models.ImageField(upload_to='advertisements/')
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return f"Image for {self.advertise_content.name}"