import customtkinter as ctk
from core import reporting # To potentially save reports as session data or separate logs
from tkinter import messagebox
import datetime
import os

class BugReportFrame(ctk.CTkFrame):
    def __init__(self, master, set_session_callback=None, heading_font=None, text_font=None):
        super().__init__(master)
        self.set_session_callback = set_session_callback # For consistency, though not directly used here
        self.heading_font = heading_font if heading_font else ctk.CTkFont(size=18, weight="bold")
        self.text_font = text_font if text_font else ctk.CTkFont(size=12)
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(5, weight=1) # Adjusted for description textbox

        title = ctk.CTkLabel(self, text="Reportar un Fallo o Sugerencia", font=self.heading_font)
        title.grid(row=0, column=0, padx=20, pady=(20, 10), sticky="ew")

        # ---- Input Fields ----
        input_frame = ctk.CTkFrame(self)
        input_frame.grid(row=1, column=0, padx=20, pady=10, sticky="ew")
        input_frame.grid_columnconfigure(0, weight=1)
        input_frame.grid_columnconfigure(1, weight=3)

        self.subject_label = ctk.CTkLabel(input_frame, text="Asunto:", font=self.text_font)
        self.subject_label.grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.subject_entry = ctk.CTkEntry(input_frame, placeholder_text="Breve descripción del fallo o sugerencia", font=self.text_font)
        self.subject_entry.grid(row=0, column=1, padx=5, pady=5, sticky="ew")

        self.contact_label = ctk.CTkLabel(input_frame, text="Contacto (Email/Usuario, opcional):", font=self.text_font)
        self.contact_label.grid(row=1, column=0, padx=5, pady=5, sticky="w")
        self.contact_entry = ctk.CTkEntry(input_frame, placeholder_text="ej: tu.email@example.com", font=self.text_font)
        self.contact_entry.grid(row=1, column=1, padx=5, pady=5, sticky="ew")

        self.description_label = ctk.CTkLabel(self, text="Descripción Detallada:", font=self.text_font)
        self.description_label.grid(row=2, column=0, padx=20, pady=(10, 5), sticky="w")
        self.description_textbox = ctk.CTkTextbox(self, height=200, font=self.text_font)
        self.description_textbox.grid(row=3, column=0, padx=20, pady=5, sticky="nsew")

        # ---- Submit Button ----
        self.submit_button = ctk.CTkButton(self, text="Enviar Reporte", command=self.submit_bug_report, font=self.text_font)
        self.submit_button.grid(row=4, column=0, padx=20, pady=(10, 20), sticky="ew")

    def submit_bug_report(self):
        subject = self.subject_entry.get()
        contact = self.contact_entry.get()
        description = self.description_textbox.get("1.0", "end-1c")

        if not subject or not description:
            messagebox.showerror("Error", "Por favor, completa el asunto y la descripción del reporte.")
            return

        report_content = f"--- Reporte de Fallo/Sugerencia ---\n"
        report_content += f"Fecha: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
        report_content += f"Asunto: {subject}\n"
        report_content += f"Contacto: {contact if contact else 'No especificado'}\n"
        report_content += f"Descripción:\n{description}\n"
        report_content += f"-----------------------------------\n"

        # Save to a file in the reports directory
        # Create a specific directory for bug reports within REPORTS_DIR
        bug_reports_dir = os.path.join(reporting.REPORTS_DIR, "bug_reports")
        os.makedirs(bug_reports_dir, exist_ok=True)

        report_filename = f"bug_report_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        report_filepath = os.path.join(bug_reports_dir, report_filename)

        try:
            with open(report_filepath, "w", encoding="utf-8") as f:
                f.write(report_content)
            messagebox.showinfo("Éxito", f"Reporte enviado y guardado en:\n{report_filepath}")
            # Clear the form
            self.subject_entry.delete(0, "end")
            self.contact_entry.delete(0, "end")
            self.description_textbox.delete("1.0", "end")
        except Exception as e:
            messagebox.showerror("Error", f"No se pudo guardar el reporte: {e}")
