from django.db import models
from django.utils import timezone
from datetime import date
from django.core.validators import MinValueValidator, MaxValueValidator


class ICICTRegistrant(models.Model):
    """Model for ICICT AI Workshop registrants imported from CSV"""
    PAYMENT_STATUS_CHOICES = [
        ('awaiting_payment', 'Awaiting Payment'),
        ('completed', 'Completed'),
    ]
    
    registration_id = models.IntegerField(unique=True)
    name = models.CharField(max_length=255)
    email = models.EmailField(unique=True)
    affiliation = models.CharField(max_length=255, blank=True, null=True)
    phone_number = models.CharField(max_length=20, blank=True, null=True)
    address = models.TextField(blank=True, null=True)
    payment_status = models.CharField(max_length=20, choices=PAYMENT_STATUS_CHOICES, default='awaiting_payment')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'ICICT Registrant'
        verbose_name_plural = 'ICICT Registrants'
        ordering = ['name']
    
    def __str__(self):
        return f"{self.name} (ID: {self.registration_id})"


class AttendanceDay(models.Model):
    """Model to configure attendance days for the multi-day conference"""
    day_number = models.IntegerField(unique=True)
    date = models.DateField()
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    is_active = models.BooleanField(default=True, help_text="Whether attendance is currently being taken for this day")
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name = 'Attendance Day'
        verbose_name_plural = 'Attendance Days'
        ordering = ['day_number']
    
    def __str__(self):
        return f"Day {self.day_number}: {self.title} ({self.date})"


