import re
import os
import gspread
import gradio as gr
import datetime
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from LLM_openai import client, expense_classifier
from utils import create_plot, create_barplot
from dataframe_processing import dataframe_process
from vision_api_call import process_image

#connect to the service account
gc = gspread.service_account(filename="credentials.json")
#connect to your sheet (between "" = the name of your G Sheet, keep it short)
spreadsheet = gc.open("Snackers_spreadsheet").sheet1

def update_spend_from_image(img):
    ##This processes the image
    extracted_dictionay_from_image=process_image(img)

    total_from_receipt=extracted_dictionay_from_image['total']
    concept_from_receipt=extracted_dictionay_from_image['purchase_summary']
    shop_type=extracted_dictionay_from_image['store_type']
    shop_name=extracted_dictionay_from_image['store']
    receipt_items=str(extracted_dictionay_from_image['items'])

    concept_and_shop=concept_from_receipt+" from "+shop_type+f" ({shop_name})"
    
    ##The function update_spend in the line below only takes a string and float
    category, day_month, todays_amount, current_week_amount , fig, fig2, fig3=update_spend(shop_name, total_from_receipt, concept_and_shop,receipt_items)

    return category, day_month, todays_amount, current_week_amount , fig, fig2, fig3



def update_spend(concept,ingreso_flag , amount, description ,items_from_receipt=None):
    category=expense_classifier(concept)
    today = datetime.date.today()
    if ingreso_flag:
        ingreso_o_egreso='ingreso'
    else:
        ingreso_o_egreso='egreso'
    # Append a new row
    spreadsheet.append_row([str(today), concept,ingreso_o_egreso,float(amount), description,category, items_from_receipt ])
    
    day_month, todays_amount, current_week_amount , fig, fig2, fig3=dataframe_process(spreadsheet)
    return category, day_month, todays_amount, current_week_amount , fig, fig2, fig3

def show_plots():
    category='N/A'
    today = 'N/A'
    
    # Append a new row
    # spreadsheet.append_row([str(today), concept,float(amount),category, items_from_receipt ])
    
    day_month, todays_amount, current_week_amount , fig, fig2, fig3=dataframe_process(spreadsheet)
    return category, day_month, todays_amount, current_week_amount , fig, fig2, fig3




with gr.Blocks() as demo:
    gr.Markdown("Tracker de gastos")
    
    with gr.Tab("Entrada manual"):
        with gr.Row():
            concept = gr.Textbox(label="Cliente o Proveedor")
        with gr.Row():
            ingreso_flag= gr.Checkbox(label="Ingreso", info="Es un ingreso? Marca la caja")
        with gr.Row():
            amount= gr.Textbox(label="Monto")
        with gr.Row():
            description= gr.Textbox(label="descripcion")
        btn_manual = gr.Button("Ingresar gasto")

    with gr.Tab("Cargar recibo"):
        with gr.Row():
            input_image = gr.Image( type="pil")
        btn_image = gr.Button("Ingresar gasto")
        
        
        
    
    
    with gr.Row():
        btn_show = gr.Button("Mostrar graficos")

    with gr.Row():
        expense_class= gr.Textbox(label='Clase de gasto')
        ui_date=gr.Textbox(label='Fecha')
        expenses_today= gr.Textbox(label='Gastos de hoy')
        expenses_this_week= gr.Textbox(label='Gastos esta semana')
    with gr.Row():
        daily_plot=gr.Plot(label=None)
        week_plot=gr.Plot()
        category_plot=gr.Plot()


    btn_manual.click(fn=update_spend, inputs=[concept, ingreso_flag,amount, description ], outputs=[expense_class,ui_date, expenses_today,expenses_this_week,
                                                                  daily_plot,week_plot,category_plot])

    btn_image.click(fn=update_spend_from_image, inputs=[input_image], outputs=[expense_class,ui_date, expenses_today,expenses_this_week,
                                                                  daily_plot,week_plot,category_plot])

    btn_show.click(fn=show_plots, inputs=[], outputs=[expense_class,ui_date, expenses_today,expenses_this_week,
                                                                  daily_plot,week_plot,category_plot])


demo.launch()