import flet as ft
import requests
import json
from config import API_BASE_URL

class Tenants:
    def __init__(self, page):
        self.page = page
        self.search_field = ft.TextField(label="Search", on_submit=self.on_search_btn_click, expand=True)
        self.all_tenants = self.get_all_tenants()
        self.tenants_list = ft.ListView(
            controls=self.create_list(self.all_tenants, self.on_tenant_btn_click),
            spacing=10,
            expand=4
        )
        self.name = ft.TextField(label="Company Name")
        self.address = ft.TextField(label="Company Address")
        self.contact_name = ft.TextField(label="Contact Name")
        self.email = ft.TextField(label="Email")
        self.phone = ft.TextField(label="Phone")
        self.first_order_number = ft.TextField(label="First Order Number")
        self.register_number = ft.TextField(label="Register Number")
        self.terms = ft.TextField(label="Terms and Conditions", multiline=True, min_lines=5, max_lines=10)
        self.logo_filename = ft.TextField(label="Logo")
        self.save = ft.Button("Save", on_click=self.on_save_btn_click, width=100)
        self.error = ft.Text("")
        self.user_id = None
        self.user_details = ft.Column(
            [
                self.name,
                self.address,
                self.contact_name,
                self.email,
                self.phone,
                self.first_order_number,
                self.register_number,
                self.logo_filename,
                self.terms,
                self.save,
                self.error
            ],
            expand=6
        )

    def on_save_btn_click(self, e):
        user_data = {
            'name': self.name.value,
            'contact_name': self.contact_name.value,
            'email': self.email.value,
            'phone': self.phone.value,
            'register_number': self.register_number.value,
            'address': self.address.value,
            'logo_filename': self.logo_filename.value,
            'terms': self.terms.value,
            'first_order_number': self.first_order_number.value,
            'user_id': self.user_id
        }  
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.post(f"{API_BASE_URL}/admin/users/update", headers=headers, json = user_data)      
            if response.status_code == 200:
                self.error.value = 'Tenant data saved!'
                self.error.color = ft.Colors.GREEN
                self.error.update()
            else:
                self.error.value = 'Tenant data not saved!'
                self.error.color = ft.Colors.RED
                self.error.update()
        except Exception as e:
            print("Error saving tenant data:", e)

    def on_search_btn_click(self, e):
        value = self.search_field.value
        print(f'Search for {value}')
        buffer = []
        for tenant in self.all_tenants:
            if value in tenant['name']:
                buffer.append(tenant)
        self.tenants_list.controls.clear()
        self.tenants_list.controls = self.create_list(buffer, self.on_tenant_btn_click)
        self.tenants_list.update()

    def on_tenant_btn_click(self, item):
        self.error.value = ''
        self.error.color = ft.Colors.RED
        self.error.update()
        self.name.value = item['name']
        self.name.update()
        self.address.value = item['address']
        self.address.update()
        self.contact_name.value = item['contact_name']
        self.contact_name.update()
        self.email.value = item['email']
        self.email.update()
        self.phone.value = item['phone']
        self.phone.update()
        self.first_order_number.value = item['first_order_number']
        self.first_order_number.update()
        self.register_number.value = item['register_number']
        self.register_number.update()
        self.terms.value = item['terms']
        self.terms.update()
        self.logo_filename.value = item['logo_filename']
        self.logo_filename.update()
        self.user_id = item['id']

    def get_all_tenants(self):
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.get(f"{API_BASE_URL}/admin/users", headers=headers)      
            return response.json() if response.status_code == 200 else []
        except Exception as e:
            print("Error loading clients:", e)

    def create_list(self, items, on_click_handler):
        """Helper to create list items for a column."""
        return [
            ft.Container(
                content=ft.Row(
                    [
                        ft.Text(item['name'], expand=True),  
                    ],
                    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),
                ink=True,  # To enable click effect
                on_click=lambda e, id=item: on_click_handler(id),  # Attach the click handler
            )
            for item in items
        ]

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Text("Tenants", size=24, weight=ft.FontWeight.BOLD),

                    ft.Column(
                        [
                            ft.Row(
                                [
                                    self.search_field,
                                    ft.Button(
                                        "Search", 
                                        icon=ft.Icons.SEARCH, 
                                        width=100, 
                                        on_click=self.on_search_btn_click
                                    )
                                ]
                            ),
                            
                        ]
                    ),
                    
                    ft.Row(
                        [
                            
                            self.tenants_list,
                            self.user_details
                        ],
                        vertical_alignment=ft.CrossAxisAlignment.START
                    )
                
                ],
                scroll=ft.ScrollMode.ADAPTIVE
            ),
            expand=True
        )