class DailyAttendance(models.Model):
    """Model to track daily attendance for each registrant"""
    registrant = models.ForeignKey(ICICTRegistrant, on_delete=models.CASCADE, related_name='attendances')
    attendance_day = models.ForeignKey(AttendanceDay, on_delete=models.CASCADE, related_name='attendances')
    checked_in_at = models.DateTimeField(auto_now_add=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.TextField(blank=True, null=True)
    
    class Meta:
        verbose_name = 'Daily Attendance'
        verbose_name_plural = 'Daily Attendances'
        unique_together = ['registrant', 'attendance_day']
        ordering = ['-checked_in_at']
    
    def __str__(self):
        return f"{self.registrant.name} - {self.attendance_day.title} ({self.checked_in_at.strftime('%Y-%m-%d %H:%M')})"


class AttendanceConfiguration(models.Model):
    """Singleton model to manage attendance configuration"""
    current_day = models.ForeignKey(AttendanceDay, on_delete=models.SET_NULL, null=True, blank=True, 
                                   help_text="The current day for which attendance is being taken")
    attendance_enabled = models.BooleanField(default=True, help_text="Whether attendance checking is currently enabled")
    welcome_message = models.TextField(default="Welcome to ICICT AI Workshop! Please confirm your attendance.", 
                                     help_text="Message shown to users on the attendance page")
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Attendance Configuration'
        verbose_name_plural = 'Attendance Configuration'
    
    def __str__(self):
        return f"Attendance Config - Day: {self.current_day}"
    
    def save(self, *args, **kwargs):
        # Ensure only one configuration exists
        if not self.pk and AttendanceConfiguration.objects.exists():
            raise ValueError("Only one AttendanceConfiguration instance is allowed")
        super().save(*args, **kwargs)
    
    @classmethod
    def get_config(cls):
        """Get or create the attendance configuration"""
        config, created = cls.objects.get_or_create(pk=1)
        return config


class WorkshopFeedback(models.Model):
    """Model to collect feedback for the ICICT Workshop/Conference"""
    RATING_CHOICES = [
        (1, '1 - Poor'),
        (2, '2 - Fair'),
        (3, '3 - Good'),
        (4, '4 - Very Good'),
        (5, '5 - Excellent'),
    ]
    
    SESSION_TYPE_CHOICES = [
        ('workshop', 'Workshop'),
        ('conference', 'Conference'),
        ('general', 'General/Overall'),
    ]
    
    # Participant information
    registrant = models.ForeignKey(ICICTRegistrant, on_delete=models.CASCADE, related_name='feedbacks', null=True, blank=True)
    participant_name = models.CharField(max_length=255, help_text="Name of the participant")
    participant_email = models.EmailField(help_text="Email address of the participant")
    
    # Session details
    attendance_day = models.ForeignKey(AttendanceDay, on_delete=models.CASCADE, related_name='feedbacks', null=True, blank=True)
    session_type = models.CharField(max_length=20, choices=SESSION_TYPE_CHOICES, default='workshop')
    
    # Ratings (1-5 scale)
    overall_rating = models.IntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)],
        choices=RATING_CHOICES,
        help_text="Overall rating of the session"
    )
    content_quality = models.IntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)],
        choices=RATING_CHOICES,
        help_text="Quality of content presented"
    )
    presenter_effectiveness = models.IntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)],
        choices=RATING_CHOICES,
        help_text="Effectiveness of the presenter/speaker"
    )
    venue_facilities = models.IntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)],
        choices=RATING_CHOICES,
        help_text="Quality of venue and facilities"
    )
    
    # Text feedback
    what_liked_most = models.TextField(
        help_text="What did you like most about today's session?",
        blank=True, null=True
    )
    suggestions_improvement = models.TextField(
        help_text="What suggestions do you have for improvement?",
        blank=True, null=True
    )
    additional_topics = models.TextField(
        help_text="What additional topics would you like to see covered?",
        blank=True, null=True
    )
    general_comments = models.TextField(
        help_text="Any other comments or feedback",
        blank=True, null=True
    )
    
    # Metadata
    submitted_at = models.DateTimeField(auto_now_add=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    is_anonymous = models.BooleanField(default=False, help_text="Whether feedback was submitted anonymously")
    
    class Meta:
        verbose_name = 'Workshop Feedback'
        verbose_name_plural = 'Workshop Feedbacks'
        ordering = ['-submitted_at']
        # Allow multiple feedback per person per day (morning/afternoon sessions)
        
    def __str__(self):
        day_info = self.attendance_day.title if self.attendance_day else "General Feedback"
        return f"{self.participant_name} - {day_info} ({self.submitted_at.strftime('%Y-%m-%d %H:%M')})"
    
    @property
    def average_rating(self):
        """Calculate average rating across all rating fields"""
        ratings = [
            self.overall_rating,
            self.content_quality,
            self.presenter_effectiveness,
            self.venue_facilities
        ]
        return sum(ratings) / len(ratings)


class FeedbackConfiguration(models.Model):
    """Configuration for feedback collection"""
    feedback_enabled = models.BooleanField(default=True, help_text="Whether feedback collection is enabled")
    current_feedback_day = models.ForeignKey(
        AttendanceDay, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True,
        help_text="Current day for which feedback is being collected"
    )
    feedback_message = models.TextField(
        default="We value your feedback! Please share your thoughts.",
        help_text="Message shown to participants on feedback form"
    )
    allow_anonymous_feedback = models.BooleanField(
        default=True, 
        help_text="Allow participants to submit feedback anonymously"
    )
    require_attendance = models.BooleanField(
        default=False,
        help_text="Require participants to have attended the day before giving feedback"
    )
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Feedback Configuration'
        verbose_name_plural = 'Feedback Configuration'
    
    def __str__(self):
        return f"Feedback Config - Day: {self.current_feedback_day}"
    
    def save(self, *args, **kwargs):
        # Ensure only one configuration exists
        if not self.pk and FeedbackConfiguration.objects.exists():
            raise ValueError("Only one FeedbackConfiguration instance is allowed")
        super().save(*args, **kwargs)
    
    @classmethod
    def get_config(cls):
        """Get or create the feedback configuration"""
        config, created = cls.objects.get_or_create(pk=1)
        return config
