<?php

namespace App\Http\Controllers\FrontUser;

use App\Http\Controllers\Controller;
use App\Services\AI\Phi3Service;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AIDashboardController extends Controller
{
    private $phi3Service;

    public function __construct(Phi3Service $phi3Service)
    {
        $this->phi3Service = $phi3Service;
    }

    /**
     * Display the AI dashboard
     */
    public function index()
    {
        $user = Auth::user();
        
        // Get conversation statistics
        $stats = $this->getConversationStats($user->id);
        
        // Get recent conversations
        $recentConversations = \App\Models\Conversation::where('user_id', $user->id)
            ->with(['messages' => function($query) {
                $query->latest()->limit(1);
            }])
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Get AI insights summary
        $insights = $this->getAIInsightsSummary($user->id);

        return view('FrontUser.ai.dashboard', compact('stats', 'recentConversations', 'insights'));
    }

    /**
     * Get conversation statistics for the user
     */
    private function getConversationStats(int $userId): array
    {
        $conversations = \App\Models\Conversation::where('user_id', $userId);
        
        $totalConversations = $conversations->count();
        $activeConversations = $conversations->where('status', 'active')->count();
        
        // Calculate average response time
        $avgResponseTime = \App\Models\ConversationMessage::whereHas('conversation', function($query) use ($userId) {
            $query->where('user_id', $userId);
        })
        ->where('role', 'assistant')
        ->whereNotNull('processing_time_ms')
        ->avg('processing_time_ms') ?? 0;

        // Calculate average satisfaction score
        $avgSatisfaction = \App\Models\Conversation::where('user_id', $userId)
            ->whereNotNull('satisfaction_score')
            ->avg('satisfaction_score') ?? 0;

        return [
            'total_conversations' => $totalConversations,
            'active_conversations' => $activeConversations,
            'avg_response_time' => round($avgResponseTime),
            'avg_satisfaction' => round($avgSatisfaction * 100, 1)
        ];
    }

    /**
     * Get AI insights summary
     */
    private function getAIInsightsSummary(int $userId): array
    {
        try {
            $insights = \App\Models\AIInsight::whereHas('conversation', function($query) use ($userId) {
                $query->where('user_id', $userId);
            })
            ->selectRaw('insight_type, COUNT(*) as count, AVG(confidence_score) as avg_confidence')
            ->groupBy('insight_type')
            ->get();

            $sentimentBreakdown = \App\Models\ConversationMessage::whereHas('conversation', function($query) use ($userId) {
                $query->where('user_id', $userId);
            })
            ->whereNotNull('sentiment')
            ->selectRaw('sentiment, COUNT(*) as count')
            ->groupBy('sentiment')
            ->get();

            return [
                'insights' => $insights,
                'sentiment_breakdown' => $sentimentBreakdown
            ];
        } catch (\Exception $e) {
            return [
                'insights' => collect(),
                'sentiment_breakdown' => collect()
            ];
        }
    }

    /**
     * Get conversation analytics data for charts
     */
    public function getAnalytics()
    {
        $user = Auth::user();
        
        // Sentiment analysis data
        $sentimentData = \App\Models\ConversationMessage::whereHas('conversation', function($query) use ($user) {
            $query->where('user_id', $user->id);
        })
        ->whereNotNull('sentiment')
        ->selectRaw('sentiment, COUNT(*) as count')
        ->groupBy('sentiment')
        ->get();

        // Conversation types data
        $conversationTypes = \App\Models\Conversation::where('user_id', $user->id)
            ->selectRaw('type, COUNT(*) as count')
            ->groupBy('type')
            ->get();

        // Daily conversation count for the last 30 days
        $dailyConversations = \App\Models\Conversation::where('user_id', $user->id)
            ->where('created_at', '>=', now()->subDays(30))
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'sentiment' => $sentimentData,
                'conversation_types' => $conversationTypes,
                'daily_conversations' => $dailyConversations
            ]
        ]);
    }

    /**
     * Get AI model status and configuration
     */
    public function getAIStatus()
    {
        try {
            $connectionTest = $this->phi3Service->testConnection();
            
            return response()->json([
                'success' => true,
                'ai_status' => [
                    'connected' => $connectionTest['success'],
                    'model' => 'phi3-mini',
                    'version' => '1.0.0',
                    'last_updated' => now()->toISOString()
                ],
                'configuration' => [
                    'max_tokens' => config('ai.phi3.max_tokens', 1000),
                    'temperature' => config('ai.phi3.temperature', 0.7),
                    'timeout' => config('ai.phi3.timeout', 30)
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update AI settings
     */
    public function updateSettings(Request $request)
    {
        $request->validate([
            'model' => 'required|string',
            'style' => 'required|string',
            'max_tokens' => 'required|integer|min:100|max:2000'
        ]);

        // In a real implementation, you would save these settings to the user's profile
        // For now, we'll just return success
        
        return response()->json([
            'success' => true,
            'message' => 'AI settings updated successfully'
        ]);
    }

    /**
     * Get conversation performance metrics
     */
    public function getPerformanceMetrics()
    {
        $user = Auth::user();
        
        $metrics = \App\Models\Conversation::where('user_id', $user->id)
            ->selectRaw('
                COUNT(*) as total_conversations,
                AVG(duration_seconds) as avg_duration,
                AVG(sentiment_score) as avg_sentiment,
                AVG(satisfaction_score) as avg_satisfaction,
                COUNT(CASE WHEN status = "completed" THEN 1 END) as completed_conversations,
                COUNT(CASE WHEN status = "active" THEN 1 END) as active_conversations
            ')
            ->first();

        $responseTime = \App\Models\ConversationMessage::whereHas('conversation', function($query) use ($user) {
            $query->where('user_id', $user->id);
        })
        ->where('role', 'assistant')
        ->whereNotNull('processing_time_ms')
        ->avg('processing_time_ms');

        return response()->json([
            'success' => true,
            'metrics' => [
                'total_conversations' => $metrics->total_conversations ?? 0,
                'avg_duration_minutes' => round(($metrics->avg_duration ?? 0) / 60, 2),
                'avg_sentiment' => round($metrics->avg_sentiment ?? 0, 2),
                'avg_satisfaction' => round(($metrics->avg_satisfaction ?? 0) * 100, 1),
                'completion_rate' => $metrics->total_conversations > 0 
                    ? round(($metrics->completed_conversations / $metrics->total_conversations) * 100, 1)
                    : 0,
                'avg_response_time_ms' => round($responseTime ?? 0),
                'active_conversations' => $metrics->active_conversations ?? 0
            ]
        ]);
    }
}
