"""
API Key Management Interface for Streamlit
Admin interface for creating and managing API keys
"""

import streamlit as st
import pandas as pd
import numpy as np
from datetime import datetime
from typing import Optional
from api_manager import (
    create_api_key, get_all_api_keys, toggle_api_key_status, 
    delete_api_key, get_api_usage_stats, APIKeyType
)
from auth import check_permission

def show_api_key_management():
    """Show API key management interface (admin only)"""
    if not check_permission('admin'):
        st.error("🚫 Access denied. Admin privileges required.")
        return
    
    st.header("🔑 API Key Management")
    st.info("Generate and manage API keys for external system integration.")
    
    # Create new API key section
    with st.expander("🆕 Generate New API Key", expanded=False):
        with st.form("create_api_key"):
            st.subheader("Create API Key")
            
            col1, col2 = st.columns(2)
            with col1:
                key_name = st.text_input(
                    "Key Name*", 
                    help="Descriptive name for this API key (e.g., 'Mobile App', 'Dashboard Integration')"
                )
                key_type = st.selectbox(
                    "Access Level*",
                    options=["user", "admin"],
                    format_func=lambda x: "👤 User Access (Read-only)" if x == "user" else "🛡️ Admin Access (Full Control)"
                )
            
            with col2:
                rate_limit = st.number_input(
                    "Rate Limit (requests/hour)",
                    min_value=10,
                    max_value=10000,
                    value=1000,
                    help="Maximum number of API requests per hour"
                )
                
            description = st.text_area(
                "Description (Optional)",
                help="Detailed description of what this API key will be used for"
            )
            
            created_by = st.session_state.get('username', 'Unknown')
            
            if st.form_submit_button("🔑 Generate API Key", type="primary"):
                if not key_name.strip():
                    st.error("Please provide a key name.")
                else:
                    with st.spinner("Generating API key..."):
                        api_key_type = APIKeyType.ADMIN if key_type == "admin" else APIKeyType.USER
                        result = create_api_key(
                            key_name.strip(), 
                            api_key_type, 
                            created_by, 
                            description.strip() if description.strip() else None,
                            rate_limit
                        )
                        
                        if result['success']:
                            st.success("✅ API Key generated successfully!")
                            
                            # Display the key securely
                            st.markdown("### 🔐 Your New API Key")
                            st.warning("⚠️ **Important**: Copy this key now! It will not be shown again for security reasons.")
                            
                            # Show key with copy functionality
                            api_key_display = result['api_key']
                            st.code(api_key_display, language=None)
                            
                            # Key details
                            st.markdown("### 📋 Key Details")
                            col1, col2, col3 = st.columns(3)
                            with col1:
                                st.metric("Key Type", key_type.upper())
                            with col2:
                                st.metric("Rate Limit", f"{rate_limit}/hour")
                            with col3:
                                st.metric("Status", "Active")
                                
                            st.info("💡 **Usage**: Include this key in your API requests using the `X-API-Key` header or `Authorization: Bearer <key>` header.")
                        else:
                            st.error(f"❌ Error creating API key: {result['error']}")
    
    # Existing API keys section
    st.subheader("📊 Existing API Keys")
    
    try:
        api_keys = get_all_api_keys()
        
        if not api_keys:
            st.info("No API keys found. Generate your first API key above.")
            return
        
        # Display summary metrics
        total_keys = len(api_keys)
        active_keys = len([k for k in api_keys if k['is_active']])
        admin_keys = len([k for k in api_keys if k['key_type'] == 'admin'])
        user_keys = len([k for k in api_keys if k['key_type'] == 'user'])
        
        col1, col2, col3, col4 = st.columns(4)
        with col1:
            st.metric("Total Keys", total_keys)
        with col2:
            st.metric("Active Keys", active_keys)
        with col3:
            st.metric("Admin Keys", admin_keys)
        with col4:
            st.metric("User Keys", user_keys)
        
        st.markdown("---")
        
        # Display keys in expandable sections
        for key in api_keys:
            status_icon = "🟢" if key['is_active'] else "🔴"
            type_icon = "🛡️" if key['key_type'] == 'admin' else "👤"
            
            with st.expander(f"{status_icon} {type_icon} {key['key_name']} ({key['api_key_prefix']}••••)"):
                # Key information
                col1, col2 = st.columns(2)
                
                with col1:
                    st.write(f"**Type:** {key['key_type'].upper()}")
                    st.write(f"**Created:** {key['created_at'].strftime('%Y-%m-%d %H:%M') if key['created_at'] else 'Unknown'}")
                    st.write(f"**Created By:** {key['created_by']}")
                    st.write(f"**Status:** {'Active' if key['is_active'] else 'Inactive'}")
                
                with col2:
                    st.write(f"**Rate Limit:** {key['rate_limit_per_hour']}/hour")
                    st.write(f"**Usage Count:** {key['usage_count']}")
                    st.write(f"**Last Used:** {key['last_used'].strftime('%Y-%m-%d %H:%M') if key['last_used'] else 'Never'}")
                
                if key['description']:
                    st.write(f"**Description:** {key['description']}")
                
                st.markdown("---")
                
                # Usage statistics
                st.subheader("📈 Usage Statistics (Last 30 Days)")
                
                try:
                    usage_stats = get_api_usage_stats(key['id'], 30)
                    
                    if usage_stats:
                        # Create DataFrame for display
                        df = pd.DataFrame(usage_stats)
                        df['date'] = pd.to_datetime(df['date'])
                        df = df.sort_values('date', ascending=False)
                        
                        # Show recent usage
                        if len(df) > 0:
                            col1, col2, col3 = st.columns(3)
                            with col1:
                                st.metric("Total Requests", df['requests'].sum())
                            with col2:
                                st.metric("Unique Endpoints", df['unique_endpoints'].sum())
                            with col3:
                                avg_response = df['avg_response_time'].mean()
                                st.metric("Avg Response Time", f"{avg_response:.1f}ms" if pd.notna(avg_response) else "N/A")
                            
                            # Usage chart
                            if len(df) > 1:
                                st.line_chart(df.set_index('date')['requests'])
                        else:
                            st.info("No usage data available for this key.")
                    else:
                        st.info("No usage statistics available.")
                        
                except Exception as e:
                    st.warning(f"Could not load usage statistics: {str(e)}")
                
                # Management actions
                st.subheader("⚙️ Management Actions")
                col1, col2 = st.columns(2)
                
                with col1:
                    # Toggle status
                    current_status = key['is_active']
                    new_status_text = "Deactivate" if current_status else "Activate"
                    new_status_color = "secondary" if current_status else "primary"
                    
                    if st.button(f"{new_status_text} Key", key=f"toggle_{key['id']}", type=new_status_color):
                        try:
                            toggle_api_key_status(key['id'], not current_status)
                            st.success(f"✅ Key {'activated' if not current_status else 'deactivated'} successfully!")
                            st.rerun()
                        except Exception as e:
                            st.error(f"❌ Error updating key status: {str(e)}")
                
                with col2:
                    # Delete key (with confirmation)
                    if f"confirm_delete_{key['id']}" not in st.session_state:
                        st.session_state[f"confirm_delete_{key['id']}"] = False
                    
                    if not st.session_state[f"confirm_delete_{key['id']}"]:
                        if st.button(f"🗑️ Delete Key", key=f"delete_{key['id']}", type="secondary"):
                            st.session_state[f"confirm_delete_{key['id']}"] = True
                            st.rerun()
                    else:
                        st.warning("⚠️ Are you sure? This action cannot be undone!")
                        col_yes, col_no = st.columns(2)
                        with col_yes:
                            if st.button("✅ Yes, Delete", key=f"confirm_yes_{key['id']}", type="secondary"):
                                try:
                                    delete_api_key(key['id'])
                                    st.success("✅ API key deleted successfully!")
                                    st.session_state[f"confirm_delete_{key['id']}"] = False
                                    st.rerun()
                                except Exception as e:
                                    st.error(f"❌ Error deleting key: {str(e)}")
                        
                        with col_no:
                            if st.button("❌ Cancel", key=f"confirm_no_{key['id']}"):
                                st.session_state[f"confirm_delete_{key['id']}"] = False
                                st.rerun()
    
    except Exception as e:
        st.error(f"❌ Error loading API keys: {str(e)}")
    
    # API Documentation link
    st.markdown("---")
    st.subheader("📚 API Documentation")
    st.info("💡 **Need help?** Check out the comprehensive API documentation to learn how to integrate with your applications.")
    
    if st.button("📖 View API Documentation", type="primary"):
        st.session_state.page = "API Documentation"
        st.rerun()

