from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.core.mail import send_mail
from django.conf import settings
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password, check_password
from .models import SuperAdmin, Organization, Participant, Gift, Rules, Subscription
import uuid, random
from django.utils.crypto import get_random_string
from django.utils import timezone

def home(request):
    return render(request, 'santa_app/home.html')


# 🔹 SuperAdmin Login
def superadmin_login(request):
    if request.method == "POST":
        email = request.POST.get("email")
        password = request.POST.get("password")
        try:
            sa = SuperAdmin.objects.get(email=email)
            if sa.check_password(password):
                request.session["superadmin_id"] = sa.id
                request.session["superadmin_name"] = sa.name
                return redirect("superadmin_dashboard")
            else:
                messages.error(request, "Invalid password")
        except SuperAdmin.DoesNotExist:
            messages.error(request, "SuperAdmin not found")
    return render(request, "santa_app/superadmin_login.html")


# 🔹 SuperAdmin Dashboard
def superadmin_dashboard(request):
    if not request.session.get("superadmin_id"):
        return redirect("superadmin_login")
    superadmin = SuperAdmin.objects.get(id=request.session["superadmin_id"])
    orgs = Organization.objects.filter(super_admin=superadmin)
    return render(request, "santa_app/superadmin_dashboard.html", {"orgs": orgs, "superadmin": superadmin})


# 🔹 OrgAdmin Login
def org_admin_login(request):
    if request.method == "POST":
        org_id = request.POST.get("org_id").strip()
        email = request.POST.get("email").strip()
        password = request.POST.get("password").strip()
        try:
            org = Organization.objects.get(org_id=org_id, email=email)
            if org.check_password(password):
                request.session["org_admin_id"] = org.id
                request.session["org_admin_name"] = org.org_name
                return redirect("org_admin_dashboard")
            else:
                messages.error(request, "Invalid password")
        except Organization.DoesNotExist:
            messages.error(request, "Organization not found")
    return render(request, "santa_app/orgadmin_login.html")


# 🔹 Org Admin Dashboard
def org_admin_dashboard(request):
    if not request.session.get("org_admin_id"):
        return redirect("org_admin_login")
    org = Organization.objects.get(id=request.session["org_admin_id"])
    participants = Participant.objects.filter(organization=org, invite_accepted=True)
    gifts = Gift.objects.filter(organization=org)
    rules, _ = Rules.objects.get_or_create(org=org)
    return render(request, "santa_app/orgadmin_dashboard.html", {
        "org": org,
        "participants": participants,
        "gifts": gifts,
        "rules": rules
    })


# 🔹 Create Organization
def create_organization(request):
    if request.method == "POST":
        org_name = request.POST.get("org_name")
        email = request.POST.get("email")
        password = request.POST.get("password")
        superadmin = SuperAdmin.objects.get(id=request.session["superadmin_id"])
        Organization.objects.create(super_admin=superadmin, org_name=org_name, email=email, password=password)
        messages.success(request, "Organization created successfully!")
        return redirect("superadmin_dashboard")
    return render(request, "santa_app/create_organization.html")


# 🔹 Reset Org Password
def reset_org_password(request, org_id):
    if not request.session.get("superadmin_id"):
        return redirect("superadmin_login")
    try:
        org = Organization.objects.get(id=org_id)
        org.password = make_password("newpassword123")
        org.save()
        messages.success(request, f"Password reset for {org.org_name} (new: newpassword123)")
    except Organization.DoesNotExist:
        messages.error(request, "Organization not found")
    return redirect("superadmin_dashboard")


# 🔹 Participant Login
def participant_login(request):
    if request.method == "POST":
        org_id = request.POST.get("org_id").strip()
        email = request.POST.get("email").strip()
        password = request.POST.get("password").strip()
        try:
            org = Organization.objects.get(org_id=org_id)
            participant = Participant.objects.get(organization=org, email=email)
            if participant.check_password(password):
                request.session["participant_id"] = participant.id
                request.session["participant_name"] = participant.name
                messages.success(request, f"Welcome {participant.name}!")
                return redirect("participant_dashboard")
            else:
                messages.error(request, "Invalid password.")
        except (Organization.DoesNotExist, Participant.DoesNotExist):
            messages.error(request, "Invalid credentials.")
    return render(request, "santa_app/participant_login.html")


