from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.label import MDLabel
from kivymd.uix.textfield import MDTextField
from kivymd.uix.button import MDRaisedButton, MDFlatButton
from kivymd.uix.textfield import MDTextFieldRect
from kivymd.uix.screen import MDScreen
from kivymd.icon_definitions import md_icons
import sqlite3

# Set background color for the app
Window.clearcolor = (0.1, 0.2, 0.3, 1)  # Dark blue background

# Database initialization
def init_db():
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS users (
                        username TEXT PRIMARY KEY,
                        email TEXT,
                        password TEXT
                    )''')
    conn.commit()
    conn.close()

# Add user function
def add_user(username, email, password):
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    try:
        cursor.execute('INSERT INTO users (username, email, password) VALUES (?, ?, ?)', 
                       (username, email, password))
        conn.commit()
        return True
    except sqlite3.IntegrityError:
        return False
    finally:
        conn.close()

# Verify user function
def verify_user(username, password):
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', (username, password))
    user = cursor.fetchone()
    conn.close()
    return user

# Login Screen
class LoginScreen(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        layout = MDBoxLayout(orientation='vertical', padding=100, spacing=10)

        # Vibrant title
        title_label = MDLabel(
            text="Login",
            halign="center",
            font_style="H4",
            theme_text_color="Custom",
            text_color=(1, 1, 0, 1),  # Vibrant yellow
            size_hint=(1, 0.2)
        )
        layout.add_widget(title_label)

        # Username and password input fields with icons
        layout.add_widget(MDLabel(text='Username', theme_text_color="Primary", font_style="H6"))
        self.username = MDTextField(
            hint_text="Enter your username", 
            mode="rectangle", 
            icon_left="account-circle", 
            line_color_focus=(0.9, 0.3, 0.4, 1),  # Red color when focused
        )
        layout.add_widget(self.username)

        layout.add_widget(MDLabel(text='Password', theme_text_color="Primary", font_style="H6"))
        self.password = MDTextField(
            hint_text="Enter your password", 
            mode="rectangle", 
            password=True, 
            icon_left="key", 
            line_color_focus=(0.2, 0.6, 1, 1),  # Blue color when focused
        )
        layout.add_widget(self.password)

        # Vibrant Login button
        login_button = MDRaisedButton(
            text='Login', 
            md_bg_color=(0.3, 0.9, 0.4, 1),  # Vibrant green
            size_hint=(1, 0.5),
            elevation=10
        )
        login_button.bind(on_press=self.login_action)
        layout.add_widget(login_button)

        # Vibrant Sign Up button
        signup_button = MDFlatButton(
            text='Go to Sign Up',
            size_hint=(1, 0.5),
            theme_text_color="Custom",
            text_color=(0.2, 0.7, 1, 1)  # Bright cyan
        )
        signup_button.bind(on_press=self.go_to_signup)
        layout.add_widget(signup_button)

        # Label for error or success messages
        self.message_label = MDLabel(
            text='', 
            theme_text_color="Custom", 
            text_color=(1, 0, 0, 1), 
            font_style="Subtitle1"
        )
        layout.add_widget(self.message_label)

        self.add_widget(layout)

    def login_action(self, instance):
        username = self.username.text.strip()
        password = self.password.text.strip()

        if not username or not password:
            self.message_label.text = "Please fill in both username and password."
            return

        user = verify_user(username, password)
        if user:
            self.message_label.text_color = (0, 1, 0, 1)  # Green color for success
            self.message_label.text = f"Welcome back, {username}!"
        else:
            self.message_label.text_color = (1, 0, 0, 1)  # Red color for errors
            self.message_label.text = "Incorrect username or password."

    def go_to_signup(self, instance):
        self.manager.current = 'signup'


# Sign-Up Screen
class SignUpScreen(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        layout = MDBoxLayout(orientation='vertical', padding=50, spacing=10)

        # Vibrant title
        title_label = MDLabel(
            text="Sign Up",
            halign="center",
            font_style="H4",
            theme_text_color="Custom",
            text_color=(1, 0.8, 0, 1),  # Vibrant yellow-orange
            size_hint=(1, 0.2)
        )
        layout.add_widget(title_label)

        # Username, email, and password input fields with icons
        layout.add_widget(MDLabel(text='Username', theme_text_color="Primary", font_style="H6"))
        self.username = MDTextField(
            hint_text="Choose a username", 
            mode="rectangle", 
            icon_left="account", 
            line_color_focus=(0.8, 0.2, 0.4, 1),  # Vibrant magenta
        )
        layout.add_widget(self.username)

        layout.add_widget(MDLabel(text='Email', theme_text_color="Primary", font_style="H6"))
        self.email = MDTextField(
            hint_text="Enter your email", 
            mode="rectangle", 
            icon_left="email", 
            line_color_focus=(0.4, 0.8, 0.2, 1),  # Bright green
        )
        layout.add_widget(self.email)

        layout.add_widget(MDLabel(text='Password', theme_text_color="Primary", font_style="H6"))
        self.password = MDTextField(
            hint_text="Create a password", 
            mode="rectangle", 
            password=True, 
            icon_left="lock", 
            line_color_focus=(0.2, 0.7, 1, 1),  # Bright blue
        )
        layout.add_widget(self.password)

        # Vibrant Sign Up button
        signup_button = MDRaisedButton(
            text='Sign Up', 
            md_bg_color=(0.8, 0.2, 0.2, 1),  # Bright red
            size_hint=(1, 0.5),
            elevation=10
        )
        signup_button.bind(on_press=self.signup_action)
        layout.add_widget(signup_button)

        # Vibrant Go to Login button
        login_button = MDFlatButton(
            text='Go to Login',
            size_hint=(1, 0.5),
            theme_text_color="Custom",
            text_color=(0.2, 0.7, 1, 1)  # Bright cyan
        )
        login_button.bind(on_press=self.go_to_login)
        layout.add_widget(login_button)

        # Label for error or success messages
        self.message_label = MDLabel(
            text='', 
            theme_text_color="Custom", 
            text_color=(1, 0, 0, 1), 
            font_style="Subtitle1"
        )
        layout.add_widget(self.message_label)

        self.add_widget(layout)

    def signup_action(self, instance):
        username = self.username.text.strip()
        email = self.email.text.strip()
        password = self.password.text.strip()

        if not username or not email or not password:
            self.message_label.text = "All fields are required."
            return

        if add_user(username, email, password):
            self.message_label.text_color = (0, 1, 0, 1)
            self.message_label.text = f"Account created successfully! Welcome, {username}."
            self.username.text = ''
            self.email.text = ''
            self.password.text = ''
        else:
            self.message_label.text_color = (1, 0, 0, 1)
            self.message_label.text = "Username already exists. Please choose another."

    def go_to_login(self, instance):
        self.manager.current = 'login'


# Main App
class MyApp(MDApp):
    def build(self):
        self.theme_cls.primary_palette = "Indigo"  # Change primary color
        self.theme_cls.theme_style = "Dark"  # Support for dark mode

        init_db()

        sm = ScreenManager()
        sm.add_widget(LoginScreen(name='login'))
        sm.add_widget(SignUpScreen(name='signup'))

        return sm


# Run the app
if __name__ == '__main__':
    MyApp().run()
