from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.storage.jsonstore import JsonStore
from kivy.uix.scrollview import ScrollView
from kivy.uix.anchorlayout import AnchorLayout
from kivy.core.window import Window
import logging
import sys

# Set up logging for debugging purposes
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")

# Set window size to a phone resolution
Window.size = (360, 640)

# Create a storage file to store the allowance and savings data
try:
    store = JsonStore('finance_tracker.json')
except Exception as e:
    logging.error(f"Error initializing JsonStore: {e}")
    sys.exit(1)  # Exit if we can't access the store

# Menu Screen
class MenuScreen(Screen):
    def __init__(self, **kwargs):
        super(MenuScreen, self).__init__(**kwargs)
        
        # Create a layout with a purple-ish blue background
        layout = BoxLayout(orientation='vertical', spacing=20, padding=[20,  20, 20, 20])
        layout.canvas.before.clear()
        with layout.canvas.before:
            from kivy.graphics import Color, Rectangle
            Color(0.6, 0.4, 1, 1)  # Purple-ish blue background
            self.rect = Rectangle(size=self.size, pos=self.pos)
            self.bind(size=self._update_rect, pos=self._update_rect)

        # Add a logo or image at the top
        try:
            logo = Image(source=r'C:\Users\user\Downloads\algoallies.png', size_hint=(0.6, 0.6))
            layout.add_widget(logo)
        except Exception as e:
            logging.error(f"Error loading image: {e}")

        # Welcome message with a clean color
        welcome_label = Label(text="Welcome to Kid's Finance Tracker!", font_size=22, color=[1, 1, 1, 1], bold=True)  # White text
        layout.add_widget(welcome_label)

        # Start button with purple-ish blue color
        start_button = Button(text="Start", font_size=30, size_hint=(1, None), height=80, background_color=[0.4, 0.2, 0.8, 1], background_normal='', border=(30, 30, 30, 30))  # Darker purple-ish blue
        start_button.bind(on_press=self.go_to_finance)
        layout.add_widget(start_button)

        self.add_widget(layout)

    def _update_rect(self, instance, value):
        self.rect.size = instance.size
        self.rect.pos = instance.pos

    # Direct transition to Finance Tracker screen without animation
    def go_to_finance(self, instance):
        logging.debug("Start button clicked - Direct transition to Finance Tracker screen")
        try:
            # Direct transition without animation
            self.manager.current = 'finance'
        except Exception as e:
            logging.error(f"Error during screen transition: {e}")


# Finance Tracker Screen
class FinanceScreen(Screen):
    def __init__(self, **kwargs):
        super(FinanceScreen, self).__init__(**kwargs)
        logging.debug("Initializing FinanceScreen")
        
        layout = FinanceApp()  # Reuse the FinanceApp layout as the content for this screen
        self.add_widget(layout)