# 🔹 Participant Dashboard
def participant_dashboard(request):
    participant_id = request.session.get("participant_id")
    if not participant_id:
        messages.error(request, "Please login first.")
        return redirect("participant_login")
    participant = Participant.objects.get(id=participant_id)
    gifts = Gift.objects.filter(participant=participant)
    return render(request, "santa_app/participant_dashboard.html", {"participant": participant, "gifts": gifts})


# 🔹 OrgAdmin Adds Participant → Send Invite Email
def add_participant(request):
    if not request.session.get("org_admin_id"):
        messages.error(request, "Please login as Org Admin first.")
        return redirect("org_admin_login")

    org = Organization.objects.get(id=request.session["org_admin_id"])

    if request.method == "POST":
        email = request.POST.get("email")

        if Participant.objects.filter(email=email, organization=org).exists():
            messages.warning(request, f"Participant with email {email} already exists.")
            return redirect("org_admin_dashboard")

        invite_token = str(uuid.uuid4())

        participant = Participant.objects.create(
            organization=org,
            email=email,
            invited=True,
            invite_token=invite_token,
            invite_created_at=timezone.now()
        )

        invite_link = request.build_absolute_uri(f"/participant/accept_invite/{invite_token}/")

        subject = f"🎅 Secret Santa Invitation from {org.org_name}"
        message = (
            f"Hi there!\n\n"
            f"You've been invited to join {org.org_name}'s Secret Santa event!\n\n"
            f"Click the link below to accept your invitation:\n"
            f"These Link Will expire in 48 hrs:\n"
            f"{invite_link}\n\n"
            f"Best,\n{org.org_name} Team 🎁"
        )

        try:
            send_mail(
                subject,
                message,
                settings.EMAIL_HOST_USER,
                [email],
                fail_silently=False,
            )
            messages.success(request, f"Invitation email sent to {email}")
        except Exception as e:
            messages.error(request, f"Error sending invite email: {e}")

        return redirect("org_admin_dashboard")

    return render(request, "santa_app/add_participant.html")


# 🔹 Accept Invite
def accept_invite(request, token):
    participant = get_object_or_404(Participant, invite_token=token)
    org = participant.organization
    rules = Rules.objects.filter(org=org).first()

    # NEW: check if invite expired (48 hours)
    if participant.is_invite_expired:
        return render(request, "santa_app/invite_expired.html", {"participant": participant})

    if request.method == "POST":
        participant.name = request.POST.get("name")
        participant.hobbies = request.POST.get("hobbies")
        participant.invite_accepted = True
        participant.is_active = True
        participant.save()
        messages.success(request, "Thank you! Your invitation has been accepted successfully!")
        return redirect("participant_success")

    return render(request, "santa_app/accept_invite.html", {"participant": participant, "rules": rules})


def participant_success(request):
    return render(request, "participant_success.html")


# 🔹 Shuffle Assignments
def shuffle_assignments(request):
    if not request.session.get("org_admin_id"):
        return redirect("org_admin_login")

    org = Organization.objects.get(id=request.session["org_admin_id"])
    participants = list(Participant.objects.filter(organization=org, invite_accepted=True))

    if len(participants) < 2:
        messages.error(request, "At least 2 accepted participants required.")
        return redirect("org_admin_dashboard")

    random.shuffle(participants)
    for i, p in enumerate(participants):
        assigned = participants[(i + 1) % len(participants)]
        if assigned == p:
            assigned = participants[(i + 2) % len(participants)]
        p.assigned_to = assigned
        p.save()

        send_mail(
            subject="🎁 Your Secret Santa Match!",
            message=f"Hi {p.name}, your Secret Santa match is {assigned.name}. Their hobbies: {assigned.hobbies}",
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[p.email],
        )

    messages.success(request, "Participants shuffled and assigned successfully!")
    return redirect("org_admin_dashboard")


