from ast import Dict
import re
from threading import Event
import io
import logging
# from pypasser import reCaptchaV3
from pickle import APPEND
import uuid
import flet as ft
import datetime

import os
import tempfile
import base64
import requests
from tags import Form
from minio import Minio
from minio.error import S3Error
from cbJenisPelaporan import CbJenisPelaporan
from cbLokasiPelaporan import CbLokasiPelaporan
from flet import (Column,ElevatedButton,FilePicker,FilePickerResultEvent,
    FilePickerUploadEvent,FilePickerUploadFile,ProgressRing,
    Ref,Row,Text,icons
)
global_url_bucket = None


class Landing(ft.Container):
    def __init__(self):
        super().__init__(
            expand=True,
            padding=ft.padding.only(top=0, left=0, right=0, bottom=15),
            col={"sm": 12, "md": 12, "lg": 6},
            bgcolor="white10",
        )
        
        self.image = ft.Container( 
            content=ft.ResponsiveRow(
                controls=[
                    ft.Image(
                    src=f"/images/wbs_new_logo.jpeg",
                    fit=ft.ImageFit.CONTAIN,
                    # col={"xs": 2, "sm": 2, "md": 4, "lg": 10},
                )
             ],
            ),
            border_radius=10,
        )

        

        self.content = ft.ResponsiveRow(
            controls=[
                self.image,
                ],
            # col={"sm": 12, "md": 12, "lg": 5},
          
        )

