from datetime import datetime
import streamlit as st
import datetime
import sqlite3
from googleapiclient.discovery import build
from google.oauth2 import service_account
from pandas.tseries.offsets import Week
import sys
import os
import CalendarView


user_name = os.environ.get("USER_NAME")
data_bench_path = os.environ.get("DATA_BENCH_PATH")
# path = os.path.abspath("DATA_BENCH_PATH")
# sys.path.append(path)


# Set up Google Calendar API credentials
SCOPES = ["https://www.googleapis.com/auth/calendar"]
SERVICE_ACCOUNT_FILE = "secrets/auto-scheduler-052723-7f0f9876eb57.json"


# Set up SQLite database connection
DATABASE_FILE = "data/tasks.db"
connection = sqlite3.connect(DATABASE_FILE)
cursor = connection.cursor()

# Initialize Google Calendar service
credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES
)
service = build("calendar", "v3", credentials=credentials)

# Set Franklin Covey "Classic" style
st.markdown(
    """
    <style>
    .franklin-covey {
        font-family: 'Times New Roman', Times, serif;
        font-size: 18px;
        line-height: 1.6;
        color: #333333;
    }
    </style>
    """,
    unsafe_allow_html=True,
)


# Function to get today's events from Google Calendar
def get_events():
    now = datetime.datetime.utcnow().isoformat() + "Z"  # 'Z' indicates UTC time
    end_of_week = (datetime.datetime.now() + Week()).isoformat() + "Z"
    events_result = (
        service.events()
        .list(
            calendarId="primary",
            timeMin=now,
            timeMax=end_of_week,
            singleEvents=True,
            orderBy="startTime",
        )
        .execute()
    )
    events = events_result.get("items", [])
    return events


# Function to fetch today's tasks from the SQLite database
def get_tasks():
    today = datetime.date.today().strftime("%Y-%m-%d")
    cursor.execute(
        "SELECT category, start_time, end_time FROM tasks WHERE date(created_at) = ? ORDER BY created_at DESC",
        (today,),
    )
    tasks = cursor.fetchall()
    return tasks


# Main app code
def main():
    st.title("My Day Planner")
    st.markdown("<hr class='franklin-covey'>", unsafe_allow_html=True)

    # Display today's date
    today = datetime.date.today().strftime("%A, %B %d, %Y")
    st.markdown(f"<p class='franklin-covey'>{today}</p>", unsafe_allow_html=True)

    # Display weekly calendar
    st.markdown(
        "<h2 class='franklin-covey'>Weekly Calendar</h2>", unsafe_allow_html=True
    )
    events = get_events()
    if not events:
        st.markdown(
            "<p class='franklin-covey'>No events this week</p>", unsafe_allow_html=True
        )
    else:
        st.markdown(
            "<p class='franklin-covey'>Select a date to view events:</p>",
            unsafe_allow_html=True,
        )
        selected_date = st.date_input("", value=datetime.date.today())
        selected_date = selected_date.strftime("%Y-%m-%d")
        selected_events = [
            event
            for event in events
            if event["start"]
            .get("dateTime", event["start"].get("date"))
            .startswith(selected_date)
        ]
        if not selected_events:
            st.markdown(
                "<p class='franklin-covey'>No events for the selected date</p>",
                unsafe_allow_html=True,
            )
        else:
            for event in selected_events:
                start_time = event["start"].get("dateTime", event["start"].get("date"))
                summary = event["summary"]
                start_time = datetime.datetime.fromisoformat(start_time).strftime(
                    "%I:%M %p"
                )
                st.markdown(
                    f"<p class='franklin-covey'><strong>{start_time}:</strong> {summary}</p>",
                    unsafe_allow_html=True,
                )

    # Display tasks
    st.markdown("<h2 class='franklin-covey'>Tasks</h2>", unsafe_allow_html=True)
    tasks = get_tasks()
    if not tasks:
        st.markdown(
            "<p class='franklin-covey'>No tasks for today</p>", unsafe_allow_html=True
        )
    else:
        for task in tasks:
            category, start_time, end_time = task
            st.markdown(
                f"<p class='franklin-covey'><strong>{start_time} - {end_time}:</strong> {category}</p>",
                unsafe_allow_html=True,
            )

    # Display appointment schedule
    st.markdown(
        "<h2 class='franklin-covey'>Appointment Schedule</h2>", unsafe_allow_html=True
    )
    st.markdown(
        "<p class='franklin-covey'>Time: 5:00 AM to 11:00 PM</p>",
        unsafe_allow_html=True,
    )
    st.markdown(
        "<p class='franklin-covey'>No appointments available</p>",
        unsafe_allow_html=True,
    )

    # Display calendar view
    st.markdown("<h2 class='franklin-covey'>Calendar View</h2>", unsafe_allow_html=True)
    calendar = CalendarView(months=1)
    calendar.add_events(events)
    st.write(calendar.render())


if __name__ == "__main__":
    main()