# 🔹 Edit Rules (Only Org Admin of that org)
def edit_rules(request):
    if not request.session.get("org_admin_id"):
        return redirect("org_admin_login")

    org = Organization.objects.get(id=request.session["org_admin_id"])
    rules, created = Rules.objects.get_or_create(org=org)

    # Default Christmas Rules if empty
    default_rules = (
        "🎅 Secret Santa Guidelines 🎄\n\n"
        "1. Keep your identity secret until the gift exchange.\n"
        "2. The gift budget should be between ₹500 - ₹1000.\n"
        "3. Gifts should be thoughtful and fun — avoid anything offensive.\n"
        "4. Make sure your gift is ready before the event day.\n"
        "5. Spread joy and kindness — it’s the Christmas spirit! ❤️\n"
    )

    # Show default rules if no custom ones exist
    if not rules.content or rules.content.strip() == "":
        rules.content = default_rules
        rules.save()

    if request.method == 'POST':
        new_rules = request.POST.get('rules', '').strip()
        if not new_rules:
            messages.error(request, "Rules cannot be empty!")
        else:
            rules.content = new_rules
            rules.save()
            messages.success(request, "Rules updated successfully!")
            return redirect("org_admin_dashboard")

    return render(request, "santa_app/edit_rules.html", {
        'rules': rules,
        'org': org
    })



# 🏠 HOME PAGE
def home(request):
    return render(request, "santa_app/home.html")


# 🏢 ORGANIZATION REGISTRATION
def register_organization(request):
    if request.method == "POST":
        org_name = request.POST.get("org_name")
        email = request.POST.get("email")
        password = request.POST.get("password") or "Org@123"

        superadmin = SuperAdmin.objects.first()
        if not superadmin:
            messages.error(request, "No SuperAdmin found. Please create one first.")
            return redirect("home")

        if Organization.objects.filter(email=email).exists():
            messages.warning(request, "Organization already registered with this email.")
            return redirect("register_organization")

        org = Organization.objects.create(
            super_admin=superadmin,
            org_name=org_name,
            email=email,
            password=password,
        )

        # send email to superadmin
        send_mail(
            "New Organization Registered",
            f"Organization '{org.org_name}' has registered successfully.\nEmail: {org.email}",
            settings.DEFAULT_FROM_EMAIL,
            [superadmin.email],
            fail_silently=True,
        )

        # redirect to payment form so the org completes subscription
        messages.success(request, f"{org.org_name} registered successfully! Please complete payment.")
        return redirect("payment_form", org_id=org.id)

    return render(request, "santa_app/register_organization.html")

# 🔹 Payment Form (after registration)
def payment_form(request, org_id):
    try:
        org = Organization.objects.get(id=org_id)
    except Organization.DoesNotExist:
        messages.error(request, "Organization not found.")
        return redirect("home")

    if request.method == "POST":
        plan_name = request.POST.get("plan_name")
        amount = request.POST.get("amount")
        # generate a simple transaction id
        transaction_id = str(uuid.uuid4())[:12].upper()

        # create or update subscription (OneToOne relation)
        Subscription.objects.create(
            organization=org,
            plan_name=plan_name,
            amount=amount,
            transaction_id=transaction_id,
            payment_status='Paid'
        )

        # send payment notification email to the superadmin of this org
        superadmin_email = org.super_admin.email
        send_mail(
            subject="💰 New Subscription Payment Received",
            message=(
                f"Organization '{org.org_name}' has completed subscription payment.\n\n"
                f"Plan: {plan_name}\nAmount: ₹{amount}\nTransaction ID: {transaction_id}"
            ),
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[superadmin_email],
            fail_silently=True,
        )

        messages.success(request, "Payment recorded. SuperAdmin has been notified.")
        return redirect("home")

    return render(request, "santa_app/payment_form.html", {"org": org})

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