import flet as ft
import requests
from config import API_BASE_URL

class Users:
    def __init__(self, page: ft.Page, dashboard):
        self.page = page
        self.dashboard = dashboard
        self.users = self.get_users()
        self.selected_user = None
        self.users_list = ft.ListView(
            controls=self.create_users_list(self.users, self.on_edit_btn_click, self.on_delete_btn_click),
            spacing=10,
            expand=True
        )
        self.add_user_dialog = ft.AlertDialog(
            title="Add Company User",
            content=ft.Column(
                [
                    ft.TextField(label="Name"),
                    ft.TextField(label="Email"),
                    ft.TextField(label="Temporary Password", password=True, can_reveal_password=True),
                    ft.Text("Give user access to add and modify:"),
                    ft.Checkbox(label="Orders In"),
                    ft.Checkbox(label="Order Out"),
                    ft.Checkbox(label="Addresses"),
                    ft.Checkbox(label="Clients"),
                    ft.Checkbox(label="Transporters"),
                    ft.Checkbox(label="Report"),
                    ft.Text("", color=ft.Colors.RED)
                ],
                width=600,
                height=500
            ),
            actions=[
                ft.TextButton(
                    "Cancel",
                    width=100,
                    on_click=self.on_cancel_btn_click
                ),
                ft.ElevatedButton(
                    "Save",
                    width=100,
                    on_click=self.on_save_btn_click
                )
            ]
        )

        self.delete_dialog = ft.AlertDialog(
            title=ft.Text("Delete User?"),
            actions=[
                ft.TextButton("Cancel", on_click=self.on_cancel_delete_btn_click, width=100),
                ft.Button("Yes", on_click=self.on_confirm_delete_btn_click, width=100),
            ]
        )

        self.edit_user_dialog = ft.AlertDialog(
            title=ft.Text(f"Edit User"),
            content=ft.Column(
                [
                    ft.Checkbox(label="Orders In"),
                    ft.Checkbox(label="Order Out"),
                    ft.Checkbox(label="Addresses"),
                    ft.Checkbox(label="Clients"),
                    ft.Checkbox(label="Transporters"),
                    ft.Checkbox(label="Report"),
                ],
                width=400,
                height=350
            ),
            actions=[
                ft.TextButton(
                    "Cancel",
                    width=100,
                    on_click=self.on_edit_cancel_btn_click
                ),
                ft.ElevatedButton(
                    "Save",
                    width=100,
                    on_click=self.on_edit_save_btn_click
                )
            ]
        )

    def on_edit_cancel_btn_click(self, e):
        self.page.close(self.edit_user_dialog)

    def on_edit_save_btn_click(self, e):
        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}
        access_payload = {
            'company_user_id':self.selected_user['id'],
            'orders_in':1 if self.edit_user_dialog.content.controls[0].value else 0,
            'orders_out':1 if self.edit_user_dialog.content.controls[1].value else 0,
            'addresses':1 if self.edit_user_dialog.content.controls[2].value else 0,
            'clients':1 if self.edit_user_dialog.content.controls[3].value else 0,
            'transporters':1 if self.edit_user_dialog.content.controls[4].value else 0,
            'report':1 if self.edit_user_dialog.content.controls[5].value else 0
        }
        response = requests.put(f"{API_BASE_URL}/company_user/update_access", headers=headers, json=access_payload)

        #set to default
        self.selected_user = None
        self.page.close(self.edit_user_dialog)
        self.edit_user_dialog.content.controls[0].value = False
        self.edit_user_dialog.content.controls[1].value = False
        self.edit_user_dialog.content.controls[2].value = False
        self.edit_user_dialog.content.controls[3].value = False
        self.edit_user_dialog.content.controls[4].value = False
        self.edit_user_dialog.content.controls[5].value = False
        self.edit_user_dialog.update()

    def on_confirm_delete_btn_click(self, e):
        self.page.close(self.delete_dialog)
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            delete_payload = {
                'user_id':self.selected_user['id']
            }
            response = requests.post(f"{API_BASE_URL}/admin/users/deactivate", headers=headers, json=delete_payload)
        except Exception as e:
            print("Error deleting company users:", e)
        users = self.get_users()
        self.users_list.controls.clear()
        self.users_list.controls = self.create_users_list(users, self.on_edit_btn_click, self.on_delete_btn_click)
        self.users_list.update()
        self.selected_user = None

    def on_cancel_delete_btn_click(self, e):
        self.page.close(self.delete_dialog)

    def add_new_user(self, e):
        self.page.open(self.add_user_dialog)

    def on_edit_btn_click(self, item):
        self.selected_user = item
        access = self.get_user_access(item['id'])
        self.edit_user_dialog.content.controls[0].value = True if access['orders_in']==1 else False
        self.edit_user_dialog.content.controls[1].value = True if access['orders_out']==1 else False
        self.edit_user_dialog.content.controls[2].value = True if access['destinations']==1 else False
        self.edit_user_dialog.content.controls[3].value = True if access['clients']==1 else False
        self.edit_user_dialog.content.controls[4].value = True if access['transporters']==1 else False
        self.edit_user_dialog.content.controls[5].value = True if access['report']==1 else False
        self.page.open(self.edit_user_dialog)

    def get_user_access(self, id):
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.get(f"{API_BASE_URL}/company_user/access/{id}", headers=headers)
            return response.json()
        except Exception as e:
            print("Error loading company user access:", e)

    def on_delete_btn_click(self, item):
        self.selected_user = item
        self.page.open(self.delete_dialog)

    def on_save_btn_click(self, e):
        self.page.close(self.add_user_dialog)
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            create_payload = {
                'name':self.add_user_dialog.content.controls[0].value,
                'email':self.add_user_dialog.content.controls[1].value,
                'company_id':self.page.session.get("user_id"),
                'password':self.add_user_dialog.content.controls[2].value
            }
            response = requests.post(f"{API_BASE_URL}/company_user/register_company_user", headers=headers, json=create_payload)
            company_user_id = response.json()['company_user_id'] if response.status_code == 201 else self.show_error_mesage
            if company_user_id:
                access_payload = {
                    'company_user_id':company_user_id,
                    'orders_in':1 if self.add_user_dialog.content.controls[4].value else 0,
                    'orders_out':1 if self.add_user_dialog.content.controls[5].value else 0,
                    'addresses':1 if self.add_user_dialog.content.controls[6].value else 0,
                    'clients':1 if self.add_user_dialog.content.controls[7].value else 0,
                    'transporters':1 if self.add_user_dialog.content.controls[8].value else 0,
                    'report':1 if self.add_user_dialog.content.controls[9].value else 0
                }
                response = requests.post(f"{API_BASE_URL}/company_user/access", headers=headers, json=access_payload)
        except Exception as e:
            print("Error loading company users:", e)
        
        users = self.get_users()
        self.users_list.controls.clear()
        self.users_list.controls = self.create_users_list(users, self.on_edit_btn_click, self.on_delete_btn_click)
        self.users_list.update()
        #set dialog to default valuse:
        self.add_user_dialog.content.controls[0].value = ''
        self.add_user_dialog.content.controls[1].value = ''
        self.add_user_dialog.content.controls[2].value = ''
        self.add_user_dialog.content.controls[4].value = False
        self.add_user_dialog.content.controls[5].value = False
        self.add_user_dialog.content.controls[6].value = False
        self.add_user_dialog.content.controls[7].value = False
        self.add_user_dialog.content.controls[8].value = False
        self.add_user_dialog.content.controls[9].value = False
        self.add_user_dialog.content.controls[10].value = ""
        self.add_user_dialog.update()

    def show_error_mesage(self):
        self.add_user_dialog.content.controls[10].value = "A user with this email has been already created, to reactivate it send a request at office@ordergo.eu"
        self.add_user_dialog.update()

    def on_cancel_btn_click(self, e):
        self.page.close(self.add_user_dialog)

    def get_users(self):
        try:
            user_id = self.page.session.get("user_id")
            users = []
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.get(f"{API_BASE_URL}/admin/users/company_users", headers=headers)
            if response.status_code == 200:
                all_users=response.json()
                for user in all_users:
                    if user['company_id'] == user_id and user['active'] == 1:
                        users.append(user)
                return users
            else:
                return []
        except Exception as e:
            print("Error loading company users:", e)

    def create_users_list(self, items, on_click_handler, on_click_handler2):
        return [
            ft.Container(
                content=ft.Row(
                    [
                        ft.Column(
                            [
                                ft.Text(item['name'], expand=True, weight=ft.FontWeight.BOLD),  
                                ft.Text(item['email'], size=12)
                            ]
                        ),
                        ft.Row(
                            [
                                ft.Button("Edit", on_click=lambda e, id=item: on_click_handler(id), width=100),
                                ft.FilledButton("Delete", on_click=lambda e, id=item: on_click_handler2(id), width=100, bgcolor=ft.Colors.RED)
                            ]
                        )
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                ),
                width=300,
                bgcolor=ft.Colors.BLUE_50,
                padding=10,
                border_radius=8,
                border=ft.border.all(1, ft.Colors.GREY_300),
            )
            for item in items
        ]

    def build(self):
        return ft.Container(
            content= ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Users", size=24, weight=ft.FontWeight.BOLD),
                            ft.Button("Add User", icon=ft.Icons.ADD, on_click=self.add_new_user)
                        ],
                        alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                    ),
                    self.users_list
                ],
                expand=True
            ),
            expand=True
        )