from datetime import date

from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from tinymce.models import HTMLField


def humanize_duration(start, end):
    """Kembalikan durasi ala LinkedIn: '2 thn 3 bln'."""
    if not start:
        return ""
    end = end or date.today()
    months = (end.year - start.year) * 12 + (end.month - start.month) + 1
    months = max(months, 1)
    years, rest = divmod(months, 12)
    parts = []
    if years:
        parts.append(f"{years} thn")
    if rest:
        parts.append(f"{rest} bln")
    return " ".join(parts)


class Skill(models.Model):
    CATEGORY_CHOICES = [
        ("language", "Bahasa Pemrograman"),
        ("framework", "Framework / Library"),
        ("database", "Database"),
        ("ai", "AI & Automation"),
        ("tool", "Tools"),
        ("design", "Design"),
        ("soft", "Soft Skill"),
        ("other", "Lainnya"),
    ]

    name = models.CharField("Nama skill", max_length=80, unique=True)
    category = models.CharField("Kategori", max_length=20, choices=CATEGORY_CHOICES, default="other")
    level = models.PositiveSmallIntegerField(
        "Level (1-100)", default=70, help_text="Dipakai untuk progress bar"
    )
    icon_class = models.CharField(
        "Icon class", max_length=80, blank=True, help_text="Opsional, contoh: devicon-python-plain"
    )
    color = models.CharField(
        "Warna hex", max_length=9, blank=True, help_text="Opsional, contoh: #F97316"
    )
    order = models.PositiveIntegerField("Urutan", default=0)
    is_featured = models.BooleanField("Tampilkan di home", default=True)

    class Meta:
        ordering = ["order", "-level", "name"]
        verbose_name = "Skill"
        verbose_name_plural = "Skills"

    def __str__(self):
        return self.name


class Experience(models.Model):
    EMPLOYMENT_CHOICES = [
        ("fulltime", "Full-time"),
        ("parttime", "Part-time"),
        ("contract", "Kontrak"),
        ("freelance", "Freelance"),
        ("internship", "Magang"),
        ("volunteer", "Volunteer"),
    ]
    LOCATION_TYPE_CHOICES = [
        ("onsite", "On-site"),
        ("remote", "Remote"),
        ("hybrid", "Hybrid"),
    ]

    company = models.CharField("Perusahaan", max_length=140)
    company_url = models.URLField("Website perusahaan", blank=True)
    logo = models.ImageField("Logo", upload_to="company/", blank=True, null=True)
    position = models.CharField("Posisi", max_length=140)
    employment_type = models.CharField(
        "Tipe kerja", max_length=20, choices=EMPLOYMENT_CHOICES, default="fulltime"
    )
    location = models.CharField("Lokasi", max_length=140, blank=True)
    location_type = models.CharField(
        "Tipe lokasi", max_length=20, choices=LOCATION_TYPE_CHOICES, default="onsite"
    )
    start_date = models.DateField("Mulai")
    end_date = models.DateField("Selesai", blank=True, null=True)
    is_current = models.BooleanField("Masih bekerja di sini", default=False)
    description = models.TextField("Deskripsi", blank=True, help_text="Satu poin per baris")
    skills = models.ManyToManyField(Skill, blank=True, related_name="experiences", verbose_name="Skill")
    order = models.PositiveIntegerField("Urutan", default=0)
    is_published = models.BooleanField("Tampilkan", default=True)

    class Meta:
        ordering = ["order", "-start_date"]
        verbose_name = "Pengalaman Kerja"
        verbose_name_plural = "Pengalaman Kerja"

    def __str__(self):
        return f"{self.position} @ {self.company}"

    def save(self, *args, **kwargs):
        if self.is_current:
            self.end_date = None
        super().save(*args, **kwargs)

    @property
    def duration(self):
        return humanize_duration(self.start_date, None if self.is_current else self.end_date)

    @property
    def period(self):
        start = self.start_date.strftime("%b %Y") if self.start_date else ""
        if self.is_current:
            return f"{start} - Sekarang"
        end = self.end_date.strftime("%b %Y") if self.end_date else "Sekarang"
        return f"{start} - {end}"

    @property
    def bullets(self):
        return [line.strip(" -•\t") for line in self.description.splitlines() if line.strip()]


