import gradio as gr
import subprocess
import sys
import pandas as pd
import numpy as np
import os

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

from .services.evaluation_function import AALibrary
from .ui.data_outlier_value import OutlierLab
from .ui.data_missing_value import MissingValueLab
from .custom_theme import theme

script_dir = os.path.dirname(os.path.abspath(__file__))
css_path = os.path.join(script_dir, "main.css")
try:
    with open(css_path, "r") as f:
        css = f.read()
except FileNotFoundError:
    css = None

class AA_Prepflow():
    def __init__(self, data=pd.DataFrame()):
        self.data = gr.DataFrame(visible=False, value=data)

    def ensure_latest_packages(self):
        required_packages = ["gradio", "numpy", "pandas","pip"]
        for pkg in required_packages:
            try:
                __import__(pkg)
                # Upgrade to latest version anyway
                subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", pkg])
            except ImportError:
                subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])
    def call_preparation_lab(self):
        with gr.Blocks(theme=theme, css=css, title="Aplikasi Data Preparation") as demo:
            gr.Markdown("# 🚀 Aplikasi Data Preparation dengan Evaluasi Statistik")
            with gr.Sidebar(elem_classes="app-sidebar"):
                gr.Markdown("### Data Input")
                with gr.Row():
                    if not self.data.value['data']:
                        upload = gr.State(value=True)
                        with gr.Group(elem_classes="sidebar-group"):
                            file_input = gr.File(label="Unggah File CSV", file_types=[".csv"], scale=1, interactive=True, visible=True)
                    else:
                        upload = gr.State(value=False)
                        file_input = gr.File(label="Unggah File CSV", file_types=[".csv"], scale=1, interactive=True, visible=False)
                    with gr.Group(elem_classes="sidebar-group"):
                        with gr.Column():
                            input_type_data = gr.Dropdown(
                                choices=['Cross Sectional Data','Timeseries','Panel'], 
                                label="Pilih Tipe Data",
                                scale=2
                            )
                            col_time = gr.Dropdown(
                                choices=[], 
                                label="Pilih Waktu",
                                info="format date: %d/%m/%Y",
                                visible=False,
                                scale=2
                            )
                            category_filter = gr.Dropdown(
                                choices=[],
                                label="Pilih Kategori",
                                visible=False,
                                scale=2
                            )
                    with gr.Group(elem_classes="sidebar-group"):
                        # Menggunakan gr.Dropdown dengan mode multiseleksi
                        col_filter = gr.Dropdown(
                            choices=[], 
                            label="Pilih Kolom Exclude",
                            multiselect=True # Mengaktifkan mode multiselect
                        )
                    
            with gr.Tabs(elem_classes="main-tabs"):
                with gr.TabItem("Profiling"):
                    report_output = gr.HTML(
                        value="<h1>Upload a file and it will generate a report</h1>",
                        label="Profile Report"
                    )
                with gr.TabItem("Missing Value Treatement"):
                    missing_value_lab = MissingValueLab()
                    missing_value_lab.call_data_missing_value(self.data, file_input, col_time, category_filter, col_filter, input_type_data, upload, demo)
                with gr.TabItem("Outlier Treatement"):
                    outlier_lab = OutlierLab()
                    outlier_lab.call_data_outlier(self.data, file_input, col_time, category_filter, col_filter, input_type_data, upload, demo)
            aa_library = AALibrary()
            if not self.data.value['data']:
                file_input.upload(fn=aa_library.generate_profile_report, inputs=[file_input, gr.State(self.data.value), upload], outputs=[report_output, self.data])
            else:
                demo.load(
                    fn=aa_library.generate_profile_report, 
                    inputs=[gr.State(value="File tidak ada"), gr.State(self.data.value), upload], 
                    outputs=[report_output, self.data]
                )
        # Jalankan aplikasi
        demo.fill_height = True
        result = demo.launch(server_name="127.0.0.1", inline=True, height=1000)
        lab = result[0] if isinstance(result, tuple) else result
        return lab
        
# ===================================================================
# Ringkasan Hasil / Summary Update (app.py)
# ===================================================================
# - File ini sudah bersih dan sesuai dengan standar.
# - Tidak ada docstring atau type hints yang ditambahkan karena file ini
#   berfungsi sebagai entry point utama Gradio.
# - Tidak ada perubahan logika.