import logging
import yaml

from django.shortcuts import render, redirect , get_object_or_404
from .forms import OrganizationForm
from .models import Organization,Document, DocumentTemplate
from backend.accounts.utils import send_confirmation_email, send_document_email
from django.contrib.admin.views.decorators import staff_member_required
from .utils import generate_pdf, generate_risk_graph, generate_residual_risk_graph
from .tables import risk_matrix_table ,get_risk_table, get_safeguard_summary_table
from django.conf import settings
site_domain = settings.SITE_DOMAIN
from .processors import render_template
from django.http import JsonResponse, FileResponse, Http404
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
import os



# @login_required
# def index(request):
#     return HttpResponse('<h1>Django</h1><p>Página simples.</p>')

logger = logging.getLogger(__name__)

# @login_required
def index(request):
    template_name = 'index.html'
    return render(request, template_name)


def signup(request):
    if request.method == 'POST':
        form = OrganizationForm(request.POST)
        if form.is_valid():
            form.save()
            send_confirmation_email(form.data['email'])

            return render(request, 'thankyou.html', {
                'email': form.data['email'],
                })
        else:
            logging.error(form.errors)
            return render(request, 'signup.html', {'form': form})
    else:
        form = OrganizationForm()

    return render(request, 'signup.html', {'form': form})


def validate_form_fields(request):
    name = request.GET.get('name', '').strip()
    email = request.GET.get('email', '').strip()
    errors = {}
    
    if name and Organization.objects.filter(name__iexact=name).exists():
        errors['name'] = 'Organization with this name already exists.'
    if email:
        try:
            validate_email(email)
        except ValidationError:
            errors['email'] = 'Please enter a valid email address.'
        else:
            if Organization.objects.filter(email__iexact=email).exists():
                errors['email'] = 'This email is already registered.'

    return JsonResponse({'errors': errors})


def thankyou(request):
    return render(request, 'thankyou.html')

def document(request, document_id):
    document = get_object_or_404(Document, id=document_id)
    risks_with_controls = get_risk_table(document)
    table_risk_matrix = risk_matrix_table()
    safeguard_summary_table = get_safeguard_summary_table(risks_with_controls)
    graph_base64 = generate_risk_graph(risks_with_controls)
    residual_graph_base64 = generate_residual_risk_graph(risks_with_controls)
    template_obj = get_object_or_404(DocumentTemplate, name="Default Template")
    template_content = template_obj.content 

    try:
        template_segments = yaml.safe_load(template_content)
    except yaml.YAMLError as e:
        return render(request, 'error.html', {'error_message': 'Error parsing template.'})
    context = {
        'document': document,
        'risks_with_controls': risks_with_controls,
        'graph': graph_base64,
        'table_risk_matrix': table_risk_matrix,
        'residual_graph': residual_graph_base64,
        'safeguard_summary_table': safeguard_summary_table,
        'table_risk_matrix_header' : table_risk_matrix[0],
        'table_risk_matrix_rows': table_risk_matrix[1:],
    }
    rendered_content = render_template(template_segments, context)
    return render(request, 'document.html',
                   {'rendered_html': rendered_content,
                    'document': document,})


@staff_member_required
def template_preview(request, name):
    template = get_object_or_404(DocumentTemplate, name=name)
    parsed_template = template.to_dict()
    return render(request, 'template_preview.html', {'template': parsed_template})

def pdf_view(request, document_id):
    document = get_object_or_404(Document, id=document_id)
    return generate_pdf(document)

def payment_page(request):
    email = request.GET.get("email")
    organization = get_object_or_404(Organization, email=email)
    document = get_object_or_404(Document, organization=organization)
    
    if request.method == "POST":
        pdf_url = f"{site_domain}/pdf/{document.id}/"
        send_document_email(email, pdf_url, document)  
        return redirect(pdf_url)
    
    return render(request, "payment.html", {"email": email})

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


def download_example_pdf(request):
    pdf_path = os.path.join(settings.BASE_DIR, 'backend/core/static/pdf/risklet_example_document.pdf')
    if not os.path.exists(pdf_path):
        raise Http404("File not found.")
    return FileResponse(open(pdf_path, 'rb'), as_attachment=True, filename='risklet_example_document.pdf')