from django.shortcuts import render, redirect
from django.core.mail import send_mail
from django.conf import settings
from django.views.generic import View
from django.contrib import messages
from django.utils import timezone  # Ensure this is imported

from at_django_boilerplate.accounts.models import CustomUser
from at_django_boilerplate.communications.models import FeedbackModel, AppointmentModel
from at_django_boilerplate.backend_admin.models import SEOConfiguration
from django.views.generic import TemplateView

class ContactView(View):
    template_name = 'contact_us_form.html'

    def get(self, request, *args, **kwargs):
        seo = SEOConfiguration.objects.first()
        context = {
            'user': request.user,
            'meta_title': seo.contact_meta_title if seo else "Contact Us - RegisterYourStartup",
            'meta_description': seo.contact_meta_description if seo else "Get in touch with our team."
        }
        return render(request, self.template_name, context)

    def post(self, request, *args, **kwargs):
        custom_user = None
        if request.user.is_authenticated:
            try:
                custom_user = request.user
            except CustomUser.DoesNotExist:
                pass

        subject = request.POST.get('subject')
        message = request.POST.get('message')
        name = request.POST.get('name')

        email = ''
        phone = ''
        full_name = name or "Anonymous User"

        if custom_user:
            email = custom_user.get_decrypted_email()
            phone = custom_user.get_decrypted_contact_number()
            full_name = custom_user.get_full_name() or name or "Authenticated User"
        else:
            email = request.POST.get('email')
            phone = request.POST.get('phone')

        # Save feedback
        feedback = FeedbackModel(
            user=custom_user,
            name=full_name,
            email=email,
            phone=phone,
            subject=subject,
            message=message
        )
        feedback.save()
        ticket_id = feedback.id

        # Prepare and send email
        email_message = f'''
        Ticket ID:\t{ticket_id}
        Name:\t{full_name}
        Email:\t{email}
        Contact Number:\t{phone or 'Not provided'}
        Subject:\t{subject}
        Message:\t{message}
        '''

        try:
            send_mail(
                subject='You have a new message on RegisterYourStartup',
                message=email_message,
                from_email=settings.EMAIL_HOST_USER,
                recipient_list=[settings.EMAIL_HOST_USER],
                fail_silently=False,
            )
        except Exception as e:
            print("Email sending failed:", e)

        messages.success(
            request,
            f"Thank you, <strong>{full_name.split()[0] if full_name.split() else 'there'}</strong>! "
            f"Your message has been sent successfully. "
            f"Your Ticket ID is <strong>{ticket_id}</strong>. We will get back to you shortly."
        )

        return redirect('contact_us_form')


class AppointmentView(View):
    template_name = 'book_appointment.html'

    def get(self, request, *args, **kwargs):
        seo = SEOConfiguration.objects.first()
        context = {
            'meta_title': seo.appointment_meta_title if seo and seo.appointment_meta_title else "Book an Appointment - RegisterYourStartup.com",
            'meta_description': seo.appointment_meta_description if seo and seo.appointment_meta_description else "Schedule a consultation with our business experts.",
        }
        return render(request, self.template_name, context)

    def post(self, request, *args, **kwargs):
        custom_user = None
        if request.user.is_authenticated:
            try:
                custom_user = request.user
            except CustomUser.DoesNotExist:
                pass

        full_name = request.POST.get('fullName')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        meeting_with = request.POST.get('meetingWith')
        appointment_datetime_str = request.POST.get('appointmentDateTime')
        notes = request.POST.get('notes', '')

        # Basic server-side validation
        if not all([full_name, email, phone, meeting_with, appointment_datetime_str]):
            messages.error(request, "All required fields must be filled.")
            return redirect('book_appointment')

        try:
            # Parse the datetime-local input (format: YYYY-MM-DDTHH:MM)
            # Replace 'T' with space to make it compatible with fromisoformat
            naive_datetime = timezone.datetime.fromisoformat(
                appointment_datetime_str.replace('T', ' ')
            )

            # Convert to timezone-aware datetime
            appointment_datetime = timezone.make_aware(naive_datetime)

            if appointment_datetime <= timezone.now():
                messages.error(request, "Appointment time must be in the future.")
                return redirect('book_appointment')
        except ValueError:
            messages.error(request, "Invalid date/time format.")
            return redirect('book_appointment')

        # Save appointment
        appointment = AppointmentModel(
            user=custom_user,
            full_name=full_name,
            email=email,
            phone=phone,
            meeting_with=meeting_with,
            appointment_datetime=appointment_datetime,
            notes=notes
        )
        appointment.save()

        ticket_id = f"APP-{appointment.pk:06d}"

        # Send email notification to admin
        email_subject = f"New Appointment Booking - {ticket_id}"
        email_message = f"""
New Appointment Request

Ticket ID: {ticket_id}
Name: {full_name}
Email: {email}
Phone: {phone}
Meet With: {appointment.get_meeting_with_display()}
Date & Time: {appointment_datetime.strftime('%d %B %Y, %I:%M %p')}
Notes: {notes or 'No additional notes'}

Please confirm or follow up with the user.
        """

        try:
            send_mail(
                subject=email_subject,
                message=email_message,
                from_email=settings.EMAIL_HOST_USER,
                recipient_list=[settings.EMAIL_HOST_USER],
                fail_silently=False,
            )
        except Exception as e:
            print("Appointment email failed:", e)

        # Success message via Django messages (shown on redirect)
        messages.success(
            request,
            f"Thank you, <strong>{full_name.split()[0] if full_name.split() else 'there'}</strong>! "
            f"Your appointment has been booked successfully. "
            f"Your Ticket ID is <strong>{ticket_id}</strong>. We will contact you shortly to confirm."
        )

        # Redirect to same page to show success message and prevent resubmission
        return redirect('book_appointment')



class Ticket(TemplateView):
    template_name = 'ticket.html'

class TeamCreate(TemplateView):
    template_name = 'team_create.html'

