"""
Site-wide settings for the academy (singleton).
"""
from django.db import models

from utils.choices import THEME_PRESET_CHOICES, THEME_PRESETS


class SiteSettings(models.Model):
    """
    Global academy settings — only one row should exist.
    Access via SiteSettings.load().
    """
    # Branding
    institute_name = models.CharField(
        max_length=150,
        default='TSN Digital Academy',
        help_text='Displayed across the site (navbar, titles, emails).',
    )
    tagline = models.CharField(
        max_length=200,
        blank=True,
        default='Learn Anything, Anytime',
    )
    logo = models.ImageField(
        upload_to='Logo/',
        blank=True,
        null=True,
        help_text='Light logo (white / light artwork) for dark backgrounds — navbar and auth brand panel.',
    )
    logo_dark = models.ImageField(
        upload_to='Logo/',
        blank=True,
        null=True,
        help_text='Dark logo for light backgrounds — login form panel and light surfaces.',
    )
    favicon = models.ImageField(
        upload_to='Logo/',
        blank=True,
        null=True,
    )

    # Certificates
    certificate_verify_url = models.CharField(
        max_length=255,
        blank=True,
        default='',
        help_text=(
            'Public URL printed on certificates as “Verify At” '
            '(e.g. https://verify.tsn.academy or https://yoursite.com/certifications/verify/). '
            'Leave blank to use this site’s built-in verify page.'
        ),
    )
    certificate_signer_name = models.CharField(
        max_length=120,
        blank=True,
        default='',
        help_text='Name shown under the signature on certificates (optional).',
    )
    certificate_signer_title = models.CharField(
        max_length=120,
        blank=True,
        default='Director',
        help_text='Title under the signature (default: Director).',
    )
    certificate_signature = models.ImageField(
        upload_to='certificates/',
        blank=True,
        null=True,
        help_text='Optional signature image for hard-copy certificates.',
    )
    certificate_seal = models.ImageField(
        upload_to='certificates/',
        blank=True,
        null=True,
        help_text='Official seal image shown on certificates (e.g. golden seal).',
    )

    # Theme / color scheme
    theme_preset = models.CharField(
        max_length=20,
        choices=THEME_PRESET_CHOICES,
        default='ocean',
        help_text='Quick color scheme. Choose Custom to use the colors below.',
    )
    theme_primary = models.CharField(
        max_length=7,
        default='#1e40af',
        help_text='Primary brand color (buttons, links). Hex e.g. #1e40af',
    )
    theme_secondary = models.CharField(
        max_length=7,
        default='#0f2557',
        help_text='Dark navbar / footer color.',
    )
    theme_accent = models.CharField(
        max_length=7,
        default='#f59e0b',
        help_text='Accent / highlight color (CTAs, badges).',
    )
    theme_success = models.CharField(
        max_length=7,
        default='#059669',
        help_text='Success / positive status color.',
    )

    # Pricing / currency
    currency_code = models.CharField(
        max_length=3,
        default='PKR',
        help_text='ISO currency code used for display and Stripe (e.g. PKR, USD, EUR).',
    )
    currency_symbol = models.CharField(
        max_length=8,
        default='PKR',
        help_text='Symbol shown next to prices (e.g. PKR, $, €).',
    )

    # Payment methods
    enable_manual_payment = models.BooleanField(
        default=True,
        help_text='Students upload a payment screenshot for admin/teacher approval.',
    )
    enable_stripe_payment = models.BooleanField(
        default=False,
        help_text='Students pay online via Stripe; enrollment auto-activates on success.',
    )
    manual_payment_instructions = models.TextField(
        blank=True,
        default=(
            'Please pay your course fee via Easypaisa / bank transfer.\n'
            'Account Number: 0345-1234567\n'
            'After paying, upload a screenshot of your transaction receipt below.'
        ),
        help_text='Shown to students on the manual payment page.',
    )

    # Stripe credentials (stored for admin UI; keep secret keys private)
    stripe_publishable_key = models.CharField(max_length=255, blank=True)
    stripe_secret_key = models.CharField(max_length=255, blank=True)
    stripe_webhook_secret = models.CharField(max_length=255, blank=True)

    # Email / SMTP (overrides .env when smtp_enabled is True)
    smtp_enabled = models.BooleanField(
        default=False,
        help_text='Use the SMTP settings below instead of .env / console backend.',
    )
    smtp_host = models.CharField(
        max_length=255,
        blank=True,
        default='',
        help_text='e.g. mail.yourdomain.com or smtp.gmail.com',
    )
    smtp_port = models.PositiveIntegerField(default=587)
    smtp_use_tls = models.BooleanField(default=True)
    smtp_use_ssl = models.BooleanField(
        default=False,
        help_text='Use SSL (port 465). Do not enable TLS and SSL together.',
    )
    smtp_username = models.CharField(max_length=255, blank=True, default='')
    smtp_password = models.CharField(max_length=255, blank=True, default='')
    smtp_from_email = models.CharField(
        max_length=255,
        blank=True,
        default='',
        help_text='From address, e.g. TSN Digital Academy <noreply@yourdomain.com>',
    )

    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Site Settings'
        verbose_name_plural = 'Site Settings'

    def __str__(self):
        return self.institute_name

    def save(self, *args, **kwargs):
        self.pk = 1
        # Apply preset colors unless custom
        if self.theme_preset != 'custom' and self.theme_preset in THEME_PRESETS:
            colors = THEME_PRESETS[self.theme_preset]
            self.theme_primary = colors['primary']
            self.theme_secondary = colors['secondary']
            self.theme_accent = colors['accent']
            self.theme_success = colors['success']
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        pass

    @classmethod
    def load(cls):
        obj, _ = cls.objects.get_or_create(pk=1)
        return obj

    @property
    def logo_url(self):
        """Light logo URL for dark backgrounds (empty if unset)."""
        if self.logo:
            return self.logo.url
        return ''

    @property
    def logo_dark_url(self):
        """Dark logo for light backgrounds only — never falls back to the light logo."""
        if self.logo_dark:
            return self.logo_dark.url
        return ''

    @property
    def logo_light_url(self):
        """Light logo for dark backgrounds only — never falls back to the dark logo."""
        if self.logo:
            return self.logo.url
        return ''

    @property
    def has_logo(self):
        return bool(self.logo or self.logo_dark)

    @property
    def has_logo_light(self):
        return bool(self.logo)

    @property
    def has_logo_dark(self):
        return bool(self.logo_dark)

    @property
    def favicon_url(self):
        if self.favicon:
            return self.favicon.url
        return ''

    @property
    def has_favicon(self):
        return bool(self.favicon)

    @property
    def stripe_ready(self):
        return bool(
            self.enable_stripe_payment
            and self.stripe_secret_key
            and self.stripe_publishable_key
        )

    @property
    def any_payment_enabled(self):
        return self.enable_manual_payment or self.stripe_ready

    def get_certificate_verify_url(self, request=None):
        """
        Base URL printed on certificates as Verify At.
        Prefer /verify/ (Part 6 course certificates). Configured override wins.
        """
        configured = (self.certificate_verify_url or '').strip()
        if configured:
            return configured.rstrip('/')
        if request is not None:
            return request.build_absolute_uri('/verify/').rstrip('/')
        return '/verify'

    @property
    def has_certificate_signature(self):
        return bool(self.certificate_signature)

    @property
    def has_certificate_seal(self):
        return bool(self.certificate_seal)

    def resolved_colors(self):
        """Return the active color map for CSS variables."""
        if self.theme_preset != 'custom' and self.theme_preset in THEME_PRESETS:
            return THEME_PRESETS[self.theme_preset]
        return {
            'primary': self.theme_primary or '#1e40af',
            'secondary': self.theme_secondary or '#0f2557',
            'accent': self.theme_accent or '#f59e0b',
            'success': self.theme_success or '#059669',
        }

    @property
    def smtp_ready(self):
        """True when admin SMTP is enabled and has a usable host + from address."""
        return bool(
            self.smtp_enabled
            and (self.smtp_host or '').strip()
            and (self.smtp_from_email or self.smtp_username or '').strip()
        )


