import json

from django.db import models


class Profile(models.Model):
    """Data diri pemilik website. Dirancang single-row (pakai Profile.get_solo())."""

    full_name = models.CharField("Nama lengkap", max_length=120)
    headline = models.CharField(
        "Headline", max_length=180, help_text="Contoh: Fullstack Developer & UI Enthusiast"
    )
    tagline_words = models.CharField(
        "Kata bergantian (hero)",
        max_length=250,
        blank=True,
        help_text="Pisahkan dengan koma. Contoh: Web Developer, Problem Solver, Coffee Lover",
    )
    bio = models.TextField("Bio singkat", blank=True)
    about = models.TextField("Tentang saya (panjang)", blank=True)
    photo = models.ImageField("Foto profil", upload_to="profile/", blank=True, null=True)
    hero_image = models.ImageField("Gambar hero", upload_to="profile/", blank=True, null=True)
    location = models.CharField("Lokasi", max_length=120, blank=True)
    email = models.EmailField("Email", blank=True)
    phone = models.CharField("No. HP / WhatsApp", max_length=40, blank=True)
    cv_file = models.FileField("File CV", upload_to="cv/", blank=True, null=True)
    is_open_to_work = models.BooleanField("Open to work", default=True)

    meta_description = models.CharField("Meta description (SEO)", max_length=300, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Profil"
        verbose_name_plural = "Profil"

    def __str__(self):
        return self.full_name or "Profil"

    @classmethod
    def get_solo(cls):
        profile = cls.objects.prefetch_related("social_links").first()
        if profile is None:
            profile = cls.objects.create(
                full_name="Nama Kamu",
                headline="Tulis headline kamu di sini",
            )
        return profile

    @property
    def words(self):
        return [w.strip() for w in self.tagline_words.split(",") if w.strip()]

    @property
    def words_json(self):
        """Dipakai oleh efek mengetik di hero."""
        return json.dumps(self.words or [self.headline])

    @property
    def whatsapp_url(self):
        digits = "".join(ch for ch in self.phone if ch.isdigit())
        if not digits:
            return ""
        if digits.startswith("0"):
            digits = "62" + digits[1:]
        return f"https://wa.me/{digits}"


class SocialLink(models.Model):
    PLATFORM_CHOICES = [
        ("github", "GitHub"),
        ("linkedin", "LinkedIn"),
        ("instagram", "Instagram"),
        ("x", "X / Twitter"),
        ("youtube", "YouTube"),
        ("tiktok", "TikTok"),
        ("facebook", "Facebook"),
        ("dribbble", "Dribbble"),
        ("behance", "Behance"),
        ("website", "Website"),
        ("email", "Email"),
    ]

    profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="social_links")
    platform = models.CharField("Platform", max_length=30, choices=PLATFORM_CHOICES)
    label = models.CharField("Label", max_length=60, blank=True)
    url = models.URLField("URL", max_length=300)
    order = models.PositiveIntegerField("Urutan", default=0)
    is_active = models.BooleanField("Tampilkan", default=True)

    class Meta:
        ordering = ["order", "id"]
        verbose_name = "Social link"
        verbose_name_plural = "Social links"

    def __str__(self):
        return f"{self.get_platform_display()} - {self.url}"

    @property
    def display_label(self):
        return self.label or self.get_platform_display()