def control_ref(page: ft.Page):
    page.theme_mode = ft.ThemeMode.LIGHT
    page.fonts = {
        "RobotoSlab": "https://github.com/google/fonts/raw/main/apache/robotoslab/RobotoSlab%5Bwght%5D.ttf"
    }
    nama_pelapor = ft.Ref[ft.TextField]()
    kronologi_kejadian = ft.Ref[ft.TextField]()
    alamat_email = ft.Ref[ft.TextField]()
    nomor_telepon = ft.Ref[ft.TextField]()
    date_pelaporan = ft.Ref[ft.TextField]()
    greetings = ft.Ref[ft.Column]()
    cbJPelaporan = CbJenisPelaporan()
    tagsClass = Form()
    cbLPelaporan = CbLokasiPelaporan()
    prog_bars: Dict[str, ProgressRing] = {}
    files = Ref[Column]()
    upload_button = Ref[ElevatedButton]()
    MAX_FILE_SIZE_MB = 2
    

    def validate_email(email):
        # Pola ekspresi reguler untuk validasi alamat email
        email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
        if re.match(email_pattern, email):
            return True
        else:
            return False

    def validate_phone_number(phone_number):
        # Pola ekspresi reguler untuk validasi nomor telepon
        phone_pattern = r'^\d{10,13}$'
        if re.match(phone_pattern, phone_number):
            return True
        else:
            return False

    def btn_click(e):
       
        # Mengambil nilai inputan dari alamat email dan nomor telepon
        alamat_email_value = alamat_email.current.value
        nomor_telepon_value = nomor_telepon.current.value

        # Memeriksa validitas email dan nomor telepon
        is_valid_email = validate_email(alamat_email_value)
        is_valid_phone_number = validate_phone_number(nomor_telepon_value)

        # Menggabungkan validasi dan menampilkan pesan Snackbar
        if is_valid_email and is_valid_phone_number:
            show_snackbar_message("Email dan nomor telepon valid")
        elif not is_valid_email and not is_valid_phone_number:
            show_snackbar_message("Email dan nomor telepon tidak valid")
        else:
            if not is_valid_email:
                show_snackbar_message("Email tidak valid")
            if not is_valid_phone_number:
                show_snackbar_message("Nomor telepon tidak valid")

            
        # jenis_laporan_value = cbJPelaporan.get_selected_values()
        # lokasi_laporan_value = cbLPelaporan.get_selected_values_2()
        
        # message = (
        #     f"Hallo, {nama_pelapor.current.value} :)!\n"
        #     f"Alamat email kamu {alamat_email.current.value}\n"
        #     f"Nomor telepon kamu {nomor_telepon.current.value}\n"
        #     f"Kamu membuat laporan pada tanggal {date_picker.value}\n"
        #     f"Jenis laporan kamu {', '.join(jenis_laporan_value)}\n"
        #     f"Kamu melaporkan dari lokasi {', '.join(lokasi_laporan_value)}\n"
        #     f"kronologi kejadian, {kronologi_kejadian.current.value}"
        # )
        # greetings.current.controls.append(ft.Column(
        #     controls=[
        #         ft.Text(message)
        #         ]))
        hit_endpoint()
    
        cbJPelaporan.reset()
        cbLPelaporan.resetDropdown()
        tagsClass.reset_tags()
        nama_pelapor.current.value = ""
        alamat_email.current.value = ""
        nomor_telepon.current.value = ""
        date_picker.value = ""

        page.update()
        nama_pelapor.current.focus()

    def change_date(e):
        date_value = date_picker.value
        formatted_date = date_value.strftime("%d/%m/%Y")
        date_pelaporan.current.value = formatted_date
        page.update()

    def date_picker_dismissed(e):
        print(f"Date picker dismissed, value is {date_picker.value}") 
    
    def show_snackbar_message(text: str = "Pesan:", duration: int = 6000):
        """
        Metode pembantu yang menampilkan pesan snackbar kepada pengguna.
        :param text: str: teks pesan snackbar
        :param duration: int: durasi pesan snackbar
        """
        page.show_snack_bar(
            ft.SnackBar(
                ft.Text(text),
                duration=duration,
                show_close_icon=True,
                behavior=ft.SnackBarBehavior.FLOATING,
                dismiss_direction=ft.DismissDirection.DOWN
            )
        )
        
    def file_picker_result(e: ft.FilePickerResultEvent):
        total_size_mb = sum([f.size / (1024 * 1024) for f in e.files])
        if total_size_mb > MAX_FILE_SIZE_MB:
            show_snackbar_message("Ukuran melebihi batas: {:.2f} MB".format(total_size_mb) + "\nMaksimal 2 MB")
            return
        upload_button.current.disabled = True if e.files is None else False
        prog_bars.clear()
        files.current.controls.clear()
        if e.files is not None:
            for f in e.files:
                prog = ProgressRing(value=0, bgcolor="#eeeeee", width=20, height=20)
                prog_bars[f.name] = prog
                files.current.controls.append(Row([prog, Text(f.name)]))
                print("files:", e.files)

        page.update()
        
    def minio(file_data):
        # Create a client with the MinIO server playground, its access key
        # and secret key.
        global global_url_bucket
        client = Minio(
            "bucket.mdd.co.id",
            access_key="minio",
            secret_key="mdd*123#123",
        )

        # The file to upload, change this path if needed'
        file_path = ('C:/Users/izol/OneDrive/Documents/Form/flet/lib/tmp/'+ file_data.name)
        try:
            with open(file_path, 'rb') as file:
                file_content = file.read()
        except Exception as e:
            print("Error:", e)
            return

        # Membuat UUID
        unique_id = uuid.uuid4()

        # Mengonversi UUID menjadi string heksadesimal
        hex_string = unique_id.hex

        # Mengambil 4 digit pertama
        four_digit_prefix = hex_string[:4]

        print("4 digit pertama dari UUID:", four_digit_prefix)
        # The destination bucket and filename on the MinIO server
        bucket_name = "wbs"
        destination_file = f"{four_digit_prefix}+{file_data.name}"

        # Make the bucket if it doesn't exist.
        found = client.bucket_exists(bucket_name)
        if not found:
            client.make_bucket(bucket_name)
            print("Created bucket", bucket_name)
        else:
            print("Bucket", bucket_name, "already exists")

        # Upload the file content
        try:
                file_stream = io.BytesIO(file_content)
                client.put_object(
                    bucket_name,
                    destination_file,
                    file_stream,
                    len(file_content)  # Get the size of the file
                )
                print(destination_file, "successfully uploaded to bucket", bucket_name,)
                
                # Get presigned URL
                global_url_bucket = client.presigned_put_object(bucket_name, destination_file)
                print("URL for the uploaded file:", global_url_bucket)
                
                # Delete file after successful upload
                os.remove(file_path)
                print("File", file_path, "deleted successfully.")
        except S3Error as e:
            print("Error:", e)

    def on_upload_progress(e: FilePickerUploadEvent):
        print("e proggres:", e.progress)
        prog_bars[e.file_name].value = e.progress
        prog_bars[e.file_name].update()
        if e.progress == 1:
            event_upload.set()
            
    file_picker = FilePicker(on_result=file_picker_result, on_upload=on_upload_progress)
    page.overlay.append(file_picker)
    event_upload = Event()
    
    def page_resize(e):
        pw.value = f"{page.width} px"
        pw.update()
    
    pw = ft.Text(bottom=50, right=50, style="displaySmall")

    def upload_files(e) :
        uf = []
        if file_picker.result is not None and file_picker.result.files is not None:
            for f in file_picker.result.files:
                uf.append(
                    FilePickerUploadFile(
                        f.name,
                        upload_url=page.get_upload_url(f.name, 600),
                    )
                )
                print("isi uf:", uf)
                print("isi f:", f)
            file_picker.upload(uf)
            event_upload.wait()
            minio(f)   
        
    def hit_endpoint():
        # post()
        # reCaptcha_response = reCaptchaV3("https://www.google.com/recaptcha/enterprise/anchor?ar=1&k=6LdSYv0UAAAAAF5PhF0Z1rK7QiupkyRBy1ebiFc4&co=aHR0cHM6Ly93d3cuZ3JhbW1hcmx5LmNvbTo0NDM.&hl=en&v=mrdLhN7MywkJAAbzddTIjTa&size=invisible&cb=dcwmpctj4h7r")
        global global_url_bucket
        jenis_laporan_value = cbJPelaporan.get_selected_values()
        lokasi_laporan_value = cbLPelaporan.get_selected_values_2()
        value_jenis_laporan = tagsClass.get_selected_tags()
        
        # Endpoint URI
        uri = "http://apidev.mdd.co.id:28194/internal/send-email"
        
         # Convert datetime object to string
        date_now = datetime.datetime.now().strftime("%d/%m/%Y")
        report_date_str = date_pelaporan.current.value if date_pelaporan.current.value else date_now
        current_time = datetime.datetime.now()
        report_time_str = current_time.strftime("%H:%M")

        # Payload data
        payload = {
            "email_data": {
                "reporter_name": nama_pelapor.current.value,
                "reporter_phone": nomor_telepon.current.value,
                "reporter_email": alamat_email.current.value,
                "report_date": report_date_str,
                "report_time": report_time_str,
                "report_location":  ", ".join(lokasi_laporan_value),
                "report_description": kronologi_kejadian.current.value,
                "report_file": global_url_bucket,
                "report_type": ", ".join(value_jenis_laporan),
                "form_id": "whistle-blower-v1"
            },
            "template": "emails.whistle-blower-v1"
        }
        
        try:
            # Kirim permintaan POST ke endpoint dengan payload yang diberikan
            response = requests.post(uri, json=payload)
            # Cek kode status respons
            print("isi payload:",payload)
            if response.status_code == 200:
                print("Email berhasil dikirim.")
                print("Response:", response.text)
            else:
                print("Gagal mengirim email. Kode status:", response.status_code)
        except Exception as e:
            print("Terjadi kesalahan:", str(e))    
            
    container_kronologi = ft.Card(
            ft.TextField(
            ref= kronologi_kejadian,
            border_color="transparent",
            multiline=True,
            min_lines=1,
            max_lines=3,
        ),
            )
        
    
                
    container_image = ft.Row(ref=files,expand=1, alignment=ft.MainAxisAlignment.CENTER)
    
    container_upload = ft.ResponsiveRow(
    controls=[
        ft.Container(
          padding=ft.padding.only(left=80,right=80),
          content=ElevatedButton(
            "Select files...",
            icon=icons.FOLDER_OPEN,
            on_click=lambda _: file_picker.pick_files(allow_multiple=True),
            expand=1
        ),
        ),
         
        container_image,
        ft.Container(
            padding=ft.padding.only(left=80, right=80),
            content= ElevatedButton(
                "Upload",
                ref=upload_button,
                icon=icons.UPLOAD,
                on_click=upload_files,
                disabled=True,
                expand=1
        ),
        )
    ]
)

    date_picker = ft.DatePicker(
        on_change=change_date,
        on_dismiss=date_picker_dismissed,
        first_date=datetime.datetime(2023, 10, 1),
        last_date=datetime.datetime(2024, 10, 1),
    )


    page.overlay.append(date_picker)

    container_date = ft.Row(
        alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
        controls=[
            ft.Card(
            ft.TextField(
                    ref=date_pelaporan,
                    label="tanggal kejadian",
                    read_only=True,
                    border_color=ft.colors.TRANSPARENT,
                ),
            expand=3
            ),
            ft.Card(
                ft.IconButton(
                        height=55,
                        icon=ft.icons.CALENDAR_MONTH,
                        on_click=lambda _: date_picker.pick_date()
            ),
            expand=1
            )
        ]
    )
    

    btn_save_Form = ft.Row(
        controls=[
            ft.ElevatedButton(
                "Submit",
                on_click=lambda e: btn_click(e)  # Gunakan lambda untuk meneruskan argumen
            )
        ],
        alignment=ft.MainAxisAlignment.CENTER
    )

    container_text_field = ft.Column(

                alignment=ft.CrossAxisAlignment.CENTER,
                controls=[
                    ft.Card(
                        ft.TextField(
                            ref=nama_pelapor,
                            label="nama pelapor",
                            autofocus=True,
                            border_color=ft.colors.TRANSPARENT
                        ),
                    ),
                    ft.Card(
                        ft.TextField(
                            ref=alamat_email,
                            label="alamat email",
                            border_color=ft.colors.TRANSPARENT
                        ),
                    ),
                    ft.Card(
                        ft.TextField(
                            ref=nomor_telepon,
                            label="nomor telepon",
                            input_filter=ft.InputFilter(
                                allow=True,
                                regex_string=r"[0-9]",
                                replacement_string=""),
                            border_color=ft.colors.TRANSPARENT
                        ),
                    )
                ]
            )
      

    title =ft.ResponsiveRow(
        controls=[
            ft.Column(
                col={"xs": 1, "sm": 6, "md": 6, "lg": 3, "xl": 3, "xxl": 3},
                controls=[
                    ft.Text('WBS', size=70, weight=ft.FontWeight.W_900,),
                    ft.Text('Menyusun Isi Pelaporan Secara Terstruktur dan Jelas',theme_style=ft.TextThemeStyle.DISPLAY_MEDIUM, overflow=ft.TextOverflow.ELLIPSIS),
                    ft.Text('Mengatasi Tantangan Umum dalam Proses Pelaporan',theme_style=ft.TextThemeStyle.DISPLAY_SMALL,overflow=ft.TextOverflow.ELLIPSIS)
                ]
            )
                
        ]
        
    )

    title_header = ft.Text(
            value="Format Pelaporan",
            size=30,
                    
        )

    subtitle = ft.Text(
            value="sampaikan Laporan Anda dengan Jelas dan Tuntas",
            size=15,
            max_lines=2
        )

    
    container_bundle = ft.ListView(
            auto_scroll=True,
            spacing=15,
            expand=True,
            controls=[
                title_header,
                subtitle,
                container_text_field,
                container_date,
                # text_lokasi,
                # container_pelaporan,
                tagsClass,
                ft.Text('lokasi pelaporan'),
                cbLPelaporan.dropdown,
                ft.Text("bukti Pelaporan :"),
                container_upload,
                ft.Text('kronolog kejadian :'),
                container_kronologi,
                btn_save_Form,
                ft.Divider(height=50),
                ft.Column(ref=greetings),
            ]
    )
    
    
    page.scroll="auto"
    page.add(
        ft.SafeArea(
            ft.Stack(
            controls=[
                ft.Container(
                    content=ft.Column(
                        controls=[
                            ft.Container(
                                content=ft.ResponsiveRow(
                                    controls=[
                                        Landing(),
                                        ft.Container(
                                            content=container_bundle,
                                            padding=ft.padding.only(left=20,right=20),
                                            col={"xs":12,"sm":12,"md":12,"lg":6})
                                    ],
                                    
                                    vertical_alignment="space-between",
                                ),
                                border=ft.border.only(
                                    top=ft.BorderSide(width=2, color="white10"),
                                    bottom=ft.BorderSide(width=2, color="white10")
                                )
                            )
                            
                        ]
                        
                    )
                )
            ],
            expand=True
        )
    )        
)
    page.update()
    

ft.app(
    target=control_ref,
    port=10000,
    assets_dir="assets",
    upload_dir="tmp",
    view=ft.AppView.WEB_BROWSER
    )
