import gradio as gr
import datetime
import json
import os
import calendar
from pathlib import Path
import plotly.graph_objects as go
import plotly.express as px
import numpy as np

# Create data directory if it doesn't exist
DATA_DIR = Path("daily_data")
try:
    DATA_DIR.mkdir(parents=True, exist_ok=True)
except Exception as e:
    print(f"Error creating data directory: {e}")

JOURNAL_QUESTIONS = [
    "What made you happiest today, and why?",
    "What was the biggest challenge you faced today, and how did you approach it?",
    "What's one thing you learned or realized today?",
    "What are you grateful for today?",
    "What emotion did you feel the most today? What triggered it?",
    "What's one moment or interaction that stood out to you?",
    "What progress did you make toward your goals today?",
    "Did you notice any recurring habits or patterns in your day?",
    "How did you support or connect with someone today?",
    "What could you have done differently to improve your day?",
    "What's one thing you want to prioritize or focus on tomorrow?",
    "If today were a chapter in your life story, what would its title be?"
]

def get_date_key():
    """Get current date in YYYY-MM-DD format"""
    return datetime.datetime.now().strftime("%Y-%m-%d")

def save_daily_data(data, date_key=None):
    """Save daily data to JSON file"""
    if date_key is None:
        date_key = get_date_key()
    
    # Ensure data is a dictionary
    if not isinstance(data, dict):
        data = create_empty_daily_data()
    
    # Convert DataFrame to list for JSON serialization
    if "focus" in data:
        if "priorities" in data["focus"]:
            priorities = data["focus"]["priorities"]
            if hasattr(priorities, '__array__') or hasattr(priorities, 'values'):
                data["focus"]["priorities"] = priorities.values.tolist() if hasattr(priorities, 'values') else priorities.tolist()
        if "later" in data["focus"]:
            later = data["focus"]["later"]
            if hasattr(later, '__array__') or hasattr(later, 'values'):
                data["focus"]["later"] = later.values.tolist() if hasattr(later, 'values') else later.tolist()
    
    # Deep merge required fields with existing data
    required_fields = {
        "tracking_metrics": {
            "productivity": 0,
            "energy": 0,
            "mood": 0,
            "sleep_quality": 0,
            "exercise_intensity": 0
        },
        "habits": {},
        "focus": {
            "priorities": [],
            "later": [],
            "priority_reward": "",
            "later_reward": ""
        },
        "meals": {
            "breakfast": "",
            "lunch": "",
            "dinner": "",
            "snacks": ""
        },
        "last_updated": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    
    for key, default_value in required_fields.items():
        if key not in data:
            data[key] = default_value
        elif isinstance(default_value, dict):
            for subkey, subvalue in default_value.items():
                if subkey not in data[key]:
                    data[key][subkey] = subvalue
    
    file_path = DATA_DIR / f"{date_key}.json"
    
    try:
        # Ensure the directory exists again (in case it was deleted)
        DATA_DIR.mkdir(parents=True, exist_ok=True)
        
        # Write directly to the file first
        with open(file_path, 'w') as f:
            json.dump(data, f, indent=2, sort_keys=True)
            
    except Exception as e:
        print(f"Error saving data: {e}")
        try:
            # Fallback: try to save in the current directory
            with open(f"{date_key}.json", 'w') as f:
                json.dump(data, f, indent=2, sort_keys=True)
            print(f"Saved data to current directory as fallback")
        except Exception as e2:
            print(f"Final save attempt failed: {e2}")

def clean_daily_data_file(date_key):
    """Clean up corrupted JSON file and restore it with valid data"""
    file_path = DATA_DIR / f"{date_key}.json"
    try:
        if file_path.exists():
            with open(file_path, 'r') as f:
                content = f.read().strip()
            
            try:
                # Try to parse the content directly first
                data = json.loads(content)
                return validate_data_structure(data)
            except json.JSONDecodeError:
                # If that fails, try to clean the content
                content = content.rstrip(', \t\n\r')
                last_brace = content.rfind('}')
                if last_brace != -1:
                    content = content[:last_brace + 1]
                    try:
                        data = json.loads(content)
                        data = validate_data_structure(data)
                        # Save the cleaned data
                        save_daily_data(data, date_key)
                        return data
                    except:
                        pass
        
        # If all cleaning attempts fail, create new data
        print(f"Creating new data for {date_key}")
        data = create_empty_daily_data()
        save_daily_data(data, date_key)
        return data
        
    except Exception as e:
        print(f"Error cleaning data file {date_key}: {e}")
        return create_empty_daily_data()

def load_daily_data(date_key=None):
    """Load daily data from JSON file"""
    if date_key is None:
        date_key = get_date_key()
    
    file_path = DATA_DIR / f"{date_key}.json"
    try:
        if file_path.exists():
            try:
                # Try to load and clean the file
                data = clean_json_file(file_path)
                
                # Validate and update the data structure
                data = validate_data_structure(data)
                save_daily_data(data, date_key)
                return data
            except Exception as e:
                print(f"Error loading data: {e}")
                return create_empty_daily_data()
        else:
            # Only create new file if it's today's date
            if date_key == get_date_key():
                data = create_empty_daily_data()
                save_daily_data(data, date_key)
                return data
            else:
                return create_empty_daily_data()
    except Exception as e:
        print(f"Error loading data: {e}")
        return create_empty_daily_data()

def validate_data_structure(data):
    """Validate and update data structure if needed"""
    if not isinstance(data, dict):
        return create_empty_daily_data()
    
    # Create a new data structure with all required fields
    valid_data = create_empty_daily_data()
    
    # Copy existing data while ensuring all required fields exist
    for key, default_value in valid_data.items():
        if key in data:
            if isinstance(default_value, dict):
                valid_data[key] = {**default_value, **data[key]}
            else:
                valid_data[key] = data[key]
    
    return valid_data

def create_empty_daily_data():
    """Create empty data structure for a new day"""
    # Load current habits list
    current_habits = load_habits()
    
    data = {
        "habits": {habit: [False] * 7 for habit in current_habits},
        "focus": {
            "priorities": [
                ["", ""],  # Empty task and status
                ["", ""],
                ["", ""],
                ["", ""],
                ["", ""]
            ],
            "later": [
                ["", ""],  # Empty task and status
                ["", ""],
                ["", ""],
                ["", ""],
                ["", ""]
            ],
            "priority_reward": "",
            "later_reward": ""
        },
        "meals": {
            "breakfast": "",
            "lunch": "",
            "dinner": "",
            "snacks": ""
        },
        "last_updated": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "tracking_metrics": {
            "productivity": 0,
            "energy": 0,
            "mood": 0,
            "sleep_quality": 0,
            "exercise_intensity": 0
        }
    }
    
    # Add journal section with empty entries
    data["journal"] = {
        question: "" for question in JOURNAL_QUESTIONS
    }
    
    return data

def get_week_dates():
    """Get dates for current week"""
    today = datetime.date.today()
    monday = today - datetime.timedelta(days=today.weekday())
    return [(monday + datetime.timedelta(days=i)).strftime("%Y-%m-%d") for i in range(7)]

def get_month_dates():
    """Get dates for current month"""
    today = datetime.date.today()
    _, num_days = calendar.monthrange(today.year, today.month)
    return [(datetime.date(today.year, today.month, day)).strftime("%Y-%m-%d") 
            for day in range(1, num_days + 1)]

def load_week_data():
    """Load data for the current week"""
    week_data = {}
    week_dates = get_week_dates()
    
    for date in week_dates:
        file_path = DATA_DIR / f"{date}.json"
        if file_path.exists():
            try:
                data = load_daily_data(date)
                week_data[date] = data
            except Exception as e:
                print(f"Error loading week data for {date}: {e}")
                week_data[date] = create_empty_daily_data()
        else:
            # Don't create a file, just return empty data structure
            week_data[date] = {
                "tracking_metrics": {
                    "productivity": 0,
                    "energy": 0,
                    "mood": 0,
                    "sleep_quality": 0,
                    "exercise_intensity": 0
                }
            }
    return week_data

def load_month_data():
    """Load data for the current month"""
    month_data = {}
    month_dates = get_month_dates()
    
    for date in month_dates:
        file_path = DATA_DIR / f"{date}.json"
        if file_path.exists():
            try:
                data = load_daily_data(date)
                month_data[date] = data
            except Exception as e:
                print(f"Error loading month data for {date}: {e}")
                month_data[date] = create_empty_daily_data()
        else:
            # Don't create a file, just return empty data structure
            month_data[date] = {
                "tracking_metrics": {
                    "productivity": 0,
                    "energy": 0,
                    "mood": 0,
                    "sleep_quality": 0,
                    "exercise_intensity": 0
                }
            }
    return month_data

def calculate_success_rate(data_dict, metric):
    """Calculate success rate for a given metric"""
    if not data_dict:
        return 0
    total = 0
    count = 0
    for date, data in data_dict.items():
        # Ensure tracking_metrics exists for each data point
        if "tracking_metrics" not in data:
            data["tracking_metrics"] = {
                "productivity": 0,
                "energy": 0,
                "mood": 0,
                "sleep_quality": 0,
                "exercise_intensity": 0
            }
        if metric in data.get("tracking_metrics", {}):
            total += data["tracking_metrics"][metric]
            count += 1
    return round((total / count) if count > 0 else 0, 2)

# Replace the hardcoded HABITS list with a function to load habits
def get_default_habits():
    """Get the default habits list if no custom list exists"""
    return [
        # Morning Routine (Essential)
        "Morning Exercise/Yoga",
        "Meditation (20min)",

        
        # After Work Activities
        "Evening Stretch (20min)",
        "Active Learning (20min)",
        "Journal",

        
        # Flexible Throughout Day
        "Reading (20min)",
        "Take a photo",
        "Future Planning"
    ]

def load_habits():
    """Load the current habits list from the configuration"""
    config_path = Path("habits_config.json")
    if config_path.exists():
        try:
            with open(config_path, 'r') as f:
                data = json.load(f)
                if "habits" in data and isinstance(data["habits"], list):
                    return data["habits"]
                else:
                    # If the file exists but is invalid, create a new one with defaults
                    default_habits = get_default_habits()
                    save_habits(default_habits)
                    return default_habits
        except Exception as e:
            print(f"Error loading habits: {e}")
            # If there's an error reading the file, create a new one with defaults
            default_habits = get_default_habits()
            save_habits(default_habits)
            return default_habits
    else:
        # If the file doesn't exist, create it with defaults
        default_habits = get_default_habits()
        save_habits(default_habits)
        return default_habits

def save_habits(habits_list):
    """Save the current habits list to configuration"""
    config_path = Path("habits_config.json")
    try:
        # Ensure the list is unique and sorted
        habits_list = sorted(list(set(habits_list)))
        
        # Save to config file
        with open(config_path, 'w') as f:
            json.dump({"habits": habits_list}, f, indent=2)
        
        # Also update the current day's data to match
        current_data = load_daily_data()
        new_habits = {habit: [False] * 7 for habit in habits_list}
        
        # Preserve existing habit states
        for habit, states in current_data["habits"].items():
            if habit in new_habits:
                new_habits[habit] = states
        
        current_data["habits"] = new_habits
        save_daily_data(current_data)
        
    except Exception as e:
        print(f"Error saving habits: {e}")

# Remove redundant constants
DEFAULT_SELF_CARE_ITEMS = [
 "Yoga (AM)", "Vitamins", "Outside",
    "Stretch (PM)", "Reading", "Learning", "Journal",
    "Tapping", "Meditate", "Brain Train"
]

def parse_time(time_str):
    """Parse time string in either 12-hour or 24-hour format"""
    try:
        # Try 24-hour format first
        return datetime.datetime.strptime(time_str, "%H:%M").strftime("%H:%M")
    except ValueError:
        try:
            # Try 12-hour format with AM/PM
            return datetime.datetime.strptime(time_str.strip().upper(), "%I:%M %p").strftime("%H:%M")
        except ValueError:
            try:
                # Try 12-hour format without space before AM/PM
                return datetime.datetime.strptime(time_str.strip().upper(), "%I:%M%p").strftime("%H:%M")
            except ValueError:
                return "00:00"  # Default if parsing fails

def calculate_age_stats(birth_date_str, birth_time_str="00:00"):
    """Calculate age-related statistics with precise birth date and time"""
    try:
        # Parse birth date and time
        try:
            birth_time = parse_time(birth_time_str)
        except ValueError:
            return {"Error": "Invalid time format. Please use either HH:MM (24-hour) or HH:MM AM/PM (12-hour)"}
        
        birth_datetime = datetime.datetime.strptime(f"{birth_date_str} {birth_time}", "%Y-%m-%d %H:%M")
        now = datetime.datetime.now()
        
        # Calculate time differences
        time_lived = now - birth_datetime
        age_days = time_lived.days
        age_hours = time_lived.total_seconds() / 3600
        age_minutes = time_lived.total_seconds() / 60
        age_weeks = age_days / 7
        age_months = age_days / 30.44
        age_years = age_days / 365.25
        
        # Calculate time until milestones
        days_until_90 = (datetime.datetime(birth_datetime.year + 90, birth_datetime.month, birth_datetime.day) - now).days
        weeks_until_90 = days_until_90 / 7
        months_until_90 = days_until_90 / 30.44
        years_until_90 = days_until_90 / 365.25
        
        # Calculate percentages and milestones
        percent_lived = (age_years / 90) * 100
        percent_of_year = (now.timetuple().tm_yday / 365.25) * 100
        percent_of_month = (now.day / calendar.monthrange(now.year, now.month)[1]) * 100
        percent_of_week = ((now.weekday() + 1) / 7) * 100
        percent_of_day = ((now.hour * 3600 + now.minute * 60 + now.second) / 86400) * 100
        
        # Calculate next birthday
        next_birthday = datetime.datetime(now.year, birth_datetime.month, birth_datetime.day)
        if next_birthday < now:
            next_birthday = datetime.datetime(now.year + 1, birth_datetime.month, birth_datetime.day)
        days_to_birthday = (next_birthday - now).days
        
        return {
            "Current Age": {
                "Years": f"{age_years:.2f}",
                "Months": f"{age_months:.1f}",
                "Weeks": f"{age_weeks:.1f}",
                "Days": str(age_days),
                "Hours": f"{age_hours:,.0f}",
                "Minutes": f"{age_minutes:,.0f}"
            },
            "Time Until 90": {
                "Years": f"{years_until_90:.1f}",
                "Months": f"{months_until_90:.1f}",
                "Weeks": f"{weeks_until_90:.1f}",
                "Days": str(days_until_90)
            },
            "Life Progress": {
                "Life Percentage": f"{percent_lived:.1f}%",
                "Current Year": f"{percent_of_year:.1f}%",
                "Current Month": f"{percent_of_month:.1f}%",
                "Current Week": f"{percent_of_week:.1f}%",
                "Current Day": f"{percent_of_day:.1f}%"
            },
            "Milestones": {
                "Days to Next Birthday": str(days_to_birthday),
                "Weeks Lived": f"{age_weeks:,.0f}",
                "Days Lived": f"{age_days:,d}",
                "Hours Lived": f"{age_hours:,.0f}",
                "10,000 Days": f"{10000 - (age_days % 10000)} days until next 10k milestone",
                "Life Seasons": f"You are in season {int(age_years/20) + 1} of your life"
            }
        }
    except ValueError as e:
        return {"Error": f"Invalid date or time format. Please use YYYY-MM-DD for date and HH:MM (24-hour) or HH:MM AM/PM (12-hour) for time."}

def update_progress(checkboxes):
    """Calculate progress percentage"""
    completed = sum(1 for x in checkboxes if x)
    total = len(checkboxes)
    return f"{(completed/total)*100:.1f}%" if total > 0 else "0%"

def check_and_refresh_day(current_data):
    """Check if we need to start a new day"""
    # Ensure tracking_metrics exists
    if "tracking_metrics" not in current_data:
        current_data["tracking_metrics"] = {
            "productivity": 0,
            "energy": 0,
            "mood": 0,
            "sleep_quality": 0,
            "exercise_intensity": 0
        }
    
    last_updated = datetime.datetime.strptime(current_data["last_updated"], "%Y-%m-%d %H:%M:%S")
    current_time = datetime.datetime.now()
    
    # If it's a new day (past midnight)
    if last_updated.date() < current_time.date():
        # Save current data with previous date
        previous_date = last_updated.strftime("%Y-%m-%d")
        save_daily_data(current_data, previous_date)
        
        # Create new empty data for today
        current_data = create_empty_daily_data()
        save_daily_data(current_data)
    
    # Always return the current data
    return current_data

def update_data(data_key, value):
    """Update specific data in the daily record"""
    current_data = load_daily_data()
    current_data = check_and_refresh_day(current_data)
    
    # Convert value to list only if it's a DataFrame or numpy array and not a dict
    if not isinstance(value, dict) and (hasattr(value, '__array__') or hasattr(value, 'values')):
        value = value.values.tolist() if hasattr(value, 'values') else value.tolist()
    
    # Update the specified data
    keys = data_key.split('.')
    target = current_data
    
    # Special handling for habits which are stored as lists
    if keys[0] == "habits" and len(keys) == 3:
        habit_name = keys[1]
        day_index = int(keys[2])  # Convert string index to integer
        if habit_name in target["habits"]:
            target["habits"][habit_name][day_index] = value
    else:
        # Normal dictionary path traversal
        for key in keys[:-1]:
            target = target[key]
        target[keys[-1]] = value
    
    current_data["last_updated"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    save_daily_data(current_data)
    return current_data

def update_activity(new_name, old_name):
    """Update a self-care activity name and maintain its status"""
    if not new_name.strip() or new_name == old_name:
        return gr.update()
    
    try:
        current_data = load_daily_data()
        
        # Ensure proper data structure
        if "self_care" not in current_data or not isinstance(current_data["self_care"], dict):
            current_data["self_care"] = {
                "items": DEFAULT_SELF_CARE_ITEMS.copy(),
                "status": {item: "Not Done" for item in DEFAULT_SELF_CARE_ITEMS}
            }
        if "items" not in current_data["self_care"]:
            current_data["self_care"]["items"] = list(current_data["self_care"].keys())
            current_data["self_care"]["status"] = current_data["self_care"].copy()
        
        # Update activity in items list
        if old_name in current_data["self_care"]["items"]:
            idx = current_data["self_care"]["items"].index(old_name)
            current_data["self_care"]["items"][idx] = new_name.strip()
            
            # Update status
            if "status" in current_data["self_care"]:
                if old_name in current_data["self_care"]["status"]:
                    current_data["self_care"]["status"][new_name.strip()] = current_data["self_care"]["status"].pop(old_name)
        
        save_daily_data(current_data)
        return gr.update()
    except Exception as e:
        print(f"Error updating activity: {e}")
        return gr.update()

def create_life_visualizations(stats):
    figures = {}
    
    # 1. Life Progress Donut Chart
    progress_data = {k: float(v.strip('%')) for k, v in stats["Life Progress"].items()}
    fig_progress = go.Figure(data=[go.Pie(
        labels=list(progress_data.keys()),
        values=list(progress_data.values()),
        hole=.3,
        marker_colors=px.colors.qualitative.Set3
    )])
    fig_progress.update_layout(title="Life Progress Metrics")
    figures["progress"] = fig_progress
    
    # 2. Time Remaining Bar Chart
    time_until = {k: float(v) for k, v in stats["Time Until 90"].items()}
    fig_remaining = go.Figure(data=[go.Bar(
        x=list(time_until.keys()),
        y=list(time_until.values()),
        marker_color='lightblue'
    )])
    fig_remaining.update_layout(title="Time Until 90")
    figures["remaining"] = fig_remaining
    
    # 3. Life Timeline
    current_year = float(stats["Current Age"]["Years"])
    fig_timeline = go.Figure()
    
    # Add seasons
    seasons = [
        {"name": "Learning & Discovery", "start": 0, "end": 20, "color": "lightgreen"},
        {"name": "Creation & Building", "start": 20, "end": 40, "color": "lightblue"},
        {"name": "Mastery & Leadership", "start": 40, "end": 60, "color": "lightyellow"},
        {"name": "Wisdom & Guidance", "start": 60, "end": 80, "color": "lightpink"},
        {"name": "Legacy & Reflection", "start": 80, "end": 90, "color": "lavender"}
    ]
    
    for season in seasons:
        fig_timeline.add_shape(
            type="rect",
            x0=season["start"],
            x1=season["end"],
            y0=0,
            y1=1,
            fillcolor=season["color"],
            opacity=0.3,
            layer="below",
            line_width=0,
        )
    
    # Add current age marker
    fig_timeline.add_trace(go.Scatter(
        x=[current_year, current_year],
        y=[0, 1],
        mode="lines",
        line=dict(color="red", width=2),
        name="Current Age"
    ))
    
    fig_timeline.update_layout(
        title="Life Seasons Timeline",
        xaxis_title="Age",
        yaxis_showticklabels=False,
        showlegend=True
    )
    figures["timeline"] = fig_timeline
    
    return figures

def update_metrics(prod, en, m, slp, ex, selected_date=None):
    """Update tracking metrics and return updated weekly grid"""
    if selected_date is None:
        selected_date = get_date_key()
    
    # Load data for the selected date
    current_data = load_daily_data(selected_date)
    
    # Update the metrics
    current_data["tracking_metrics"] = {
        "productivity": prod,
        "energy": en,
        "mood": m,
        "sleep_quality": slp,
        "exercise_intensity": ex
    }
    
    # Save the updated data
    save_daily_data(current_data, selected_date)
    
    # Reload week data to get updated grid
    week_data = load_week_data()
    
    # Create updated weekly grid values
    week_dates = get_week_dates()
    grid_values = [
        ["Productivity"] + [week_data[date]["tracking_metrics"]["productivity"] for date in week_dates],
        ["Energy"] + [week_data[date]["tracking_metrics"]["energy"] for date in week_dates],
        ["Mood"] + [week_data[date]["tracking_metrics"]["mood"] for date in week_dates],
        ["Sleep"] + [week_data[date]["tracking_metrics"]["sleep_quality"] for date in week_dates],
        ["Exercise"] + [week_data[date]["tracking_metrics"]["exercise_intensity"] for date in week_dates]
    ]
    
    # Calculate monthly averages
    month_data = load_month_data()
    avg_prod = calculate_success_rate(month_data, "productivity")
    avg_energy = calculate_success_rate(month_data, "energy")
    avg_mood = calculate_success_rate(month_data, "mood")
    avg_sleep = calculate_success_rate(month_data, "sleep_quality")
    avg_exercise = calculate_success_rate(month_data, "exercise_intensity")
    
    return [
        grid_values,  # Weekly grid values
        f"Average Productivity: {avg_prod}/5",
        f"Average Energy: {avg_energy}/5",
        f"Average Mood: {avg_mood}/5",
        f"Average Sleep: {avg_sleep}/5",
        f"Average Exercise: {avg_exercise}/5"
    ]

def update_journal_entry(question, answer):
    """Update a specific journal entry"""
    current_data = load_daily_data()
    
    # Ensure journal section exists
    if "journal" not in current_data:
        current_data["journal"] = {q: "" for q in JOURNAL_QUESTIONS}
    
    # Update the specific question's answer
    current_data["journal"][question] = answer
    
    # Save the updated data
    save_daily_data(current_data)
    return current_data

# Add this function to format the stats display
def create_stats_display(stats):
    # Current Age Section
    current_age = f"""
    ### 🎂 Current Age
    - **Years:** {stats["Current Age"]["Years"]} years
    - **Months:** {stats["Current Age"]["Months"]} months
    - **Weeks:** {stats["Current Age"]["Weeks"]} weeks
    - **Days:** {stats["Current Age"]["Days"]} days
    
    ⏰ You've been alive for:
    - **{stats["Current Age"]["Hours"]}** hours
    - **{stats["Current Age"]["Minutes"]}** minutes
    """
    
    # Time Until 90 Section
    time_remaining = f"""
    ### ⏳ Time Until 90
    - **Years:** {stats["Time Until 90"]["Years"]} years
    - **Months:** {stats["Time Until 90"]["Months"]} months
    - **Weeks:** {stats["Time Until 90"]["Weeks"]} weeks
    - **Days:** {stats["Time Until 90"]["Days"]} days
    """
    
    # Progress Section
    progress = f"""
    ### 📊 Life Progress
    - **Life Journey:** {stats["Life Progress"]["Life Percentage"]} complete
    - **This Year:** {stats["Life Progress"]["Current Year"]} complete
    - **This Month:** {stats["Life Progress"]["Current Month"]} complete
    - **This Week:** {stats["Life Progress"]["Current Week"]} complete
    - **Today:** {stats["Life Progress"]["Current Day"]} complete
    """
    
    # Milestones Section
    milestones = f"""
    ### 🏆 Key Milestones
    - **Next Birthday:** {stats["Milestones"]["Days to Next Birthday"]} days away
    - **Weeks Journey:** {stats["Milestones"]["Weeks Lived"]} weeks lived
    - **Days Journey:** {stats["Milestones"]["Days Lived"]} days experienced
    - **Hours Journey:** {stats["Milestones"]["Hours Lived"]} hours lived
    - **10k Milestone:** {stats["Milestones"]["10,000 Days"]}
    - **Life Season:** {stats["Milestones"]["Life Seasons"]}
    """
    
    return current_age, time_remaining, progress, milestones

# Add this function to format daily data for display
def format_daily_summary(date, data):
    """Format daily data into a summary row for the history table"""
    try:
        metrics = data.get("tracking_metrics", {})
        habits_completed = sum(1 for habit in data.get("habits", {}).values() 
                             for done in habit if done)
        total_habits = len(data.get("habits", {})) * 7
        habits_percent = f"{(habits_completed/total_habits)*100:.1f}%" if total_habits > 0 else "0%"
        
        journal_entries = sum(1 for entry in data.get("journal", {}).values() if entry.strip())
        
        # Format date for display
        display_date = datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%Y-%m-%d (%a)")
        
        return [
            display_date,
            metrics.get("productivity", 0),
            metrics.get("energy", 0),
            metrics.get("mood", 0),
            metrics.get("sleep_quality", 0),
            metrics.get("exercise_intensity", 0),
            habits_percent,
            journal_entries
        ]
    except Exception as e:
        print(f"Error formatting data for {date}: {e}")
        return [date, 0, 0, 0, 0, 0, "0%", 0]

# Add this function to load history data
def load_history_data():
    """Load all available daily data files"""
    history_data = []
    
    # Get all JSON files in the data directory
    json_files = sorted(DATA_DIR.glob("*.json"), reverse=True)  # Sort newest first
    
    for file_path in json_files:
        date = file_path.stem  # Get date from filename
        try:
            with open(file_path, 'r') as f:
                data = json.load(f)
                # Format the data for display
                history_data.append(format_daily_summary(date, data))
        except Exception as e:
            print(f"Error loading {file_path}: {e}")
    
    return history_data

def save_user_config(birth_date, birth_time):
    """Save user configuration data"""
    try:
        # Validate date format
        datetime.datetime.strptime(birth_date, "%Y-%m-%d")
        
        # Convert time to 24-hour format
        formatted_time = parse_time(birth_time)
        
        config = {
            "birth_date": birth_date,
            "birth_time": formatted_time
        }
        
        config_path = Path("user_config.json")
        with open(config_path, "w") as f:
            json.dump(config, f, indent=2)
        
        return True
    except Exception as e:
        print(f"Error saving config: {e}")
        return False

def load_user_config():
    """Load user configuration data"""
    config_path = Path("user_config.json")
    default_config = {
        "birth_date": "",  # Your birth date
        "birth_time": ""        # Your birth time in 24-hour format
    }
    
    if config_path.exists():
        try:
            with open(config_path, "r") as f:
                config = json.load(f)
                # Validate loaded data
                datetime.datetime.strptime(config["birth_date"], "%Y-%m-%d")
                parse_time(config["birth_time"])
                return config
        except Exception as e:
            print(f"Error loading config: {e}")
    
    return default_config

def add_new_habit(habit_name, duration, category):
    """Add a new habit to the tracking system"""
    try:
        if not habit_name.strip():
            return "⚠️ Please enter a habit name", None, None, None
        
        # Format the habit name with duration if provided
        formatted_habit = habit_name.strip()
        if duration:
            formatted_habit = f"{formatted_habit} ({duration})"
        
        # Add category prefix for sorting
        if category == "Morning":
            formatted_habit = f"Morning {formatted_habit}"
        elif category == "Evening":
            formatted_habit = f"Evening {formatted_habit}"
        
        # Load current habits
        current_habits = load_habits()
        
        # Check if habit already exists
        if formatted_habit in current_habits:
            return "⚠️ This habit already exists", None, None, None
        
        # Add new habit to list
        current_habits.append(formatted_habit)
        
        # Save updated habits list
        save_habits(current_habits)
        
        # Return success message and clear inputs
        return "✅ Habit added successfully!", "", "", ""
        
    except Exception as e:
        print(f"Error adding habit: {e}")
        return f"❌ Error adding habit: {str(e)}", None, None, None

def create_habit_section():
    """Create the habit tracking section with better layout"""
    # Load current habits
    current_habits = load_habits()
    
    # Group habits by time of day
    morning_habits = [h for h in current_habits if any(x in h.lower() for x in ["wake", "morning", "meditation", "brain", "walk"])]
    evening_habits = [h for h in current_habits if any(x in h.lower() for x in ["evening", "massage", "learning", "journal", "guitar"])]
    flexible_habits = [h for h in current_habits if h not in morning_habits + evening_habits]
    
    with gr.Column(scale=1):
        gr.Markdown("### 📅 Daily Habits & Tasks")
        
        # Create summary text component first
        with gr.Row():
            gr.Markdown("### 📊 Weekly Summary")
            summary_text = gr.Markdown()
            refresh_btn = gr.Button("🔄 Refresh")
        
        # Add status message component
        status_message = gr.Markdown(visible=False)
        
        # Connect refresh button to update summary
        refresh_btn.click(
            fn=update_summary,
            outputs=summary_text
        )
        
        # Add column headers once at the top
        with gr.Row(equal_height=True, variant="compact"):
            with gr.Column(scale=6):
                gr.Markdown("Task")
            with gr.Column(scale=7):
                with gr.Row(equal_height=True, variant="compact"):
                    days = ["M", "T", "W", "Th", "F", "S", "Su"]
                    for day in days:
                        with gr.Column(scale=1, min_width=35):
                            gr.Markdown(day)
            with gr.Column(scale=3):
                gr.Markdown("Progress")
        
        # Morning Section
        with gr.Group():
            gr.Markdown("#### 🌅 Morning Routine")
            create_habit_group(morning_habits, summary_text)
        
        gr.Markdown("---")
        
        # Evening Section
        with gr.Group():
            gr.Markdown("#### 🌙 Evening Activities")
            create_habit_group(evening_habits, summary_text)
            
        gr.Markdown("---")
        
        # Flexible Section
        with gr.Group():
            gr.Markdown("#### ⭐ Flexible Activities")
            create_habit_group(flexible_habits, summary_text)
        
        gr.Markdown("---")
        
        # Add new habit section
        with gr.Row(equal_height=True):
            new_habit = gr.Textbox(
                label="New Habit/Task",
                placeholder="Enter a new habit or task to track",
                scale=3,
                min_width=200
            )
            category = gr.Dropdown(
                choices=["Morning", "Evening", "Flexible"],
                label="Category",
                value="Flexible",
                scale=2,
                min_width=100
            )
            duration = gr.Dropdown(
                choices=["", "15min", "20min", "30min", "45min", "60min"],
                label="Duration",
                scale=2,
                min_width=100
            )
            add_btn = gr.Button("Add Habit", scale=1, min_width=100)
        
        # Add status message component
        status_message = gr.Markdown(visible=False)
        
        def add_and_refresh(habit_name, category, duration):
            message, _, _, _ = add_new_habit(habit_name, duration, category)
            
            # Reload habits and recreate sections
            current_habits = load_habits()
            morning_habits = [h for h in current_habits if any(x in h.lower() for x in ["wake", "morning", "meditation", "brain", "walk"])]
            evening_habits = [h for h in current_habits if any(x in h.lower() for x in ["evening", "massage", "learning", "journal", "guitar"])]
            flexible_habits = [h for h in current_habits if h not in morning_habits + evening_habits]
            
            # Update summary
            summary = update_summary()
            
            # Create updated habit groups
            create_habit_group(morning_habits, summary_text)
            create_habit_group(evening_habits, summary_text)
            create_habit_group(flexible_habits, summary_text)
            
            return [
                message,                    # Status message
                "",                        # Clear habit input
                category,                  # Keep category selection
                "",                        # Clear duration input
                gr.update(visible=True),   # Show status message
                gr.update(value=summary)   # Update summary text
            ]
        
        # Connect the add button event
        add_btn.click(
            fn=add_and_refresh,
            inputs=[new_habit, category, duration],
            outputs=[
                status_message,
                new_habit,
                category,
                duration,
                status_message,
                summary_text
            ]
        )
        
        # Create a refresh button that will be clicked programmatically
        refresh_habits_btn = gr.Button("Refresh", visible=False)
        
        def add_and_refresh(habit_name, duration):
            message, _, _ = add_new_habit(habit_name, duration)
            return [
                message,                    # Status message
                "",                        # Clear habit input
                "",                        # Clear duration input
                gr.update(visible=True),    # Show status message
                True                        # Trigger refresh button
            ]
        
        # Connect the add button event
        add_btn.click(
            fn=add_and_refresh,
            inputs=[new_habit, duration],
            outputs=[
                status_message,
                new_habit,
                duration,
                status_message,
                refresh_habits_btn
            ]
        )
        
        # Connect refresh button to reload habits
        def reload_habits():
            current_habits = load_habits()
            morning_habits = [h for h in current_habits if any(x in h.lower() for x in ["wake", "morning", "meditation", "brain", "walk"])]
            evening_habits = [h for h in current_habits if any(x in h.lower() for x in ["evening", "massage", "learning", "journal", "guitar"])]
            flexible_habits = [h for h in current_habits if h not in morning_habits + evening_habits]
            
            return [
                gr.update(value=update_summary()),  # Update summary
                gr.update(visible=False)            # Hide status message
            ]
        
        refresh_habits_btn.click(
            fn=reload_habits,
            outputs=[
                summary_text,
                status_message
            ]
        )

def create_habit_group(habits, summary_text):
    """Create a group of habit tracking rows with better scaling"""
    for habit in habits:
        with gr.Row(equal_height=True, variant="compact") as row:
            # Task name and duration (left side)
            with gr.Column(scale=6, min_width=300):
                name_edit = gr.Textbox(
                    value=habit,
                    label="Task Name",
                    interactive=True,
                    container=False,
                )
                
                # Duration slider (optional, shown inline)
                duration_edit = None
                if any(x in habit.lower() for x in ["min", "hour"]):
                    duration_edit = gr.Slider(
                        minimum=5,
                        maximum=60,
                        value=int(''.join(filter(str.isdigit, habit))) if any(c.isdigit() for c in habit) else 20,
                        step=5,
                        label="Duration",
                        container=False,
                        scale=1
                    )
            
            # Checkboxes container (middle)
            with gr.Column(scale=7, min_width=350):
                with gr.Row(equal_height=True, variant="compact"):
                    days = ["M", "T", "W", "Th", "F", "S", "Su"]
                    checkboxes = []
                    for day in days:
                        with gr.Column(scale=1, min_width=30):
                            checkbox = gr.Checkbox(
                                label=day,
                                container=False,
                                scale=1,
                                min_width=25,
                                show_label=False
                            )
                            gr.Markdown(day, container=False)
                            checkboxes.append(checkbox)
            
            # Progress and actions (right side)
            with gr.Column(scale=3, min_width=150):
                with gr.Row(equal_height=True, variant="compact"):
                    progress = gr.Textbox(
                        value="0%",
                        label="Progress",
                        interactive=False,
                        container=False,
                        scale=2
                    )
                    edit_btn = gr.Button("✏️", scale=1, min_width=30)
                    delete_btn = gr.Button("🗑️", scale=1, min_width=30)
            
            # Connect edit button handler
            def edit_habit(name, duration=None):
                if duration is not None:
                    result = update_habit_name(habit, name, duration)
                    gr.Info(f"Updated: {name}")
                    return result
                result = update_habit_name(habit, name)
                gr.Info(f"Updated: {name}")
                return result
            
            edit_btn.click(
                fn=edit_habit,
                inputs=[name_edit] + ([duration_edit] if duration_edit else []),
                outputs=[name_edit]
            )
            
            # Connect delete button handler
            def delete_habit_fn(habit_name=habit):
                """Delete a habit and update the UI"""
                try:
                    # 1. Delete from habits_config.json first
                    config_path = Path("habits_config.json")
                    if config_path.exists():
                        with open(config_path, 'r') as f:
                            config_data = json.load(f)
                        if "habits" in config_data:
                            if habit_name in config_data["habits"]:
                                config_data["habits"].remove(habit_name)
                                with open(config_path, 'w') as f:
                                    json.dump(config_data, f, indent=2)
                                print(f"Removed {habit_name} from habits_config.json")

                    # 2. Update current daily data
                    current_data = load_daily_data()
                    if "habits" in current_data and habit_name in current_data["habits"]:
                        del current_data["habits"][habit_name]
                        save_daily_data(current_data)
                        print(f"Removed {habit_name} from current daily data")

                    # 3. Clean up historical data
                    json_files = list(DATA_DIR.glob("*.json"))
                    for file_path in json_files:
                        try:
                            with open(file_path, 'r') as f:
                                day_data = json.load(f)
                            if "habits" in day_data and habit_name in day_data["habits"]:
                                del day_data["habits"][habit_name]
                                with open(file_path, 'w') as f:
                                    json.dump(day_data, f, indent=2)
                                print(f"Removed {habit_name} from {file_path}")
                        except Exception as e:
                            print(f"Error updating file {file_path}: {e}")

                    # Show success notification
                    gr.Info(f"Deleted: {habit_name}")
                    
                    # Force reload habits from config
                    load_habits()  # Reload habits to ensure sync
                    
                    # Hide the row in UI
                    return gr.update(visible=False)
                
                except Exception as e:
                    print(f"Error deleting habit: {e}")
                    gr.Warning(f"Failed to delete {habit_name}")
                    return gr.update()
            
            # Connect delete button with proper output
            delete_btn.click(
                fn=delete_habit_fn,
                outputs=row
            )
            
            # Update progress when checkboxes change
            def make_progress_handler(current_habit):
                """Create a closure for the progress handler to capture the habit name"""
                def update_progress_display(*checkbox_values):
                    """Update progress display for a habit"""
                    completed = sum(1 for x in checkbox_values if x)
                    total = len(checkbox_values)
                    percentage = f"{(completed/total)*100:.1f}%" if total > 0 else "0%"
                    
                    # Update the data
                    current_data = load_daily_data()
                    if current_habit in current_data["habits"]:
                        current_data["habits"][current_habit] = list(checkbox_values)
                        save_daily_data(current_data)
                    
                    return percentage
                return update_progress_display
            
            # Connect checkbox handlers using closure
            progress_handler = make_progress_handler(habit)
            for checkbox in checkboxes:
                checkbox.change(
                    fn=progress_handler,
                    inputs=checkboxes,
                    outputs=progress
                )

def update_habit_name(old_name, new_name, duration=None):
    """Update habit name and optionally duration"""
    if not new_name.strip():
        return gr.update()
    
    try:
        # Format new name
        new_full_name = new_name.strip()
        if duration is not None:
            new_full_name = f"{new_full_name} ({int(duration)}min)"
        
        # Update habits configuration
        current_habits = load_habits()
        if old_name in current_habits:
            current_habits.remove(old_name)
            current_habits.append(new_full_name)
            save_habits(current_habits)
        
        # Update all daily files
        update_all_daily_files(habit_to_rename=old_name, new_name=new_full_name)
        
        # Return update for the textbox
        return gr.update(value=new_full_name)
    except Exception as e:
        print(f"Error updating habit name: {e}")
        gr.Warning(f"Failed to update {old_name}")
        return gr.update()

def update_summary():
    """Update the weekly summary text"""
    current_data = load_daily_data()
    total_habits = len(current_data["habits"])
    total_completed = sum(
        sum(1 for x in habit_data if x)
        for habit_data in current_data["habits"].values()
    )
    total_possible = total_habits * 7
    completion_rate = (total_completed / total_possible * 100) if total_possible > 0 else 0
    
    return f"""
    - Total Habits: {total_habits}
    - Completed Tasks: {total_completed}/{total_possible}
    - Overall Completion Rate: {completion_rate:.1f}%
    """

def auto_refresh():
    """Auto refresh function to check and refresh day data"""
    try:
        current_data = load_daily_data()
        current_data = check_and_refresh_day(current_data)
        save_daily_data(current_data)
        # Don't return anything
    except Exception as e:
        print(f"Error in auto refresh: {e}")

def update_all_daily_files(habit_to_remove=None, habit_to_rename=None, new_name=None):
    """Update all daily data files when habits are modified"""
    try:
        # Get all JSON files in the data directory
        json_files = list(DATA_DIR.glob("*.json"))
        
        for file_path in json_files:
            try:
                # Load the file
                with open(file_path, 'r') as f:
                    data = json.load(f)
                
                modified = False
                
                # Handle habit removal
                if habit_to_remove and habit_to_remove in data.get("habits", {}):
                    del data["habits"][habit_to_remove]
                    modified = True
                
                # Handle habit renaming
                if habit_to_rename and new_name and habit_to_rename in data.get("habits", {}):
                    data["habits"][new_name] = data["habits"].pop(habit_to_rename)
                    modified = True
                
                # Save if modified
                if modified:
                    with open(file_path, 'w') as f:
                        json.dump(data, f, indent=2, sort_keys=True)
                        
            except Exception as e:
                print(f"Error updating file {file_path}: {e}")
                continue
    except Exception as e:
        print(f"Error updating daily files: {e}")

def get_available_dates():
    """Get list of dates with existing data files"""
    try:
        json_files = sorted(DATA_DIR.glob("*.json"), reverse=True)  # Most recent first
        dates = [file.stem for file in json_files]  # Get dates from filenames
        return dates
    except Exception as e:
        print(f"Error getting available dates: {e}")
        return [get_date_key()]  # Return today's date as fallback

def refresh_dates():
    """Refresh the available dates in the dropdown"""
    dates = get_available_dates()
    return gr.update(choices=dates)

def load_selected_date_metrics(date):
    """Load metrics for the selected date"""
    data = load_daily_data(date)
    metrics = data.get("tracking_metrics", {
        "productivity": 0,
        "energy": 0,
        "mood": 0,
        "sleep_quality": 0,
        "exercise_intensity": 0
    })
    
    return [
        metrics["productivity"],
        metrics["energy"],
        metrics["mood"],
        metrics["sleep_quality"],
        metrics["exercise_intensity"]
    ]

def load_day_details(evt: gr.SelectData):
    """Load detailed view of a specific day"""
    try:
        # Get clicked date (remove the day of week if present)
        date = evt.value[0].split(" (")[0] if isinstance(evt.value, list) else evt.value
        
        data = load_daily_data(date)
        
        # Ensure required data structures exist with defaults
        if "focus" not in data:
            data["focus"] = {
                "priorities": [],
                "later": [],
                "priority_reward": "",
                "later_reward": ""
            }
        
        if "meals" not in data:
            data["meals"] = {
                "breakfast": "",
                "lunch": "",
                "dinner": "",
                "snacks": ""
            }
        
        # Ensure focus lists exist and are properly formatted
        if not isinstance(data["focus"].get("priorities", []), list):
            data["focus"]["priorities"] = []
        if not isinstance(data["focus"].get("later", []), list):
            data["focus"]["later"] = []
        
        # Format metrics data
        metrics_data = [
            ["Productivity", data.get("tracking_metrics", {}).get("productivity", 0)],
            ["Energy", data.get("tracking_metrics", {}).get("energy", 0)],
            ["Mood", data.get("tracking_metrics", {}).get("mood", 0)],
            ["Sleep Quality", data.get("tracking_metrics", {}).get("sleep_quality", 0)],
            ["Exercise Intensity", data.get("tracking_metrics", {}).get("exercise_intensity", 0)]
        ]
        
        # Format habits data with proper validation
        habits_data = []
        habits_dict = data.get("habits", {})
        
        # Load current habits configuration to ensure we show all configured habits
        current_habits = load_habits()
        
        # Create a row for each habit, using stored data if available or default values if not
        for habit in current_habits:
            status = habits_dict.get(habit, [False] * 7)
            # Ensure status is a list of 7 boolean values
            if not isinstance(status, list) or len(status) != 7:
                status = [False] * 7
            row = [habit]
            row.extend(["✓" if done else "×" for done in status])
            habits_data.append(row)
        
        # Sort habits by category (morning, evening, flexible)
        def get_habit_category(habit):
            if any(x in habit.lower() for x in ["wake", "morning", "meditation", "brain", "walk"]):
                return 0  # Morning
            elif any(x in habit.lower() for x in ["evening", "massage", "learning", "journal", "guitar"]):
                return 1  # Evening
            return 2  # Flexible
        
        habits_data.sort(key=lambda x: get_habit_category(x[0]))

        # Format journal data with validation
        journal_data = []
        for q, a in data.get("journal", {}).items():
            if isinstance(a, str):
                if a.strip():
                    journal_data.append([q, a])
        
        # Format focus and meals data with proper validation
        priorities_text = "\n".join([
            f"- {task[0]}: {task[1]}" if isinstance(task, list) and len(task) >= 2 else "- No task"
            for task in data["focus"]["priorities"]
            if isinstance(task, list) and len(task) >= 2 and task[0]
        ]) or "No priorities set"
        
        later_text = "\n".join([
            f"- {task[0]}: {task[1]}" if isinstance(task, list) and len(task) >= 2 else "- No task"
            for task in data["focus"]["later"]
            if isinstance(task, list) and len(task) >= 2 and task[0]
        ]) or "No tasks set"
        
        focus_meals = f"""### 🎯 Focus Tasks

**Must Do Today:**
{priorities_text}

**For Later:**
{later_text}

### 🍽️ Meals
- **Breakfast:** {data["meals"].get("breakfast", "") or "Not recorded"}
- **Lunch:** {data["meals"].get("lunch", "") or "Not recorded"}
- **Dinner:** {data["meals"].get("dinner", "") or "Not recorded"}
- **Snacks:** {data["meals"].get("snacks", "") or "Not recorded"}
"""
        
        return [
            date,  # Selected date
            metrics_data,  # Metrics view
            habits_data,  # Habits view
            journal_data,  # Journal view
            focus_meals  # Focus and meals view
        ]
    except Exception as e:
        print(f"Error loading details for date {date if 'date' in locals() else 'unknown'}: {str(e)}")
        # Return a graceful fallback with empty/default values
        return [
            evt.value,
            [["No metrics data available", 0]],
            [["No habits data available", "×", "×", "×", "×", "×", "×", "×"]],
            [["No journal entries available", ""]],
            """### 🎯 Focus Tasks\n\n**Must Do Today:**\nNo data available\n\n**For Later:**\nNo data available\n\n### 🍽️ Meals\nNo meal data available"""
        ]

def manual_save():
    """Manually save all current data"""
    try:
        current_data = load_daily_data()
        save_daily_data(current_data)
        return "✅ Data saved successfully!"
    except Exception as e:
        print(f"Error saving data: {e}")
        return "❌ Error saving data"

def clean_json_file(file_path):
    """Clean up potentially corrupted JSON file"""
    try:
        with open(file_path, 'r') as f:
            content = f.read().strip()
            
        # Try to find the last valid JSON structure
        try:
            # First try to parse as-is
            data = json.loads(content)
            return data
        except json.JSONDecodeError:
            # If that fails, try to clean up the content
            # Find the last closing brace
            last_brace = content.rfind('}')
            if last_brace != -1:
                content = content[:last_brace + 1]
                try:
                    data = json.loads(content)
                    # Save the cleaned data back to file
                    with open(file_path, 'w') as f:
                        json.dump(data, f, indent=2)
                    return data
                except json.JSONDecodeError:
                    pass
            
            # If all cleanup attempts fail, create new data
            data = create_empty_daily_data()
            with open(file_path, 'w') as f:
                json.dump(data, f, indent=2)
            return data
            
    except Exception as e:
        print(f"Error cleaning JSON file {file_path}: {e}")
        return create_empty_daily_data()

with gr.Blocks() as demo:
    # Load initial data
    current_data = load_daily_data()
    current_data = check_and_refresh_day(current_data)

    
    # Centered, smaller logo
    with gr.Row():
        with gr.Column(scale=2):
            pass  # Empty column for spacing
        with gr.Column(scale=1):
            gr.Image("./logo.png", show_label=False, container=False, width=250, show_download_button=False, )
        with gr.Column(scale=2):
            pass  # Empty column for spacing
    
    with gr.Row():
        date_text = gr.Textbox(
            value=datetime.datetime.now().strftime("%A, %B %d"),
            label="Date",
            interactive=False
        )
        date_picker = gr.Dropdown(
            choices=get_available_dates(),
            value=get_date_key(),
            label="Select Date",
            interactive=True
        )
        today_btn = gr.Button("Return to Today")
        refresh_dates_btn = gr.Button("🔄 Refresh Dates")
        save_btn = gr.Button("💾 Save Data", variant="primary")
        save_status = gr.Markdown(visible=True)
    
    # Connect save button event
    save_btn.click(
        fn=manual_save,
        outputs=save_status
    ).then(
        lambda: gr.update(visible=True),
        None,
        save_status
    )

    # Create state for all components that need updating
    with gr.Tabs():
        # Must Do Daily Tab
        with gr.TabItem("Must Do Daily"):
            create_habit_section()

        # Today's Focus Tab
        with gr.TabItem("Today's Focus"):
            with gr.Column():
                gr.Markdown("### Today's Focus")
                with gr.Row():
                    # Left column for priorities
                    with gr.Column(scale=2):
                        gr.Markdown("#### Must Do Today")
                        priorities = gr.Dataframe(
                            headers=["Task", "Status"],
                            datatype=["str", "str"],
                            value=current_data["focus"]["priorities"],
                            row_count=5,  # Fixed number of rows
                            col_count=(2, "fixed"),  # Fixed number of columns
                            interactive=True
                        )
                        priority_reward = gr.Textbox(
                            label="Reward for Completion",
                            value=current_data["focus"]["priority_reward"],
                            placeholder="Enter reward for completing priorities",
                            lines=2
                        )
                    
                    # Right column for later tasks
                    with gr.Column(scale=2):
                        gr.Markdown("#### For Later")
                        later = gr.Dataframe(
                            headers=["Task", "Status"],
                            datatype=["str", "str"],
                            value=current_data["focus"]["later"],
                            row_count=5,  # Fixed number of rows
                            col_count=(2, "fixed"),  # Fixed number of columns
                            interactive=True
                        )
                        later_reward = gr.Textbox(
                            label="Reward for Completion",
                            value=current_data["focus"]["later_reward"],
                            placeholder="Enter reward for completing later tasks",
                            lines=2
                        )
                
                # Event handlers
                priorities.change(
                    lambda x: update_data("focus.priorities", x),
                    inputs=[priorities]
                )
                priority_reward.change(
                    lambda x: update_data("focus.priority_reward", x),
                    inputs=[priority_reward]
                )
                later.change(
                    lambda x: update_data("focus.later", x),
                    inputs=[later]
                )
                later_reward.change(
                    lambda x: update_data("focus.later_reward", x),
                    inputs=[later_reward]
                )

        # Meals Tab
        with gr.TabItem("Meals"):
            with gr.Column():
                meal_inputs = {}
                for meal in ["breakfast", "lunch", "dinner", "snacks"]:
                    meal_inputs[meal] = gr.Textbox(
                        label=meal.capitalize(),
                        value=current_data["meals"][meal],
                        placeholder=f"What did you have for {meal}?"
                    )
                    meal_inputs[meal].change(
                        lambda x, m=meal: update_data(f"meals.{m}", x),
                        inputs=[meal_inputs[meal]]
                    )
        
        # Life Overview Tab
        with gr.TabItem("Life Overview"):
            with gr.Column():
                gr.Markdown("""
                ### 🌟 Your Life Journey Calculator
                
                Time is our most precious resource - not because it's limited, but because it's an opportunity for endless possibilities. 
                Let's explore your unique journey through time and discover the incredible potential that lies ahead.
                """)
                
                # Load saved config
                user_config = load_user_config()
                
                with gr.Row():
                    birth_date = gr.Textbox(
                        label="Your Birth Date (YYYY-MM-DD)",
                        value=user_config["birth_date"],
                        placeholder="YYYY-MM-DD"
                    )
                    birth_time = gr.Textbox(
                        label="Your Birth Time",
                        value=user_config["birth_time"],
                        placeholder="HH:MM (24-hour) or HH:MM AM/PM"
                    )
                    calculate_btn = gr.Button("✨ Calculate Your Life Journey", variant="primary")
                
                # Add status message
                status_msg = gr.Markdown()
                
                with gr.Tabs():
                    with gr.TabItem("Life Stats"):
                        with gr.Row():
                            current_age_md = gr.Markdown()
                            time_remaining_md = gr.Markdown()
                        with gr.Row():
                            progress_md = gr.Markdown()
                            milestones_md = gr.Markdown()
                            
                    with gr.TabItem("Visualizations"):
                        with gr.Row():
                            progress_plot = gr.Plot(label="Life Progress")
                            remaining_plot = gr.Plot(label="Time Until 90")
                        timeline_plot = gr.Plot(label="Life Seasons Timeline")

                # Update the calculate button click handler
                def update_stats_and_plots(birth_date_str, birth_time_str):
                    try:
                        # Save the values
                        if save_user_config(birth_date_str, birth_time_str):
                            stats = calculate_age_stats(birth_date_str, birth_time_str)
                            if "Error" in stats:
                                return [
                                    f"⚠️ {stats['Error']}", "", "", "", None, None, None
                                ]
                            
                            figures = create_life_visualizations(stats)
                            current_age, time_remaining, progress, milestones = create_stats_display(stats)
                            return [
                                current_age,
                                time_remaining,
                                progress,
                                milestones,
                                figures["progress"],
                                figures["remaining"],
                                figures["timeline"]
                            ]
                        else:
                            return ["⚠️ Failed to save configuration", "", "", "", None, None, None]
                    except Exception as e:
                        return [f"⚠️ Error: {str(e)}", "", "", "", None, None, None]
            
            calculate_btn.click(
                    fn=update_stats_and_plots,
                inputs=[birth_date, birth_time],
                    outputs=[
                        current_age_md,
                        time_remaining_md,
                        progress_md,
                        milestones_md,
                        progress_plot,
                        remaining_plot,
                        timeline_plot
                    ]
            )

        # Progress Tracking Tab
        with gr.TabItem("Progress Tracking"):
            with gr.Column():
                gr.Markdown("### Daily Metrics")
                with gr.Row():
                    # Load data for the selected date
                    selected_data = load_daily_data(date_picker.value)
                    
                    if "tracking_metrics" not in selected_data:
                        selected_data["tracking_metrics"] = {
                            "productivity": 0,
                            "energy": 0,
                            "mood": 0,
                            "sleep_quality": 0,
                            "exercise_intensity": 0
                        }
                    
                    productivity = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["productivity"], label="Productivity", step=1)
                    energy = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["energy"], label="Energy Level", step=1)
                    mood = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["mood"], label="Mood", step=1)
                    sleep = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["sleep_quality"], label="Sleep Quality", step=1)
                    exercise = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["exercise_intensity"], label="Exercise Intensity", step=1)

                gr.Markdown("### Weekly Overview")
                week_data = load_week_data()
                week_dates = get_week_dates()
                weekly_grid = gr.DataFrame(
                    headers=["Metric"] + [datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%a %d") for date in week_dates],
                    value=[
                        ["Productivity"] + [week_data[date]["tracking_metrics"]["productivity"] for date in week_dates],
                        ["Energy"] + [week_data[date]["tracking_metrics"]["energy"] for date in week_dates],
                        ["Mood"] + [week_data[date]["tracking_metrics"]["mood"] for date in week_dates],
                        ["Sleep"] + [week_data[date]["tracking_metrics"]["sleep_quality"] for date in week_dates],
                        ["Exercise"] + [week_data[date]["tracking_metrics"]["exercise_intensity"] for date in week_dates]
                    ],
                    interactive=False
                )

                gr.Markdown("### Monthly Stats")
                month_data = load_month_data()
                with gr.Row():
                    prod_label = gr.Label(f"Average Productivity: {calculate_success_rate(month_data, 'productivity')}/10")
                    energy_label = gr.Label(f"Average Energy: {calculate_success_rate(month_data, 'energy')}/10")
                    mood_label = gr.Label(f"Average Mood: {calculate_success_rate(month_data, 'mood')}/10")
                    sleep_label = gr.Label(f"Average Sleep: {calculate_success_rate(month_data, 'sleep_quality')}/10")
                    exercise_label = gr.Label(f"Average Exercise: {calculate_success_rate(month_data, 'exercise_intensity')}/10")

                # Update tracking metrics and connect to UI elements
                for slider in [productivity, energy, mood, sleep, exercise]:
                    slider.change(
                        fn=update_metrics,
                        inputs=[productivity, energy, mood, sleep, exercise, date_picker],
                        outputs=[
                            weekly_grid,
                            prod_label,
                            energy_label,
                            mood_label,
                            sleep_label,
                            exercise_label
                        ]
                    )

        # Journaling Tab
        with gr.TabItem("Daily Journal"):
            with gr.Column():
                gr.Markdown("""
                ### 📝 Daily Reflection Journal
                
                Take a moment to reflect on your day. These questions will help you process your experiences,
                learn from them, and plan for tomorrow. Your responses are saved automatically.
                """)
                
                # Create journal entries
                journal_inputs = {}
                current_journal = current_data.get("journal", {})
                
                for question in JOURNAL_QUESTIONS:
                    with gr.Group():
                        gr.Markdown(f"#### {question}")
                        journal_inputs[question] = gr.TextArea(
                            value=current_journal.get(question, ""),
                            placeholder="Write your thoughts here...",
                            lines=3,
                            label=""
                        )
                        
                        # Add change handler for each text area
                        journal_inputs[question].change(
                            fn=update_journal_entry,
                            inputs=[
                                gr.State(question),
                                journal_inputs[question]
                            ]
                        )
                
                # Add export button
                def export_journal():
                    current_data = load_daily_data()
                    if "journal" in current_data:
                        date = get_date_key()
                        export_text = f"Journal Entry for {date}\n\n"
                        
                        for question in JOURNAL_QUESTIONS:
                            answer = current_data["journal"].get(question, "")
                            if answer:  # Only include questions with answers
                                export_text += f"Q: {question}\n"
                                export_text += f"A: {answer}\n\n"
                        
                        return export_text
                    return "No journal entries found for today."
                
                with gr.Row():
                    export_btn = gr.Button("Export Journal Entry")
                    export_text = gr.TextArea(
                        label="Exported Journal",
                        interactive=False,
                        visible=False
                    )
                
                export_btn.click(
                    fn=export_journal,
                    outputs=export_text,
                    show_progress=True
                ).then(
                    lambda: gr.update(visible=True),
                    None,
                    [export_text]
                )

        # History Tab
        with gr.TabItem("History"):
            with gr.Column():
                gr.Markdown("### 📚 History Viewer")
                
                # Create the history table
                history_headers = [
                    "Date",
                    "Productivity",
                    "Energy",
                    "Mood",
                    "Sleep",
                    "Exercise",
                    "Habits",
                    "Journal"
                ]
                
                with gr.Row():
                    history_table = gr.DataFrame(
                        headers=history_headers,
                        datatype=["str", "number", "number", "number", "number", "number", "str", "number"],
                        value=load_history_data(),
                        interactive=False
                    )
                
                # Create detail view sections
                with gr.Row():
                    selected_date = gr.Textbox(label="Selected Date", interactive=False)
                    refresh_btn = gr.Button("🔄 Refresh History")
                
                with gr.Tabs() as detail_tabs:
                    with gr.TabItem("Metrics"):
                        metrics_view = gr.DataFrame(
                            headers=["Metric", "Value"],
                            datatype=["str", "number"],
                            interactive=False
                        )
                    
                    with gr.TabItem("Habits"):
                        gr.Markdown("### Daily Habits Tracking")
                        habits_view = gr.DataFrame(
                            headers=["Habit", "M", "T", "W", "Th", "F", "S", "Su"],
                            datatype=["str", "str", "str", "str", "str", "str", "str", "str"],
                            interactive=False,
                            value=[[habit] + ["×"] * 7 for habit in load_habits()]  # Initialize with default values
                        )
                    
                    with gr.TabItem("Journal"):
                        journal_view = gr.DataFrame(
                            headers=["Question", "Response"],
                            datatype=["str", "str"],
                            interactive=False
                        )
                    
                    with gr.TabItem("Focus & Meals"):
                        focus_meals_md = gr.Markdown()
                
                # Connect event handlers
                history_table.select(
                    fn=load_day_details,
                    outputs=[
                        selected_date,
                        metrics_view,
                        habits_view,
                        journal_view,
                        focus_meals_md
                    ]
                )
                
                refresh_btn.click(
                    fn=load_history_data,
                    outputs=[history_table]
                )

        # Documentation Tab
        with gr.TabItem("Documentation"):
            with gr.Column():
                gr.Markdown("""
                # Potential Made Simple System Documentation

                ## Overview
                Welcome to your Life Tracking System, inspired by Rob Dyrdek's "Rhythm of Existence" philosophy. This comprehensive app helps you monitor and optimize various aspects of your life, creating a harmonious balance between work, health, personal life, and sleep.

                ## Philosophy
                The "Rhythm of Existence" philosophy, pioneered by entrepreneur Rob Dyrdek, emphasizes the importance of creating intentional, balanced routines that maximize both productivity and life satisfaction. Key principles include:

                - **Intentional Living**: Every day is an opportunity to make progress towards your goals
                - **Balance**: Maintaining equilibrium between work, health, relationships, and personal growth
                - **Consistency**: Building sustainable habits that compound over time
                - **Measurement**: What gets measured gets improved
                - **Reflection**: Regular review and adjustment of life patterns

                ## Features

                ### 1. Must Do Daily
                - Track daily habits and routines
                - Organize tasks into morning, evening, and flexible time slots
                - Monitor weekly progress and completion rates
                - Set custom durations for time-based activities

                ### 2. Today's Focus
                - Prioritize tasks with "Must Do Today" and "For Later" lists
                - Set rewards for completing priority tasks
                - Track task status and progress
                - Maintain clarity on daily objectives

                ### 3. Meals
                - Log daily meals and snacks
                - Monitor eating patterns
                - Track nutritional consistency

                ### 4. Life Overview
                - Calculate and visualize your life journey
                - Track progress through different life seasons
                - Set and monitor life milestones
                - Understand time allocation and remaining potential

                ### 5. Progress Tracking
                - Monitor daily metrics:
                  - Productivity (0-5)
                  - Energy Level (0-5)
                  - Mood (0-5)
                  - Sleep Quality (0-5)
                  - Exercise Intensity (0-5)
                - View weekly and monthly trends
                - Track success rates and improvements

                ### 6. Daily Journal
                - Reflect on daily experiences
                - Answer guided questions for deeper insight
                - Export journal entries for review
                - Build self-awareness through consistent reflection

                ### 7. History
                - Review past data and trends
                - Analyze patterns in habits and metrics
                - Track long-term progress
                - Learn from historical patterns

                ## Best Practices

                1. **Morning Routine**
                   - Start with mindfulness and exercise
                   - Review daily priorities
                   - Set intentions for the day

                2. **Throughout the Day**
                   - Update task status regularly
                   - Log meals as they happen
                   - Track metrics while they're fresh

                3. **Evening Routine**
                   - Complete journal entries
                   - Review task completion
                   - Plan for tomorrow

                4. **Weekly Review**
                   - Analyze progress trends
                   - Adjust habits as needed
                   - Set new goals and rewards

                ## Tips for Success

                1. **Start Small**
                   - Begin with a few key habits
                   - Gradually add more as you build consistency
                   - Focus on progress, not perfection

                2. **Be Consistent**
                   - Log data daily
                   - Complete journal entries regularly
                   - Track metrics consistently

                3. **Review and Adjust**
                   - Use the History tab to spot patterns
                   - Adjust goals based on progress
                   - Celebrate improvements

                4. **Stay Motivated**
                   - Set meaningful rewards
                   - Track progress visually
                   - Share achievements with others

                ## Technical Notes

                - Data is saved automatically
                - Manual save option available
                - Export functionality for journal entries
                - Daily refresh at midnight
                - Ability to view and edit past dates

                ## Support and Feedback

                This is a free tool designed to help you optimize your life and create your own perfect rhythm of existence. As you use the app, remember that the goal is progress, not perfection. Every small improvement compounds over time to create significant life changes.

                For support or to share feedback, please visit the project's repository or contact the development team.

                Happy tracking! 🌟
                """)

    # Date selection handlers
    def load_selected_date(date):
        try:
            # Validate date format
            datetime.datetime.strptime(date, "%Y-%m-%d")
            data = load_daily_data(date)
            
            # Update display date
            display_date = datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%A, %B %d")
            
            # Update journal entries if they exist
            journal_updates = []
            for question in JOURNAL_QUESTIONS:
                journal_updates.append(data.get("journal", {}).get(question, ""))
            
            return [display_date] + journal_updates
        except ValueError:
            return [date_text.value] + ["" for _ in JOURNAL_QUESTIONS]

    def return_to_today():
        today = get_date_key()
        date_picker.value = today
        return [today, datetime.datetime.now().strftime("%A, %B %d")]

    # Connect date selection events
    date_picker.change(
        fn=load_selected_date,
        inputs=[date_picker],
        outputs=[date_text] + list(journal_inputs.values())
    )

    today_btn.click(
        fn=return_to_today,
        outputs=[date_picker, date_text]
    )

    # Auto-refresh every minute
    def auto_refresh():
        """Auto refresh function to check and refresh day data"""
        try:
            current_data = load_daily_data()
            current_data = check_and_refresh_day(current_data)
            save_daily_data(current_data)
        except Exception as e:
            print(f"Error in auto refresh: {e}")

    demo.load(fn=auto_refresh)  # No outputs needed
    demo.queue()

    # Connect the date selection events
    date_picker.change(
        fn=load_selected_date_metrics,
        inputs=[date_picker],
        outputs=[productivity, energy, mood, sleep, exercise]
    )

    refresh_dates_btn.click(
        fn=refresh_dates,
        outputs=[date_picker]
    )

demo.launch()