from django.db import models
from django.conf import settings
import uuid
from tenants.models import Tenants

# Choices for the type of poll/survey
POLL_TYPES = [
    ("poll", "Poll"),
    ("survey", "Survey"),
    ("quiz", "Quiz"),
]

# Choices for the status of the poll/survey
STATUS_CHOICES = [
    ("draft", "Draft"),
    ("active", "Active"),
    ("closed", "Closed"),
]

# Choices for the type of question
QUESTION_TYPES = [
    ("multiple_choice", "Multiple Choice"),
    ("text", "Text"),
    ("rating", "Rating"),
    ("checkbox", "Checkbox"),
]


class PollSurvey(models.Model):
    """
    Represents a multi-tenant poll, survey, or quiz.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    tenant = models.ForeignKey(
        Tenants, on_delete=models.CASCADE, related_name="polls_surveys"
    )
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    type = models.CharField(max_length=20, choices=POLL_TYPES, default="survey")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="draft")
    start_date = models.DateTimeField(null=True, blank=True)
    end_date = models.DateTimeField(null=True, blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="created_polls_surveys",
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

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


class Question(models.Model):
    """
    Represents a question within a poll or survey.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    tenant = models.ForeignKey(
        Tenants, on_delete=models.CASCADE, related_name="questions"
    )
    survey = models.ForeignKey(
        PollSurvey, on_delete=models.CASCADE, related_name="questions"
    )
    question_text = models.TextField()
    question_type = models.CharField(max_length=20, choices=QUESTION_TYPES)
    order = models.IntegerField()

    def __str__(self):
        return f"Q{self.order}: {self.question_text[:50]}..."


class Option(models.Model):
    """
    Model to store options for multiple-choice and checkbox questions.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    question = models.ForeignKey(
        Question, related_name="options", on_delete=models.CASCADE
    )
    option_text = models.CharField(max_length=255)

    def __str__(self):
        return f"{self.question.question_text} - {self.option_text}"


class Response(models.Model):
    """
    Represents a single user's submission to a poll or survey.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    tenant = models.ForeignKey(
        Tenants, on_delete=models.CASCADE, related_name="responses"
    )
    survey = models.ForeignKey(
        PollSurvey, on_delete=models.CASCADE, related_name="responses"
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="submitted_responses",
    )
    submitted_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("user", "survey")

    def __str__(self):
        return f"Response by {self.user} to '{self.survey.title}'"


class ResponseDetail(models.Model):
    """
    Stores the details of a specific answer to a question within a response.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    tenant = models.ForeignKey(
        Tenants, on_delete=models.CASCADE, related_name="response_details"
    )
    response = models.ForeignKey(
        Response, on_delete=models.CASCADE, related_name="details"
    )
    question = models.ForeignKey(
        Question, on_delete=models.CASCADE, related_name="answers"
    )
    answer_text = models.TextField(blank=True, null=True)
    option = models.ForeignKey(
        Option,
        on_delete=models.SET_NULL,  # Use SET_NULL so answers are not deleted if the option is.
        null=True,
        blank=True,
        related_name="responses",
    )
    rating_value = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return f"Answer for '{self.question.question_text[:30]}...'"
