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

class Subscriptions:
    def __init__(self, page: ft.Page):
        self.page = page
        self.plan = {
            'first_2_months':'First Two Months' ,
            'monthly':'Monthly',
            'yearly':'Yearly'
        }
        self.status = {
            'active':'Active',
            'cancelled':'Cancelled',
            'expired':'Expired',
            'less_than_5_days':'Less than 5 days'
        }
        self.search_field = ft.TextField(label="Search", on_submit=self.on_search_btn_click, expand=True)
        self.all_subscriptions = self.get_subscriptions()

        self.subscriptions_list = ft.ListView(
            controls=self.create_list(self.all_subscriptions, self.on_subscription_btn_click),
            spacing=10,
            expand=4
        )

        self.company_name = ft.TextField(label="Company Name", read_only=True)
        self.company_register_number = ft.TextField(label="Register Number", read_only=True)
        self.subscription_plan = ft.TextField(label="Subscription Plan",  read_only=True)
        self.subscription_status = ft.TextField(label="Subscription Status", read_only=True)
        self.subscription_start_date = ft.TextField(label="Subscription Start Date", read_only=True)
        self.subscription_end_date = ft.TextField(label="Subscription End Date", read_only=True)

        self.selected_subscription = None

    def create_list(self, items, on_click_handler):
        """Helper to create list items for a column."""
        return [
            ft.Container(
                content=ft.Row(
                    [
                        ft.Column(
                            [
                                ft.Text(item['register_number'], expand=True, weight=ft.FontWeight.BOLD),  
                                ft.Text(self.plan[item['plan']], size=12)
                            ]
                        ),
                        ft.Text(self.status[item['status']])
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                ),
                width=300,
                bgcolor=ft.Colors.BLUE_50 if item['status'] != 'expired' else ft.Colors.RED,
                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 on_subscription_btn_click(self, item):
        self.selected_subscription = item
        tenant = self.get_tenant(item['user_id'])
        self.company_name.value = tenant['name']
        self.company_name.update()
        self.company_register_number.value = tenant['register_number']
        self.company_register_number.update()
        self.subscription_plan.value = self.plan[item['plan']]
        self.subscription_plan.update()
        self.subscription_status.value = self.status[item['status']]
        self.subscription_status.update()
        self.subscription_start_date.value = str(item['start_date']).split('T')[0]
        self.subscription_start_date.update()
        self.subscription_end_date.value = str(item['end_date']).split('T')[0]
        self.subscription_end_date.update()

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

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

    def on_search_btn_click(self, e):
        value = self.search_field.value
        print(f'Search for {value}')
        buffer = []
        for subscription in self.all_subscriptions:
            if value in subscription['register_number']:
                buffer.append(subscription)
        self.subscriptions_list.controls.clear()
        self.subscriptions_list.controls = self.create_list(buffer, self.on_subscription_btn_click)
        self.subscriptions_list.update()

    def update_status(self, status):
        try:
            user_data = {
                'subscription_id': self.selected_subscription['id'],
                'status': status
            }
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.post("{API_BASE_URL}/admin/users/update", headers=headers, json = user_data)  
            #print(response.text)
        except Exception as e:
            print(e)

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Text("Subscriptions", size=24, weight=ft.FontWeight.BOLD),
                    ft.Row(
                        [
                            self.search_field,
                            ft.Button("Search", on_click=self.on_search_btn_click)
                        ]
                    ),
                    ft.Row(
                        [
                            self.subscriptions_list,
                            ft.Column(
                                [
                                    self.company_name,
                                    self.company_register_number,
                                    self.subscription_plan,
                                    self.subscription_status,
                                    self.subscription_start_date,
                                    self.subscription_end_date,
                                    ft.Row(
                                        [
                                            ft.Button("Renew", on_click=self.update_status('active')),
                                            ft.Button("Unsubscribe", on_click=self.update_status('cancelled'))
                                        ]
                                    )
                                ],
                                expand=6
                            )
                        ],
                        vertical_alignment=ft.CrossAxisAlignment.START
                    )
                ],
                alignment=ft.MainAxisAlignment.START,
            )
        )