from django.db import models
import json
from datetime import datetime
from django.core.serializers.json import DjangoJSONEncoder

from wagtail.models import Page
from modelcluster.fields import ParentalKey
from wagtail.admin.panels import FieldPanel
from wagtail.fields import RichTextField
from django import forms

# Custom model to store contact form submissions
class ContactFormSubmission(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100)
    email = models.EmailField()
    subject = models.CharField(max_length=200, blank=True)
    message = models.TextField()
    page = models.ForeignKey(Page, on_delete=models.CASCADE, related_name='contact_submissions')
    
    class Meta:
        ordering = ['-created_at']
        verbose_name = 'contact form submission'
        verbose_name_plural = 'contact form submissions'
    
    def __str__(self):
        return f"Contact from {self.name} ({self.created_at})"


class ContactPage(Page):
    intro = RichTextField(blank=True)
    thank_you_text = RichTextField(blank=True)
    
    # Contact Information
    email = models.CharField(max_length=100, blank=True, help_text="Your email address")
    phone = models.CharField(max_length=20, blank=True, help_text="Your phone number")
    location = models.CharField(max_length=100, blank=True, help_text="Your location")
    
    # Availability Information
    availability_text = models.TextField(blank=True, help_text="Describe your current availability")
    response_time = models.CharField(max_length=100, blank=True, help_text="Your typical response time")
    
    # No longer needed since we're handling form submissions directly in the serve method
    
    def serve(self, request, *args, **kwargs):
        """
        Override the serve method to handle custom form and AJAX requests
        """
        from django.http import JsonResponse
        from django.shortcuts import render
        from django import forms
        
        # Define a custom form class for our hardcoded form
        class ContactForm(forms.Form):
            name = forms.CharField(max_length=100, required=True)
            email = forms.EmailField(required=True)
            subject = forms.CharField(max_length=200, required=False)
            message = forms.CharField(widget=forms.Textarea, required=True)
        
        if request.method == 'POST':
            # Use our custom form instead of Wagtail's form builder
            form = ContactForm(request.POST)
            
            if form.is_valid():
                # Store the form submission in the database
                submission = ContactFormSubmission.objects.create(
                    name=form.cleaned_data['name'],
                    email=form.cleaned_data['email'],
                    subject=form.cleaned_data.get('subject', ''),
                    message=form.cleaned_data['message'],
                    page=self
                )
                
                # Check if this is an AJAX request
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': True})
                    
                # If not AJAX, render the thank you page
                context = self.get_context(request)
                context['form_submission'] = submission
                return render(request, 'contact/contact_page.html', context)
            else:
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'errors': form.errors}, status=400)
        
        # For GET requests, render the page with our custom form
        context = self.get_context(request)
        return render(request, 'contact/contact_page.html', context)

    content_panels = Page.content_panels + [
        FieldPanel('intro'),
        FieldPanel('thank_you_text'),
        
        # Contact Information
        FieldPanel('email'),
        FieldPanel('phone'),
        FieldPanel('location'),
        
        # Availability Information
        FieldPanel('availability_text'),
        FieldPanel('response_time'),
    ]
