from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.decorators import login_required
from .forms import PropertyForm, BookingForm
from .models import Property, Booking

def index(request):
    properties = Property.objects.all()[:6]
    context = {
        'properties': properties
    }
    return render(request, 'core/index.html', context)

def property_detail(request, property_id):
    property = get_object_or_404(Property, pk=property_id)
    return render(request, 'core/property_detail.html', {'property': property})

def signup_view(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('index')
    else:
        form = UserCreationForm()
    return render(request, 'core/signup.html', {'form': form})

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('index')
    else:
        form = AuthenticationForm()
    return render(request, 'core/login.html', {'form': form})

def logout_view(request):
    if request.method == 'POST':
        logout(request)
        return redirect('index')

@login_required
def property_create(request):
    if request.method == 'POST':
        form = PropertyForm(request.POST, request.FILES)
        if form.is_valid():
            property = form.save(commit=False)
            property.owner = request.user
            property.save()
            return redirect('property_detail', property_id=property.id)
    else:
        form = PropertyForm()
    return render(request, 'core/property_create.html', {'form': form})

@login_required
def booking_create(request, property_id):
    property = get_object_or_404(Property, pk=property_id)
    if request.method == 'POST':
        form = BookingForm(request.POST)
        if form.is_valid():
            booking = form.save(commit=False)
            booking.property = property
            booking.user = request.user
            booking.save()
            return redirect('profile')
    else:
        form = BookingForm()
    return render(request, 'core/booking_create.html', {'form': form, 'property': property})

@login_required
def profile(request):
    bookings = Booking.objects.filter(user=request.user)
    return render(request, 'core/profile.html', {'bookings': bookings})

def about(request):
    return render(request, 'core/about.html')

def contact(request):
    return render(request, 'core/contact.html')

def faq(request):
    return render(request, 'core/faq.html')
