import os
from datetime import date, timedelta
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.db.models import Q
from .models import Item, Outfit, DailySchedule, Category, Folder
from .forms import ItemForm

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

def get_weekly_schedule(user):
    today = date.today()
    start_of_week = today - timedelta(days=today.weekday())
    days = []
    for i in range(7):
        day_date = start_of_week + timedelta(days=i)
        schedule, _ = DailySchedule.objects.get_or_create(user=user, date=day_date)
        days.append({
            'date': day_date,
            'day_name': day_date.strftime('%A'),
            'schedule': schedule
        })
    return days

@login_required
def home(request):
    """Render the landing screen with the weekly planner grid."""
    weekly_days = get_weekly_schedule(request.user)
    total_items = Item.objects.filter(user=request.user).count()
    
    month = date.today().month
    if month in [12, 1, 2]:
        season = "Winter"
    elif month in [3, 4, 5]:
        season = "Spring"
    elif month in [6, 7, 8]:
        season = "Summer"
    else:
        season = "Autumn"

    context = {
        "weekly_days": weekly_days,
        "total_items": total_items,
        "current_season": season,
        "project_name": "New Style",
    }
    return render(request, "core/index.html", context)

@login_required
def new_fit(request):
    """View to create a new outfit on a model."""
    items = Item.objects.filter(user=request.user)
    categories = Category.objects.all()
    context = {
        "title": "New Fit",
        "items": items,
        "categories": categories,
        "total_items": items.count(),
    }
    return render(request, "core/new_fit.html", context)

@login_required
def outfits(request):
    """View all saved outfits and folders."""
    outfits = Outfit.objects.filter(user=request.user, folder__isnull=True)
    folders = Folder.objects.filter(user=request.user)
    context = {
        "outfits": outfits,
        "folders": folders,
        "title": "Outfits",
        "total_items": Item.objects.filter(user=request.user).count(),
    }
    return render(request, "core/outfits.html", context)

@login_required
def wardrobe(request):
    """Render the wardrobe items."""
    items = Item.objects.filter(user=request.user, item_type='wardrobe')
    categories = Category.objects.all()
    form = ItemForm(initial={'item_type': 'wardrobe'})
    context = {
        "items": items,
        "categories": categories,
        "title": "Wardrobe",
        "total_items": Item.objects.filter(user=request.user).count(),
        "form": form,
    }
    return render(request, "core/wardrobe.html", context)

@login_required
def accessories(request):
    """Render the accessories items."""
    items = Item.objects.filter(user=request.user, item_type='accessory')
    categories = Category.objects.all()
    form = ItemForm(initial={'item_type': 'accessory'})
    context = {
        "items": items,
        "categories": categories,
        "title": "Accessories",
        "total_items": Item.objects.filter(user=request.user).count(),
        "form": form,
    }
    return render(request, "core/wardrobe.html", context)

@login_required
def add_item(request):
    """Handle item creation."""
    if request.method == 'POST':
        form = ItemForm(request.POST, request.FILES)
        if form.is_valid():
            item = form.save(commit=False)
            item.user = request.user
            item.save()
            if item.item_type == 'accessory':
                return redirect('accessories')
            return redirect('wardrobe')
    return redirect('wardrobe')

@login_required
def delete_item(request, pk):
    item = get_object_or_404(Item, pk=pk, user=request.user)
    item.delete()
    return redirect(request.META.get('HTTP_REFERER', 'wardrobe'))

@login_required
def save_outfit(request):
    if request.method == 'POST':
        name = request.POST.get('name', 'Untitled Outfit')
        item_ids = request.POST.getlist('items')
        outfit = Outfit.objects.create(user=request.user, name=name)
        if item_ids:
            outfit.items.add(*item_ids)
        return redirect('outfits')
    return redirect('new_fit')

@login_required
def schedule_outfit(request):
    if request.method == 'POST':
        day_date = request.POST.get('date')
        outfit_id = request.POST.get('outfit_id')
        schedule = get_object_or_404(DailySchedule, user=request.user, date=day_date)
        if outfit_id:
            outfit = get_object_or_404(Outfit, pk=outfit_id, user=request.user)
            schedule.outfit = outfit
        else:
            schedule.outfit = None
        schedule.save()
    return redirect('home')

@login_required
def create_folder(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        if name:
            Folder.objects.create(user=request.user, name=name)
    return redirect('outfits')