import flet as ft
import requests
from config import API_BASE_URL

class TransportersPage:
    def __init__(self, page: ft.Page, dashboard):
        self.page = page
        self.dashboard = dashboard
        self.transporters = []
        self.dialog = None
        self.name = ft.TextField(
            label="Name", 
            expand=True,
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.street_and_number = ft.TextField(
            label="Street and number",
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.postal_code = ft.TextField(
            label="Postal code",
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.city = ft.TextField(
            label="City",
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.region_county = ft.TextField(
            label="Region / County",
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.country = ft.TextField(
            label="Country",
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.register_number = ft.TextField(
            label="Register Number", 
            expand=True,
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.contact_person = ft.TextField(
            label="Contact Person", 
            expand=True,
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.phone = ft.TextField(
            label="Phone", 
            expand=True,
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.email = ft.TextField(
            label="Email", 
            expand=True,
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.vat = ft.TextField(
            label="VAT", 
            expand=True,
            input_filter=ft.InputFilter(
                allow=True,
                regex_string=r"^[\x20-\x7E]*$", 
                replacement_string=""
            ),
        )
        self.user_id = self.page.session.get("user_id")
        self.selected_id = None
        self.subscription_error = ft.Text("Please subscribe to add new transporter", color=ft.Colors.RED)

    def open_dialog(self, transporter=None):
        if transporter:
            self.selected_id = transporter["id"]
            self.name.value = transporter["name"]
            self.street_and_number.value = transporter["address"].split(" %")[0]
            self.postal_code.value = transporter["address"].split(" %")[1]
            self.city.value = transporter["address"].split(" %")[2]
            self.region_county.value = transporter["address"].split(" %")[3]
            self.country.value = transporter["address"].split(" %")[4]
            self.register_number.value = transporter["register_number"]
            self.contact_person.value = transporter["contact_person"]
            self.phone.value = transporter["phone"]
            self.email.value = transporter["email"]
            self.vat.value = transporter["vat"]
        else:
            self.selected_id = None
            self.name.value = ""
            self.street_and_number.value = ""
            self.postal_code.value = ""
            self.city.value = ""
            self.region_county.value = ""
            self.country.value = ""
            self.register_number.value = ""
            self.contact_person.value = ""
            self.phone.value = ""
            self.email.value = ""
            self.vat.value = ""

        self.dialog = ft.AlertDialog(
            modal=True,
            title=ft.Text("Transporter"),
            content=ft.Column(
                controls=[
                    self.name,
                    self.register_number,
                    self.vat,
                    self.contact_person,
                    self.phone,
                    self.email,
                    self.street_and_number, 
                    self.postal_code,
                    self.city,
                    self.region_county,
                    self.country,
                ],
                width=600,
                scroll=ft.ScrollMode.ALWAYS
            ),
            actions=[
                ft.TextButton("Cancel", on_click=lambda e: self.page.close(self.dialog)),
                ft.ElevatedButton("Save", on_click=self.save_transporter)
            ],
        )
        self.page.dialog = self.dialog
        self.page.open(self.dialog)

    def save_transporter(self, e):
        address = f'{self.street_and_number.value} %{self.postal_code.value} %{self.city.value} %{self.region_county.value} %{self.country.value}'

        data = {
            "name": self.name.value,
            "address": address,
            "register_number": self.register_number.value,
            "contact_person": self.contact_person.value,
            "phone": self.phone.value,
            "email": self.email.value,
            "vat": self.vat.value, 
            "user_id": self.user_id
        }

        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}

        if self.selected_id:
            requests.put(f"{API_BASE_URL}/transporters/{self.selected_id}", json=data, headers=headers)
        else:
            requests.post(f"{API_BASE_URL}/transporters/", json=data, headers=headers)

        self.page.close(self.dialog)
        self.refresh()
        self.page.update()

    def delete_transporter(self, transporter_id):
        def confirm_delete(e):
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            requests.delete(f"{API_BASE_URL}/transporters/{transporter_id}", headers=headers)
            self.page.close(self.confirm_dialog)
            self.refresh()

        self.confirm_dialog = ft.AlertDialog(
            title=ft.Text("Confirm"),
            content=ft.Text("Are you sure you want to delete this transporter?"),
            actions=[
                ft.ElevatedButton("Yes", on_click=confirm_delete),
                ft.ElevatedButton("No", on_click=lambda e: self.page.close(self.confirm_dialog))
            ]
        )
        self.page.dialog = self.confirm_dialog
        self.page.open(self.confirm_dialog)

    def refresh(self):
        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(f"{API_BASE_URL}/transporters/", headers=headers)
        if response.ok:
            self.transporters = response.json()
        else:
            self.transporters = []

        self.transporter_list.controls.clear()
        for transporter in self.transporters:
            self.transporter_list.controls.append(
                ft.Container(
                    content=ft.Row([
                        ft.Column([
                            ft.Text(f"{transporter['name']}", size=16, weight=ft.FontWeight.BOLD),
                            ft.Text(f"{transporter['email']} • {transporter['phone']}", size=12)
                        ], expand=True),
                        ft.IconButton(icon=ft.Icons.EDIT, on_click=lambda e, t=transporter: self.open_dialog(t)),
                        ft.IconButton(icon=ft.Icons.DELETE, on_click=lambda e, t=transporter: self.delete_transporter(t["id"])),
                    ]),
                    padding=10,
                    border=ft.border.all(1, ft.Colors.GREY_300),
                    bgcolor=ft.Colors.BLUE_50,
                    border_radius=10,
                )
            )
        self.page.update()

    def get_current_subscription_plan(self):
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.get(f"{API_BASE_URL}/subscription/", headers=headers)
            #print(response.text)
            return response.json()[-1] if response.status_code == 200 else None
        except Exception as e:
            print("Error loading subscription:", e)

    def get_client_access(self):
        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(f"{API_BASE_URL}/profile/", headers=headers, timeout=10)
        user = response.json()
        if user['user_role'] == 'user':
            return True
        else:
            id = self.page.session.get("user_id")
            response = requests.get(f"{API_BASE_URL}/company_user/access/{id}", headers=headers)
            return True if response.json()['transporters'] == 1 else False

    def build(self):
        self.transporter_list = ft.Column(spacing=10, expand=True, scroll=ft.ScrollMode.ADAPTIVE,)
        self.refresh()
        self.add_transporter_btn = ft.ElevatedButton("Add Transporter", icon=ft.Icons.ADD, on_click=lambda e: self.open_dialog())
        self.header = ft.Row(
            controls=[
                ft.Text("Transporters", size=24, weight=ft.FontWeight.BOLD, expand=True),
            ],
            alignment=ft.MainAxisAlignment.SPACE_BETWEEN
        )
        subscription = self.get_current_subscription_plan()
        if subscription:
            if subscription['status'] != 'expired':
                self.header.controls.append(self.add_transporter_btn)
            else:
                self.header.controls.append(self.subscription_error)
        else:
            self.header.controls.append(self.subscription_error)
        return ft.Column(
            [
                self.header,
                self.transporter_list
            ], 
            alignment=ft.MainAxisAlignment.START,
            
        ) if self.get_client_access() else ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Transporters", size=24, weight=ft.FontWeight.BOLD),
                        ],
                        alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                    ),
                    ft.Row(
                        [
                            ft.Text(
                                "You do not have access to this page content", 
                                size=24, 
                                weight=ft.FontWeight.BOLD,
                                color=ft.Colors.RED
                            )
                        ],
                        alignment=ft.MainAxisAlignment.CENTER
                    ),
                    ft.Text("")
                ],
                alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                expand=True
            ),
            expand=True
        )
