import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
from datetime import datetime, timedelta

import streamlit as st
import pandas as pd
from pathlib import Path

# تنظیمات صفحه
st.set_page_config(
    page_title="داشبورد مدیریت",
    page_icon="👤",
    layout="wide"
)

# استایل‌های داشبورد
st.markdown("""
<style>
    @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;700&display=swap');

    * {
        font-family: 'Vazirmatn', sans-serif;
        direction: rtl;
    }

    .dashboard-container {
        background: white;
        border-radius: 15px;
        padding: 25px;
        margin: 20px 0;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }

    .stat-card {
        background: linear-gradient(135deg, #6B73FF 0%, #000DFF 100%);
        color: white;
        padding: 20px;
        border-radius: 10px;
        margin: 10px;
        text-align: center;
    }

    .file-upload {
        border: 2px dashed #ccc;
        padding: 20px;
        border-radius: 10px;
        text-align: center;
        margin: 20px 0;
        transition: all 0.3s ease;
    }

    .file-upload:hover {
        border-color: #2196F3;
    }

    .action-button {
        background: #2196F3;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .action-button:hover {
        background: #1976D2;
        transform: scale(1.05);
    }

    .file-list {
        margin-top: 20px;
    }

    .file-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px;
        background: #f5f5f5;
        border-radius: 8px;
        margin: 10px 0;
    }

    .delete-button {
        background: #ff4444;
        color: white;
        padding: 5px 15px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }

    .delete-button:hover {
        background: #cc0000;
    }
</style>
""", unsafe_allow_html=True)

# هدر داشبورد
st.title("🎛️ داشبورد مدیریت")

# آمار کلی
col1, col2, col3 = st.columns(3)
with col1:
    st.markdown("""
        <div class="stat-card">
            <h2>۱۲۳</h2>
            <p>تعداد فایل‌ها</p>
        </div>
    """, unsafe_allow_html=True)
    
with col2:
    st.markdown("""
        <div class="stat-card">
            <h2>۴۵۶</h2>
            <p>تعداد پرسش‌ها</p>
        </div>
    """, unsafe_allow_html=True)
    
with col3:
    st.markdown("""
        <div class="stat-card">
            <h2>۷۸۹</h2>
            <p>پاسخ‌های موفق</p>
        </div>
    """, unsafe_allow_html=True)

# بخش آپلود فایل
st.markdown("""
    <div class="dashboard-container">
        <h3>📤 آپلود فایل جدید</h3>
        <div class="file-upload">
            <p>فایل خود را اینجا رها کنید یا کلیک کنید</p>
            <input type="file" accept=".csv,.json,.txt">
        </div>
    </div>
""", unsafe_allow_html=True)

# لیست فایل‌ها
st.markdown("""
    <div class="dashboard-container">
        <h3>📁 مدیریت فایل‌ها</h3>
        <div class="file-list">
            <div class="file-item">
                <span>banking_data.csv</span>
                <button class="delete-button">حذف</button>
            </div>
            <div class="file-item">
                <span>customer_qa.json</span>
                <button class="delete-button">حذف</button>
            </div>
            <div class="file-item">
                <span>training_data.txt</span>
                <button class="delete-button">حذف</button>
            </div>
        </div>
    </div>
""", unsafe_allow_html=True)

# تنظیمات مدل
st.markdown("""
    <div class="dashboard-container">
        <h3>⚙️ تنظیمات مدل</h3>
        <div style="margin: 20px 0;">
            <label>دمای مدل:</label>
            <input type="range" min="0" max="100" value="70">
        </div>
        <div style="margin: 20px 0;">
            <label>حداکثر طول پاسخ:</label>
            <input type="number" value="512">
        </div>
        <button class="action-button">ذخیره تنظیمات</button>
    </div>
""", unsafe_allow_html=True)

if __name__ == "__main__":
    st.markdown("""
        <script>
        // اضافه کردن عملکرد به دکمه‌ها
        document.querySelectorAll('.delete-button').forEach(button => {
            button.addEventListener('click', function() {
                if (confirm('آیا از حذف این فایل اطمینان دارید؟')) {
                    this.closest('.file-item').remove();
                }
            });
        });
        </script>
    """, unsafe_allow_html=True)

# اضافه کردن بخش نمودارها
st.markdown("""
    <div class="dashboard-container">
        <h3>📊 تحلیل عملکرد مدل</h3>
    </div>
""", unsafe_allow_html=True)

# نمودار نرخ یادگیری
col1, col2 = st.columns(2)
with col1:
    # نمودار نرخ یادگیری
    dates = [datetime.now() - timedelta(days=x) for x in range(30)]
    learning_rate = [0.001 * np.exp(-x/10) for x in range(30)]
    
    fig_learning = go.Figure()
    fig_learning.add_trace(go.Scatter(
        x=dates, 
        y=learning_rate,
        mode='lines+markers',
        name='نرخ یادگیری',
        line=dict(color='#2196F3', width=3)
    ))
    fig_learning.update_layout(
        title='نرخ یادگیری در طول زمان',
        xaxis_title='تاریخ',
        yaxis_title='نرخ یادگیری',
        template='plotly_white',
        dir='rtl'
    )
    st.plotly_chart(fig_learning, use_container_width=True)