EMAIL_TRIGGER_MANUAL = 'manual'
EMAIL_TRIGGER_SIGNUP = 'signup'
EMAIL_TRIGGER_PASSWORD_RESET = 'password_reset'

EMAIL_TRIGGER_CHOICES = [
    (EMAIL_TRIGGER_MANUAL, 'Manual / bulk only'),
    (EMAIL_TRIGGER_SIGNUP, 'On user signup (welcome)'),
    (EMAIL_TRIGGER_PASSWORD_RESET, 'Password reset'),
]


class EmailTemplate(models.Model):
    """
    Editable email templates for signup welcome, password reset, and campaigns.
    Placeholders: {{ user_name }}, {{ email }}, {{ username }}, {{ institute_name }},
    {{ login_url }}, {{ reset_url }}, {{ year }}, {{ role }}.
    """
    name = models.CharField(max_length=120)
    slug = models.SlugField(
        max_length=80,
        unique=True,
        help_text='Stable key, e.g. signup_welcome or promo_march.',
    )
    trigger = models.CharField(
        max_length=32,
        choices=EMAIL_TRIGGER_CHOICES,
        default=EMAIL_TRIGGER_MANUAL,
        help_text='When this template is sent automatically.',
    )
    subject = models.CharField(max_length=255)
    body_html = models.TextField(
        help_text='HTML body. Use placeholders like {{ user_name }}.',
    )
    body_text = models.TextField(
        blank=True,
        default='',
        help_text='Plain-text fallback (optional).',
    )
    is_active = models.BooleanField(
        default=True,
        help_text='Inactive templates are never sent automatically.',
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['name']
        verbose_name = 'Email template'
        verbose_name_plural = 'Email templates'

    def __str__(self):
        return f'{self.name} ({self.slug})'
