import tkinter as tk
from tkinter import ttk, messagebox
from app.email.emailClient import EmailClient

class ReciveEmailTab:
    def __init__(self, notebook, panel_derecho):
        self.email_client = EmailClient()
        self.panel_derecho = panel_derecho  
        self.correos = []  
        
        self.tab = ttk.Frame(notebook)
        notebook.add(self.tab, text="📩 Recibir Correo")
        self.setup_ui()

    def setup_ui(self):
        frame_principal = tk.Frame(self.tab, bg="white", padx=10, pady=10)
        frame_principal.pack(fill="both", expand=True)

        # Botones de recibir y eliminar correos
        frame_botones = ttk.Frame(frame_principal)
        frame_botones.pack(fill="x", pady=5)

        tk.Button(
            frame_botones, text="🔄 Recibir Correos", font=("Helvetica", 11, "bold"), bg="blue", fg="white",
            command=self.obtener_correos_con_estado
        ).pack(side="left", padx=5)

        tk.Button(
            frame_botones, text="🗑️ Eliminar Correo", font=("Helvetica", 11, "bold"), bg="red", fg="white",
            command=self.eliminar_correo
        ).pack(side="right", padx=5)

        # Lista de correos
        self.tree = ttk.Treeview(frame_principal, columns=("Leído", "De", "Asunto", "Fecha"), show="headings")
        self.tree.heading("Leído", text="📌")
        self.tree.heading("De", text="De")
        self.tree.heading("Asunto", text="Asunto")
        self.tree.heading("Fecha", text="Fecha")
        self.tree.column("Leído", width=30, anchor="center")
        self.tree.bind("<Double-1>", self.abrir_correo)
        self.tree.pack(fill="both", expand=True)
        
    def obtener_correos_con_estado(self):
        email, password = self.panel_derecho.get_credentials()

        if not email or not password:
            messagebox.showerror("Error", "⚠️ Debes iniciar sesión primero.")
            return

        def actualizar_lista(correos):
            self.tree.delete(*self.tree.get_children())  # Limpiar la lista
            self.correos = correos  # Guardar la lista de correos

            for correo in correos:
                estado_icono = "✅" if correo["read"] else "🔴"
                self.tree.insert("", "end", values=(estado_icono, correo["from"], correo["subject"], correo["date"]))

        self.email_client.recibir_correos(email, password, actualizar_lista)


    def abrir_correo(self, event):
        email, password = self.panel_derecho.get_credentials()

        selected_item = self.tree.selection()
        if not selected_item:
            return

        index = self.tree.index(selected_item[0])
        correo = self.correos[index]

        def mostrar_correo(datos):
            ventana = tk.Toplevel()
            ventana.title("📩 Detalle del Correo")
            ventana.geometry("500x400")

            tk.Label(ventana, text=f"De: {datos['from']}", font=("Helvetica", 11, "bold")).pack(pady=5)
            tk.Label(ventana, text=f"Asunto: {datos['subject']}", font=("Helvetica", 11, "bold")).pack(pady=5)
            tk.Label(ventana, text=f"Fecha: {datos['date']}", font=("Helvetica", 10)).pack(pady=5)

            text_area = tk.Text(ventana, wrap="word", font=("Helvetica", 11))
            text_area.insert("1.0", datos["body"])
            text_area.pack(expand=True, fill="both", padx=10, pady=10)

            # Actualizar el icono en la lista de correos
            self.tree.item(selected_item[0], values=("✅", correo["from"], correo["subject"], correo["date"]))

        self.email_client.obtener_contenido_correo(email, password, correo["id"], mostrar_correo)

    def eliminar_correo(self):
        email, password = self.panel_derecho.get_credentials()

        selected_item = self.tree.selection()
        if not selected_item:
            messagebox.showwarning("Aviso", "⚠️ Selecciona un correo para eliminar.")
            return

        index = self.tree.index(selected_item[0])
        correo = self.correos[index]

        def confirmar_eliminacion():
            self.email_client.eliminar_correo(email, password, correo["id"])
            self.tree.delete(selected_item[0])  # Eliminar de la lista

        respuesta = messagebox.askyesno("Eliminar Correo", "¿Estás seguro de que deseas eliminar este correo?")
        if respuesta:
            confirmar_eliminacion()
