import json
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.core.mail import send_mail
from django.conf import settings
from .models import AIInquiry, ContactSubmission

@csrf_exempt
@require_POST
def submit_ai_inquiry(request):
    try:
        if request.content_type == 'application/json':
            data = json.loads(request.body.decode('utf-8'))
        else:
            data = request.POST

        name = data.get('name', '').strip()
        email = data.get('email', '').strip()
        company = data.get('company', '').strip()
        role = data.get('role', '').strip()
        phone = data.get('phone', '').strip()
        interest = data.get('interest', '').strip()
        environment = data.get('environment', '').strip()
        timeline = data.get('timeline', '').strip()
        use_case = data.get('usecase', data.get('use_case', '')).strip()

        # Validation
        if not name or not email or not company or not use_case:
            return JsonResponse({
                'success': False,
                'error': 'Please fill in all required fields (Name, Business Email, Company, Use Case).'
            }, status=400)

        # Save to database table
        inquiry = AIInquiry.objects.create(
            name=name,
            email=email,
            company=company,
            role=role,
            phone=phone,
            interest=interest,
            environment=environment,
            timeline=timeline,
            use_case=use_case
        )

        # Company Notification Email
        company_email = getattr(settings, 'COMPANY_NOTIFICATION_EMAIL', getattr(settings, 'DEFAULT_FROM_EMAIL', 'info@datacapital.com'))
        subject = f"🚨 New AI Inquiry: {company} ({name})"
        message = f"""New AI & Intelligent Automation Inquiry Submitted:

--------------------------------------------------
Full Name:        {name}
Business Email:   {email}
Company / Agency: {company}
Role / Title:     {role or 'N/A'}
Phone Number:     {phone or 'N/A'}

Interested In:    {interest or 'N/A'}
Environment:      {environment or 'N/A'}
Timeline:         {timeline or 'N/A'}

Use Case Details:
{use_case}
--------------------------------------------------
Submitted At: {inquiry.created_at.strftime('%Y-%m-%d %H:%M:%S UTC')}
Inquiry ID: #{inquiry.id}
"""

        try:
            send_mail(
                subject=subject,
                message=message,
                from_email=getattr(settings, 'DEFAULT_FROM_EMAIL'),
                recipient_list=[company_email],
                fail_silently=False
            )
        except Exception as mail_err:
            print(f"[Email Warning] Could not send email: {mail_err}")

        return JsonResponse({
            'success': True,
            'message': 'Your AI inquiry has been submitted successfully!',
            'inquiry_id': inquiry.id
        })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'An unexpected error occurred: {str(e)}'
        }, status=500)


@csrf_exempt
@require_POST
def submit_contact_inquiry(request):
    try:
        if request.content_type == 'application/json':
            data = json.loads(request.body.decode('utf-8'))
        else:
            data = request.POST

        category = data.get('category', data.get('activeTab', 'project')).strip()
        name = data.get('name', data.get('contact', '')).strip()
        email = data.get('email', '').strip()
        company = data.get('company', data.get('organization', '')).strip()
        phone = data.get('phone', '').strip()
        role = data.get('role', data.get('roleNeeded', '')).strip()
        project_type = data.get('projectType', data.get('rfp', data.get('vehicle', data.get('engagement', '')))).strip()
        timeline = data.get('timeline', '').strip()
        budget = data.get('budget', '').strip()
        message = data.get('message', '').strip()

        if not name or not email:
            return JsonResponse({
                'success': False,
                'error': 'Please provide your Name and Email address.'
            }, status=400)

        submission = ContactSubmission.objects.create(
            category=category,
            name=name,
            email=email,
            company=company,
            phone=phone,
            role=role,
            project_type=project_type,
            timeline=timeline,
            budget=budget,
            message=message
        )

        # Send notification email
        recipient_email = getattr(settings, 'COMPANY_NOTIFICATION_EMAIL', getattr(settings, 'DEFAULT_FROM_EMAIL', 'info@datacapitalinc.com'))
        category_labels = {
            'project': 'Project Discussion',
            'teaming': 'Teaming / Public Sector',
            'capability': 'Capability Statement',
            'talent': 'Talent Request',
            'careers': 'Careers / General',
        }
        category_name = category_labels.get(category, category.title())

        subject = f"📬 New Website Contact Inquiry [{category_name}]: {name}"
        email_message = f"""New Contact Inquiry Submitted:

--------------------------------------------------
Category:         {category_name}
Full Name:        {name}
Email Address:    {email}
Company / Org:    {company or 'N/A'}
Phone Number:     {phone or 'N/A'}
Role / Title:     {role or 'N/A'}

Project / RFP:    {project_type or 'N/A'}
Timeline:         {timeline or 'N/A'}
Budget Range:     {budget or 'N/A'}

Message Details:
{message or 'N/A'}
--------------------------------------------------
Submitted At: {submission.created_at.strftime('%Y-%m-%d %H:%M:%S UTC')}
Submission ID: #{submission.id}
"""

        try:
            send_mail(
                subject=subject,
                message=email_message,
                from_email=getattr(settings, 'DEFAULT_FROM_EMAIL'),
                recipient_list=[recipient_email],
                fail_silently=False
            )
        except Exception as mail_err:
            print(f"[Email Warning] Could not send contact email: {mail_err}")

        return JsonResponse({
            'success': True,
            'message': 'Your contact inquiry has been received!',
            'submission_id': submission.id
        })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'An unexpected error occurred: {str(e)}'
        }, status=500)

