import json

from django.contrib import messages
from django.http import Http404, JsonResponse
from django.shortcuts import redirect, render
from django.views.decorators.http import require_http_methods, require_POST

from .assistant import generate_reply
from .data import SERVICES, WHY_US, get_featured_service, get_service
from .forms import ContactForm
from .mailer import notify_sales_inquiry, send_client_acknowledgement
from .models import ChatTranscript, Inquiry


def home(request):
    featured = get_featured_service()
    other_services = [s for s in SERVICES if s['slug'] != featured['slug']] if featured else SERVICES
    return render(request, 'website/home.html', {
        'services': SERVICES,
        'featured_service': featured,
        'other_services': other_services,
        'why_us': WHY_US,
    })


def services(request):
    return render(request, 'website/services.html', {
        'services': SERVICES,
    })


def service_detail(request, slug):
    service = get_service(slug)
    if not service:
        raise Http404('Service not found')
    others = [s for s in SERVICES if s['slug'] != slug]
    return render(request, 'website/service_detail.html', {
        'service': service,
        'other_services': others,
    })


def about(request):
    return render(request, 'website/about.html', {
        'why_us': WHY_US,
    })


@require_http_methods(['GET', 'POST'])
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            inquiry = form.save(commit=False)
            inquiry.source = 'contact_form'
            inquiry.save()
            notify_sales_inquiry(inquiry)
            send_client_acknowledgement(inquiry)
            messages.success(
                request,
                'Thank you. Your message is with our sales team — we will get back to you shortly.',
            )
            return redirect('contact')
    else:
        initial = {}
        service_slug = request.GET.get('service')
        if service_slug:
            initial['service'] = service_slug
        form = ContactForm(initial=initial)

    return render(request, 'website/contact.html', {
        'form': form,
        'services': SERVICES,
    })


def _json_body(request):
    try:
        return json.loads(request.body.decode('utf-8') or '{}')
    except json.JSONDecodeError:
        return {}


@require_POST
def chat_api(request):
    data = _json_body(request)
    message = (data.get('message') or '').strip()
    history = data.get('history') or []
    if not message:
        return JsonResponse({'ok': False, 'error': 'Message is required.'}, status=400)
    if len(message) > 4000:
        return JsonResponse({'ok': False, 'error': 'Message is too long.'}, status=400)

    if not request.session.session_key:
        request.session.create()
    session_key = request.session.session_key or ''

    ChatTranscript.objects.create(session_key=session_key, role='user', content=message)
    result = generate_reply(message, history=history)
    reply = result.get('reply') or ''
    handoff = bool(result.get('handoff'))
    ChatTranscript.objects.create(session_key=session_key, role='assistant', content=reply)

    return JsonResponse({
        'ok': True,
        'reply': reply,
        'handoff': handoff,
        'reason': result.get('reason') or '',
    })


@require_POST
def chat_lead_api(request):
    """Capture a chat lead and email sales@sphereflux.co.ke."""
    data = _json_body(request)
    name = (data.get('name') or '').strip()
    email = (data.get('email') or '').strip()
    phone = (data.get('phone') or '').strip()
    service = (data.get('service') or 'other').strip()
    message = (data.get('message') or '').strip()
    transcript = (data.get('transcript') or '').strip()

    if not name or not (email or phone) or not message:
        return JsonResponse(
            {'ok': False, 'error': 'Name, message, and email or phone are required.'},
            status=400,
        )

    valid_services = {c[0] for c in Inquiry.SERVICE_CHOICES}
    if service not in valid_services:
        service = 'other'

    # Guard against double-clicks creating duplicate leads/emails
    from django.utils import timezone
    from datetime import timedelta

    recent = Inquiry.objects.filter(
        source='chat',
        created_at__gte=timezone.now() - timedelta(seconds=45),
    )
    if email:
        recent = recent.filter(email__iexact=email)
    elif phone:
        recent = recent.filter(phone=phone)
    else:
        recent = recent.none()

    duplicate = recent.first()
    if duplicate:
        return JsonResponse({
            'ok': True,
            'emailed': True,
            'duplicate': True,
            'handoff_complete': True,
            'message': (
                'Thanks — your request is already with our sales team at sales@sphereflux.co.ke. '
                'A teammate will follow up shortly. For urgent needs, WhatsApp 0718 679 683.'
            ),
        })

    inquiry = Inquiry.objects.create(
        name=name,
        email=email or f'chat-lead+{phone}@sphereflux.co.ke',
        phone=phone,
        service=service,
        message=message if not transcript else f'{message}\n\n--- Chat summary ---\n{transcript}',
        source='chat',
    )

    sent = notify_sales_inquiry(inquiry)
    ack = send_client_acknowledgement(inquiry)

    return JsonResponse({
        'ok': True,
        'emailed': sent,
        'ack_emailed': ack,
        'handoff_complete': True,
        'message': (
            'Thanks — you are now with our human sales queue. '
            + (
                'Your details were emailed to sales@sphereflux.co.ke and a teammate will follow up shortly. '
                if sent else
                'We saved your request, but email delivery failed — please WhatsApp 0718 679 683 or email sales@sphereflux.co.ke directly. '
            )
            + 'For urgent needs, WhatsApp 0718 679 683.'
        ),
    })