with col2:
    # نمودار دقت مدل
    accuracy_data = np.linspace(0.7, 0.95, 30)
    fig_accuracy = go.Figure()
    fig_accuracy.add_trace(go.Scatter(
        x=dates,
        y=accuracy_data,
        mode='lines+markers',
        name='دقت مدل',
        line=dict(color='#4CAF50', width=3)
    ))
    fig_accuracy.update_layout(
        title='پیشرفت دقت مدل',
        xaxis_title='تاریخ',
        yaxis_title='دقت',
        template='plotly_white',
        dir='rtl'
    )
    st.plotly_chart(fig_accuracy, use_container_width=True)

# نمودار پاسخ‌های صحیح و غلط
labels = ['پاسخ‌های صحیح', 'پاسخ‌های غلط']
values = [85, 15]
fig_pie = go.Figure(data=[go.Pie(
    labels=labels,
    values=values,
    hole=.3,
    marker_colors=['#4CAF50', '#f44336']
)])
fig_pie.update_layout(title='نسبت پاسخ‌های صحیح به غلط')
st.plotly_chart(fig_pie, use_container_width=True)

# چت‌بات آموزش سریع
st.markdown("""
    <div class="dashboard-container">
        <h3>🤖 آموزش سریع با چت‌بات</h3>
        <div class="chat-trainer">
            <input type="text" placeholder="دستور آموزشی خود را وارد کنید..." class="trainer-input">
            <button class="action-button">ارسال دستور</button>
        </div>
    </div>
""", unsafe_allow_html=True)

# دکمه دسترسی به نالج بیس
st.markdown("""
    <div class="dashboard-container">
        <h3>📚 مدیریت نالج بیس</h3>
        <button class="action-button" onclick="window.open('/filemanager.py')">
            <i class="fas fa-folder-open"></i>
            دسترسی به فایل منیجر
        </button>
    </div>
""", unsafe_allow_html=True)

# اضافه کردن استایل‌های جدید
st.markdown("""
<style>
    .chat-trainer {
        display: flex;
        gap: 10px;
        margin: 20px 0;
    }
    
    .trainer-input {
        flex: 1;
        padding: 12px;
        border: 2px solid #f0f0f0;
        border-radius: 8px;
        font-size: 14px;
    }
    
    .plotly-chart {
        background: white;
        border-radius: 10px;
        padding: 15px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
</style>
""", unsafe_allow_html=True)
# اضافه کردن نمودار هیت‌مپ برای نمایش ماتریس خطا
confusion_matrix = np.array([
    [850, 50],
    [30, 70]
])

fig_heatmap = px.imshow(
    confusion_matrix,
    labels=dict(x="پیش‌بینی", y="مقدار واقعی"),
    x=['مثبت', 'منفی'],
    y=['مثبت', 'منفی'],
    color_continuous_scale="RdBu",
    title="ماتریس خطا"
)
fig_heatmap.update_layout(
    template='plotly_white',
    dir='rtl',
    width=600,
    height=500
)

# نمودار روند زمانی با قابلیت فیلتر
training_metrics = pd.DataFrame({
    'تاریخ': pd.date_range(start='2023-01-01', periods=100),
    'دقت': np.random.normal(0.85, 0.05, 100).cumsum()/100,
    'recall': np.random.normal(0.80, 0.05, 100).cumsum()/100,
    'f1_score': np.random.normal(0.82, 0.05, 100).cumsum()/100
})

fig_metrics = px.line(
    training_metrics, 
    x='تاریخ',
    y=['دقت', 'recall', 'f1_score'],
    title='روند معیارهای ارزیابی',
    labels={'value': 'مقدار', 'variable': 'معیار'},
    template='plotly_white'
)
fig_metrics.update_layout(
    showlegend=True,
    legend_title_text='معیارها',
    hovermode='x unified',
    updatemenus=[
        dict(
            buttons=list([
                dict(
                    args=[{"visible": [True, True, True]}],
                    label="همه",
                    method="restyle"
                ),
                dict(
                    args=[{"visible": [True, False, False]}],
                    label="دقت",
                    method="restyle"
                ),
                dict(
                    args=[{"visible": [False, True, False]}],
                    label="Recall",
                    method="restyle"
                ),
                dict(
                    args=[{"visible": [False, False, True]}],
                    label="F1 Score",
                    method="restyle"
                )
            ]),
            direction="down",
            showactive=True,
            x=0.1,
            y=1.1
        )
    ]
)

# نمودار توزیع خطا
errors = np.random.normal(0, 1, 1000)
fig_dist = px.histogram(
    errors,
    nbins=50,
    title='توزیع خطای پیش‌بینی',
    labels={'value': 'خطا', 'count': 'تعداد'},
    template='plotly_white'
)
fig_dist.update_layout(
    bargap=0.1,
    showlegend=False
)

# اضافه کردن کنترل‌های تعاملی
st.sidebar.markdown("## تنظیمات نمودارها")
time_range = st.sidebar.slider(
    "بازه زمانی (روز)",
    min_value=7,
    max_value=100,
    value=30
)

metric_threshold = st.sidebar.number_input(
    "آستانه دقت",
    min_value=0.0,
    max_value=1.0,
    value=0.8,
    step=0.05
)

# نمایش نمودارها با چینش جدید
col1, col2 = st.columns(2)
with col1:
    st.plotly_chart(fig_metrics, use_container_width=True)
    st.plotly_chart(fig_heatmap, use_container_width=True)
with col2:
    st.plotly_chart(fig_dist, use_container_width=True)
    st.plotly_chart(fig_pie, use_container_width=True)