def show_api_usage_monitoring():
    """Show API usage monitoring dashboard"""
    if not check_permission('admin'):
        st.error("🚫 Access denied. Admin privileges required.")
        return
        
    st.header("📊 API Usage Monitoring")
    st.info("Monitor API usage across all keys and endpoints.")
    
    # Time period selector
    col1, col2 = st.columns(2)
    with col1:
        days = st.selectbox("Time Period", [7, 30, 90], index=1, format_func=lambda x: f"Last {x} days")
    
    try:
        # Overall usage stats
        overall_stats = get_api_usage_stats(days=days)
        
        if overall_stats:
            df = pd.DataFrame(overall_stats)
            df['date'] = pd.to_datetime(df['date'])
            df = df.sort_values('date', ascending=False)
            
            # Summary metrics
            col1, col2, col3, col4 = st.columns(4)
            with col1:
                st.metric("Total Requests", df['requests'].sum())
            with col2:
                st.metric("Unique Endpoints", df['unique_endpoints'].sum())
            with col3:
                avg_response = df['avg_response_time'].mean()
                st.metric("Avg Response Time", f"{avg_response:.1f}ms" if pd.notna(avg_response) else "N/A")
            with col4:
                st.metric("Active Days", len(df))
            
            # Usage chart
            st.subheader("📈 Request Volume Over Time")
            if len(df) > 0:
                chart_df = df.set_index('date')[['requests']]
                st.line_chart(chart_df)
                
                # Response time chart
                st.subheader("⚡ Response Time Trends")
                response_df = df.set_index('date')[['avg_response_time']].dropna()
                if len(response_df) > 0:
                    st.line_chart(response_df)
                else:
                    st.info("No response time data available.")
            else:
                st.info("No usage data available for the selected period.")
        else:
            st.info("No API usage data found for the selected period.")
            
    except Exception as e:
        st.error(f"❌ Error loading usage statistics: {str(e)}")