import gradio as gr
import mysql.connector
from mysql.connector import Error

# Function to format fetched data into an HTML table
def format_data_as_table(data):
    if not data:
        return "<div style='color: red;'>No details found for the provided input.</div>"
    
    # Table style for formatting
    table_style = (
        "<style>"
        "table { width: 100%; border-collapse: collapse; }"
        "th, td { border: 1px solid #dddddd; padding: 8px; text-align: left; }"
        "th { background-color: #f2f2f2; }"
        "tr:nth-child(even) { background-color: #f9f9f9; }"
        "</style>"
    )
    
    # Create a table with headers
    headers = data[0].keys()
    table_html = table_style + "<table><tr>" + "".join([f"<th>{header}</th>" for header in headers]) + "</tr>"
    
    # Create rows for each record
    for record in data:
        row_html = "<tr>" + "".join([f"<td>{value}</td>" for value in record.values()]) + "</tr>"
        table_html += row_html
    
    table_html += "</table>"
    return table_html

# Main function to fetch data from MySQL based on PR Number or Status
def fetch_data(pr_number, status):
    connection = None
    try:
        connection = mysql.connector.connect(
            host='localhost',
            database='records',
            user='root',
            password='Nikki@1234'  # Use a secure password retrieval method here
        )

        if connection.is_connected():
            cursor = connection.cursor(dictionary=True)

            # Determine whether to use PR Number or Status (using the one that’s not empty)
            if pr_number and not status:
                # Fetch by PR Number
                cursor.execute("SELECT * FROM pr_details WHERE PR_Number = %s", (pr_number,))
            elif status and not pr_number:
                # Fetch by Status
                cursor.execute("SELECT * FROM pr_details WHERE Status = %s", (status,))
            elif pr_number and status:
                # If both fields are provided, return an error message
                return "<div style='color: red;'>Please provide either PR Number or Status, not both.</div>"
            else:
                return "<div style='color: red;'>Please provide a PR Number or select a Status.</div>"

            data = cursor.fetchall()

            # Use the table format function to render results
            return format_data_as_table(data)

    except Error as e:
        return f"<div style='color: red;'>Error: {e}</div>"
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL connection closed.")

# Gradio Interface with improvements
iface = gr.Interface(
    fn=fetch_data,
    inputs=[
        gr.Textbox(placeholder="Enter PR Number", label="PR Number"),
        gr.Radio(choices=['Submitted', 'Ordered', 'Composing'], label="Status", horizontal=True),
        gr.Button(value="Reset", style={"margin-left": "auto"}, variant="outline")  # Reset button
    ],
    outputs=gr.HTML(label="Details"),  # Output as HTML to allow for styling
    title="Purchase PO Automation Management System",
    live=False,  # Submit button is used instead of live updates
    theme="compact",
    allow_flagging="never",
    css=''' .gradio-container { font-family: Arial, sans-serif; }
           .gradio-row { align-items: center; }
           .gradio-button { margin: 0; } '''
)

# Function to reset the inputs
def reset_form():
    return "", "Submitted"  # Adjust the second return value according to your default status if necessary

# Adding the reset action to a button press
iface.add_component(
    value=reset_form,
    type="action",
    visible=True,
    component=iface.inputs[-1]  # The reset button is the last input item
)

# Launch the interface with remote access enabled
iface.launch(share=True)


getting below errors

(venv) PS E:\BITS> & e:/BITS/venv/Scripts/python.exe e:/BITS/test2.py
Traceback (most recent call last):
  File "e:\BITS\test2.py", line 77, in <module>
    gr.Radio(choices=['Submitted', 'Ordered', 'Composing'], label="Status", horizontal=True),
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\BITS\venv\Lib\site-packages\gradio\component_meta.py", line 155, in wrapper
    return fn(self, **kwargs)
           ^^^^^^^^^^^^^^^^^^
TypeError: Radio.__init__() got an unexpected keyword argument 'horizontal'
(venv) PS E:\BITS>