from django.db import models
from django.contrib.auth.models import User


COURSE_CHOICES = [
    ("graphics", "Graphics Design"),
    ("digital_art", "Digital Art"),
    ("photography", "Photography"),
    ("photography_graphics", "Photography & Editing"),
    ("graphics_digital_art", "Graphics & Digital Art"),
    ("programming", "Programming"),
    ("special_offer", "Special Offer"),
]

GENDER_CHOICES = [
    ("male", "Male"),
    ("female", "Female"),
]

COURSE_PRICES = {
    "graphics": 30000,
    "digital_art": 35000,
    "photography": 45000,
    "photography_graphics": 50000,
    "graphics_digital_art": 45000,
    "programming": 40000,
    "special_offer": 70000,
}


class PortfolioItem(models.Model):
    """Works by instructors displayed publicly."""

    CATEGORY_CHOICES = [
        ("graphics", "Graphics Design"),
        ("digital_art", "Digital Art"),
        ("photography", "Photography"),
        ("programming", "Programming"),
        ("special_offer", "Special Offer"),
    ]
    title = models.CharField(max_length=200)
    category = models.CharField(max_length=50, choices=CATEGORY_CHOICES)
    image = models.ImageField(upload_to="portfolio/")
    description = models.TextField(blank=True)
    instructor_name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.title} – {self.instructor_name}"

    class Meta:
        ordering = ["-created_at"]


class Student(models.Model):
    """Registration record for a student."""

    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    full_name = models.CharField(max_length=200)
    email = models.EmailField(unique=True)
    phone_number = models.CharField(max_length=20)
    course = models.CharField(max_length=50, choices=COURSE_CHOICES)
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES)
    has_prior_knowledge = models.BooleanField(default=False)
    registered_at = models.DateTimeField(auto_now_add=True)
    payment_confirmed = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True, verbose_name="Active")

    class Meta:
        ordering = ["-registered_at", "-is_active", "name"]

    # Password saved hashed for login
    raw_password_hint = models.CharField(
        max_length=100,
        blank=True,
        help_text="Store only for admin reference — never use plain text in production",
    )

    def __str__(self):
        return f"{self.full_name} – {self.get_course_display()}"

    @property
    def course_price(self):
        return COURSE_PRICES.get(self.course, 0)

    @property
    def formatted_price(self):
        return f"₦{self.course_price:,}"

    class Meta:
        ordering = ["-registered_at"]


class TestAttendance(models.Model):
    """Tracks test/exam completion for each student."""

    TEST_TYPE_CHOICES = [
        ("test1", "Test 1"),
        ("test2", "Test 2"),
        ("test3", "Test 3"),
        ("exam", "Final Exam"),
    ]
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="attendances"
    )
    test_type = models.CharField(max_length=20, choices=TEST_TYPE_CHOICES)
    completed = models.BooleanField(default=False)
    date_completed = models.DateField(null=True, blank=True)

    class Meta:
        unique_together = ("student", "test_type")

    def __str__(self):
        status = "✓" if self.completed else "✗"
        return f"{self.student.full_name} – {self.get_test_type_display()} {status}"


class PerformanceRating(models.Model):
    """Instructor-assigned performance rating."""

    student = models.OneToOneField(
        Student, on_delete=models.CASCADE, related_name="performance"
    )
    score = models.IntegerField(default=0, help_text="Score out of 100")
    remarks = models.TextField(blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.student.full_name} – {self.score}/100"

    @property
    def grade(self):
        if self.score >= 80:
            return "A"
        elif self.score >= 70:
            return "B"
        elif self.score >= 60:
            return "C"
        elif self.score >= 50:
            return "D"
        return "F"

    @property
    def grade_label(self):
        labels = {
            "A": "Excellent",
            "B": "Good",
            "C": "Average",
            "D": "Below Average",
            "F": "Fail",
        }
        return labels.get(self.grade, "")


class Assignment(models.Model):
    """Assignment uploaded by a student."""

    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="assignments"
    )
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    file = models.FileField(upload_to="assignments/")
    submitted_at = models.DateTimeField(auto_now_add=True)
    feedback = models.TextField(blank=True)

    def __str__(self):
        return f"{self.title} – {self.student.full_name}"

    class Meta:
        ordering = ["-submitted_at"]