class Education(models.Model):
    school = models.CharField("Institusi", max_length=160)
    logo = models.ImageField("Logo", upload_to="school/", blank=True, null=True)
    degree = models.CharField("Jenjang / Gelar", max_length=120, blank=True)
    field_of_study = models.CharField("Jurusan", max_length=160, blank=True)
    start_date = models.DateField("Mulai")
    end_date = models.DateField("Selesai", blank=True, null=True)
    is_current = models.BooleanField("Masih berjalan", default=False)
    grade = models.CharField("Nilai / IPK", max_length=40, blank=True)
    description = models.TextField("Deskripsi", blank=True)
    order = models.PositiveIntegerField("Urutan", default=0)
    is_published = models.BooleanField("Tampilkan", default=True)

    class Meta:
        ordering = ["order", "-start_date"]
        verbose_name = "Pendidikan"
        verbose_name_plural = "Pendidikan"

    def __str__(self):
        return f"{self.school} - {self.degree}"

    def save(self, *args, **kwargs):
        if self.is_current:
            self.end_date = None
        super().save(*args, **kwargs)

    @property
    def period(self):
        start = self.start_date.strftime("%Y") if self.start_date else ""
        if self.is_current:
            return f"{start} - Sekarang"
        end = self.end_date.strftime("%Y") if self.end_date else ""
        return f"{start} - {end}"


class Certificate(models.Model):
    name = models.CharField("Nama sertifikat", max_length=180)
    issuer = models.CharField("Penerbit", max_length=160)
    logo = models.ImageField("Logo penerbit", upload_to="certificate/", blank=True, null=True)
    issue_date = models.DateField("Tanggal terbit")
    expire_date = models.DateField("Berlaku sampai", blank=True, null=True)
    credential_id = models.CharField("Credential ID", max_length=140, blank=True)
    credential_url = models.URLField("URL kredensial", blank=True)
    file = models.FileField("File sertifikat", upload_to="certificate/files/", blank=True, null=True)
    order = models.PositiveIntegerField("Urutan", default=0)
    is_published = models.BooleanField("Tampilkan", default=True)

    class Meta:
        ordering = ["order", "-issue_date"]
        verbose_name = "Sertifikat"
        verbose_name_plural = "Sertifikat"

    def __str__(self):
        return self.name

    @property
    def is_expired(self):
        return bool(self.expire_date and self.expire_date < date.today())


class Project(models.Model):
    STATUS_CHOICES = [
        ("completed", "Selesai"),
        ("ongoing", "Sedang dikerjakan"),
        ("archived", "Arsip"),
    ]

    title = models.CharField("Judul", max_length=180)
    slug = models.SlugField("Slug", max_length=200, unique=True, blank=True)
    thumbnail = models.ImageField("Thumbnail", upload_to="project/", blank=True, null=True)
    short_description = models.CharField("Deskripsi singkat", max_length=280, blank=True)
    description = HTMLField("Deskripsi lengkap", blank=True)
    role = models.CharField("Peran saya", max_length=140, blank=True)
    client = models.CharField("Klien / Perusahaan", max_length=140, blank=True)
    tech_stack = models.ManyToManyField(
        Skill, blank=True, related_name="projects", verbose_name="Tech stack"
    )
    demo_url = models.URLField("Link demo", blank=True)
    repo_url = models.URLField("Link repository", blank=True)
    status = models.CharField("Status", max_length=20, choices=STATUS_CHOICES, default="completed")
    started_at = models.DateField("Tanggal mulai", blank=True, null=True)
    finished_at = models.DateField("Tanggal selesai", blank=True, null=True)
    is_featured = models.BooleanField("Unggulan", default=False)
    is_published = models.BooleanField("Tampilkan", default=True)
    order = models.PositiveIntegerField("Urutan", default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["order", "-created_at"]
        verbose_name = "Proyek"
        verbose_name_plural = "Proyek"

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            base = slugify(self.title)[:180] or "proyek"
            slug, n = base, 2
            while Project.objects.filter(slug=slug).exclude(pk=self.pk).exists():
                slug = f"{base}-{n}"
                n += 1
            self.slug = slug
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("careers:project_detail", kwargs={"slug": self.slug})
