# -*- coding: utf-8 -*-
"""
Created on Sat May  2 17:47:39 2026

@author: MICAELA
"""

import tkinter as tk
from tkinter import ttk, messagebox
import serial
import serial.tools.list_ports

# --- Configuración de la Ventana ---
root = tk.Tk()
root.title("Micaela's Interface - ESP32 Control")
root.geometry("400x300")
root.configure(bg='#f0f0f0')

arduino = None

# --- Funciones de Control ---
def connect_board():
    global arduino
    port = port_selector.get()
    try:
        # Iniciamos la conexión serial
        arduino = serial.Serial(port, 9600, timeout=1)
        status_label.config(text=f"Status: Connected to {port}", foreground="green")
        messagebox.showinfo("Success", f"Connected to {port} successfully!")
    except Exception as e:
        status_label.config(text="Status: Connection Failed", foreground="red")
        messagebox.showerror("Error", f"Could not connect: {e}")

def send_signal(state):
    if arduino and arduino.is_open:
        arduino.write(state.encode())
        print(f"Signal sent: {state}")
    else:
        messagebox.showwarning("Warning", "Please connect to a port first!")

# --- Elementos de la Interfaz (UI) ---
style = ttk.Style()
style.configure("TButton", padding=6, font=('Helvetica', 10))

title_label = tk.Label(root, text="XIAO ESP32-C3 LED Control", font=('Helvetica', 14, 'bold'), bg='#f0f0f0')
title_label.pack(pady=15)

# Selector de Puertos
frame_port = tk.Frame(root, bg='#f0f0f0')
frame_port.pack(pady=10)

tk.Label(frame_port, text="Select Port:", bg='#f0f0f0').grid(row=0, column=0, padx=5)
available_ports = [p.device for p in serial.tools.list_ports.comports()]
port_selector = ttk.Combobox(frame_port, values=available_ports, width=15)
port_selector.grid(row=0, column=1, padx=5)
if available_ports: port_selector.current(0)

btn_connect = ttk.Button(frame_port, text="Connect", command=connect_board)
btn_connect.grid(row=0, column=2, padx=5)

# Botones de Acción
btn_frame = tk.Frame(root, bg='#f0f0f0')
btn_frame.pack(pady=20)

btn_on = tk.Button(btn_frame, text="TURN ON", bg="#4CAF50", fg="white", 
                   font=('Helvetica', 10, 'bold'), width=12, height=2,
                   command=lambda: send_signal('H'))
btn_on.grid(row=0, column=0, padx=10)

btn_off = tk.Button(btn_frame, text="TURN OFF", bg="#F44336", fg="white", 
                    font=('Helvetica', 10, 'bold'), width=12, height=2,
                    command=lambda: send_signal('L'))
btn_off.grid(row=0, column=1, padx=10)

# Etiqueta de Estado
status_label = ttk.Label(root, text="Status: Disconnected", font=('Helvetica', 9, 'italic'))
status_label.pack(side="bottom", pady=10)

root.mainloop()