class FinanceApp(BoxLayout):
    def __init__(self, **kwargs):
        super(FinanceApp, self).__init__(**kwargs)
        logging.debug("Initializing FinanceApp layout")
        self.orientation = 'vertical'
        self.spacing = 20  # Increased spacing between elements
        self.padding = [20, 20, 20, 20]  # Padding around the layout

        # ScrollView to make the app scrollable if the content overflows the screen
        scroll_view = ScrollView(size_hint=(1, None), size=(Window.width, Window.height))

        # Main layout for the app content with a light purple-ish background
        content_layout = BoxLayout(orientation='vertical', spacing=20, size_hint_y=None)
        content_layout.canvas.before.clear()
        with content_layout.canvas.before:
            from kivy.graphics import Color, Rectangle
            Color(0.8, 0.6, 1, 1)  # Lighter purple-ish blue background
            self.rect = Rectangle(size=self.size, pos=self.pos)
            self.bind(size=self._update_rect, pos=self._update_rect)

        content_layout.bind(minimum_height=content_layout.setter('height'))

        # Initialize allowance, savings, and goal values
        try:
            self.allowance = store.get('finance').get('allowance', 0) if store.exists('finance') else 0
            self.savings = store.get('finance').get('savings', 0) if store.exists('finance') else 0
            self.goal = store.get('finance').get('goal', 0) if store.exists('finance') else 0
        except Exception as e:
            logging.error(f"Error loading finance data from store: {e}")
            self.allowance = 0
            self.savings = 0
            self.goal = 0

        # Add image at the top-left
        try:
            header_layout = BoxLayout(orientation='horizontal', size_hint_y=None, height=100)
            header_layout.add_widget(Image(source=r'C:\Users\user\Downloads\algoallies.png', size_hint_x=0.3))
            header_layout.add_widget(Label(text="Kid's Finance Tracker", font_size=20, bold=True, color=[1, 1, 1, 1], size_hint_x=0.7))  # White text
            content_layout.add_widget(header_layout)
        except Exception as e:
            logging.error(f"Error loading header layout: {e}")

        # Current Allowance Section with green text for money
        content_layout.add_widget(Label(text="Allowance Tracker", font_size=22, bold=True, color=[0.2, 0.2, 0.9, 1]))  # Green
        self.allowance_label = Label(text=f"Your Current Allowance: ${self.allowance}", font_size=20, color=[0.2, 0.2, 0.2, 1], bold=True)  # Darker green
      
        content_layout.add_widget(self.allowance_label)

        # Input for adding allowance, centered and smaller
        content_layout.add_widget(Label(text="Add Allowance:", font_size=22, color=[1, 1, 1, 1]))  # White
        content_layout.add_widget(Label(text="", font_size=10, color=[1, 1, 1, 1]))  # White EMPTY SPACE
        allowance_input_container = AnchorLayout(anchor_x='center')
        self.allowance_input = TextInput(multiline=False, font_size=18, size_hint=(0.6, None), height=40, background_color=[1, 1, 1, 1], padding_y=10)  # Centered and narrower width (60% of container)
        allowance_input_container.add_widget(self.allowance_input)
        content_layout.add_widget(allowance_input_container)

        # Button to add allowance with green background
        self.add_allowance_button = Button(text="Add Allowance", font_size=20, size_hint_y=None, height=40, background_color=[0, 0.7, 0.3, 1], background_normal='', border=(30, 30, 30, 30))  # Green button
        self.add_allowance_button.bind(on_press=self.add_allowance)
        content_layout.add_widget(self.add_allowance_button)

        # Add a visual separator (space)
        content_layout.add_widget(Label(size_hint_y=None, height=10))  # Spacer

        # Current Savings Section
        content_layout.add_widget(Label(text="Savings Tracker", font_size=22, bold=True, color=[0.2, 0.2, 0.9, 1]))  # Green
        self.savings_label = Label(text=f"Your Current Savings: ${self.savings}", font_size=20, color=[0.2, 0.2, 0.2, 1], bold=True)  # Green
        content_layout.add_widget(self.savings_label)

        # Input for setting a savings goal, centered and smaller
        content_layout.add_widget(Label(text="Set Savings Goal:", font_size=20, color=[1, 1, 1, 1]))  # White
        content_layout.add_widget(Label(text="", font_size=10, color=[1, 1, 1, 1]))  # White EMPTY SPACE
        goal_input_container = AnchorLayout(anchor_x='center')
        self.goal_input = TextInput(multiline=False, font_size=18, size_hint=(0.6, None), height=40, background_color=[1, 1, 1, 1], padding_y=10)  # Centered and narrower width (60% of container)
        goal_input_container.add_widget(self.goal_input)
        content_layout.add_widget(goal_input_container)

        # Button to set goal with red background
        self.set_goal_button = Button(text="Set Goal", font_size=20, size_hint_y=None, height=40, background_color=[1, 0.4, 0.4, 1], background_normal='', border=(30, 30, 30, 30))  # Red button
        self.set_goal_button.bind(on_press=self.set_goal)
        content_layout.add_widget(self.set_goal_button)

        # Show the user's current goal with yellow text for goal money
        self.goal_display = Label(text=f"Your Savings Goal: ${self.goal}" if self.goal > 0 else "No goal set", font_size=20, color=[0.9, 0.2, 0.2, 1], bold=True)  # Red for goal
        content_layout.add_widget(self.goal_display)

        # Add a visual separator (space)
        content_layout.add_widget(Label(size_hint_y=None, height=20))  # Spacer

        # Input for adding to savings, centered and smaller
        content_layout.add_widget(Label(text="Add to Savings:", font_size=20, color=[1, 1, 1, 1]))  # White
        content_layout.add_widget(Label(text="", font_size=10, color=[1, 1, 1, 1]))  # White EMPTY SPACE
        savings_input_container = AnchorLayout(anchor_x='center')
        self.add_savings_input = TextInput(multiline=False, font_size=18, size_hint=(0.6, None), height=50, background_color=[1, 1, 1, 1], padding_y=10)  # Centered and narrower width (60% of container)
        savings_input_container.add_widget(self.add_savings_input)
        content_layout.add_widget(savings_input_container)

        # Button to add to savings with green background
        self.add_savings_button = Button(text="Add to Savings", font_size=20, size_hint_y=None, height=40, background_color=[0, 0.7, 0.3, 1], background_normal='', border=(30, 30, 30, 30))  # Green button
        self.add_savings_button.bind(on_press=self.add_to_savings)
        content_layout.add_widget(self.add_savings_button)

        # Display savings goal progress
        content_layout.add_widget(Label(text="Savings Goal Progress:", font_size=20, bold = True, color=[0.2, 0.2, 0.9, 1]))  # White
        self.goal_label = Label(text=self.get_progress(), font_size=20, color=[0.9, 0.2, 0.2, 1], bold=True)  # Red for progress
        content_layout.add_widget(Label(text="", font_size=10, color=[1, 1, 1, 1]))  # White EMPTY SPACE
        content_layout.add_widget(self.goal_label)

        # Congratulatory message for achieving the savings goal
        self.congrats_label = Label(text="", font_size=20, color=[0.2, 0.6, 0.2, 1], opacity=0)  # Red
        content_layout.add_widget(Label(text="", font_size=10, color=[1, 1, 1, 1]))  # White EMPTY SPACE
        content_layout.add_widget(Label(text="*****************", font_size=10, color=[1, 1, 1, 1]))  # White EMPTY SPACE
        content_layout.add_widget(self.congrats_label)

        # Add the main content to the scroll view and then to the layout
        scroll_view.add_widget(content_layout)
        self.add_widget(scroll_view)

    def _update_rect(self, instance, value):
        self.rect.size = instance.size
        self.rect.pos = instance.pos

    # Add allowance and update the display
    def add_allowance(self, instance):
        try:
            logging.debug(f"Adding allowance: {self.allowance_input.text}")
            self.allowance += float(self.allowance_input.text)
            self.allowance_label.text = f"Your Current Allowance: ${self.allowance}"
            store.put('finance', allowance=self.allowance, savings=self.savings, goal=self.goal)
            self.allowance_input.text = ''
        except ValueError:
            logging.error("Invalid input for allowance")
            self.allowance_label.text = "Invalid input"

    # Set a savings goal and update the display
    def set_goal(self, instance):
        try:
            logging.debug(f"Setting goal: {self.goal_input.text}")
            self.goal = float(self.goal_input.text)
            self.goal_label.text = self.get_progress()
            self.goal_display.text = f"Your Savings Goal: ${self.goal}"
            store.put('finance', allowance=self.allowance, savings=self.savings, goal=self.goal)
            self.goal_input.text = ''
        except ValueError:
            logging.error("Invalid input for goal")
            self.goal_label.text = "Invalid input"

    # Add to savings and update the display
    def add_to_savings(self, instance):
        try:
            amount = float(self.add_savings_input.text)
            logging.debug(f"Adding to savings: {amount}")
            if amount > self.allowance:
                self.savings_label.text = "Not enough allowance"
            else:
                self.savings += amount
                self.allowance -= amount
                self.savings_label.text = f"Your Current Savings: ${self.savings}"
                self.allowance_label.text = f"Your Current Allowance: ${self.allowance}"
                store.put('finance', allowance=self.allowance, savings=self.savings, goal=self.goal)
                self.goal_label.text = self.get_progress()

                if self.savings >= self.goal:
                    self.show_congrats_message()
                    
                    

            self.add_savings_input.text = ''
        except ValueError:
            logging.error("Invalid input for savings")
            self.savings_label.text = "Invalid input"

    # Show congratulatory message when goal is reached
    def show_congrats_message(self):
        self.congrats_label.text = "Congrats! Now you can buy your desired item!\n\n"
        self.congrats_label.opacity = 1  # Show message
        

    # Get progress toward the savings goal
    def get_progress(self):
        if self.goal > 0:
            progress = (self.savings / self.goal) * 100
            return f"{progress:.2f}% of goal"
        else:
            return "No goal set"


class MyFinanceApp(App):
    def build(self):
        # Create a screen manager to switch between menu and finance tracker
        try:
            sm = ScreenManager()
            sm.add_widget(MenuScreen(name='menu'))
            sm.add_widget(FinanceScreen(name='finance'))
            return sm
        except Exception as e:
            logging.error(f"Error initializing ScreenManager: {e}")
            sys.exit(1)


if __name__ == '__main__':
    try:
        MyFinanceApp().run()
    except Exception as e:
        logging.critical(f"Critical error during app runtime: {e}")