<?php

namespace App\Http\Controllers\Brand;

use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\SupportConversation;
use App\Models\SupportMessage;
use App\Models\SupportBotSettings;
use App\Models\SupportAnalytics;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class SupportDashboardController extends Controller
{
    /**
     * Display support dashboard.
     */
    public function index(Request $request, Brand $brand)
    {
        Gate::authorize('manage-support', $brand);

        $dateRange = $request->input('date_range', '7'); // days
        $startDate = Carbon::now()->subDays($dateRange);

        // Get conversations
        $conversations = SupportConversation::where('brand_id', $brand->id)
            ->with(['customer', 'assignedAgent'])
            ->when($request->input('status'), function ($query, $status) {
                $query->where('status', $status);
            })
            ->when($request->input('escalated'), function ($query) {
                $query->where('escalated_to_human', true);
            })
            ->latest()
            ->paginate(20);

        // Get statistics
        $stats = $this->getStatistics($brand->id, $startDate);

        // Get bot settings
        $settings = SupportBotSettings::where('brand_id', $brand->id)->first();

        return view('brand.support.dashboard', compact('brand', 'conversations', 'stats', 'settings'));
    }

    /**
     * Get support statistics.
     */
    public function statistics(Request $request, Brand $brand): JsonResponse
    {
        Gate::authorize('manage-support', $brand);

        $dateRange = $request->input('date_range', 7);
        $startDate = Carbon::now()->subDays($dateRange);

        $stats = $this->getStatistics($brand->id, $startDate);

        return response()->json([
            'success' => true,
            'data' => $stats,
        ]);
    }

    /**
     * Get conversation details.
     */
    public function showConversation(Brand $brand, SupportConversation $conversation): JsonResponse
    {
        Gate::authorize('manage-support', $brand);

        if ($conversation->brand_id !== $brand->id) {
            return response()->json([
                'success' => false,
                'message' => 'Conversation not found',
            ], 404);
        }

        $conversation->load(['messages', 'customer', 'assignedAgent']);

        return response()->json([
            'success' => true,
            'data' => $conversation,
        ]);
    }

    /**
     * Assign agent to conversation.
     */
    public function assignAgent(Request $request, Brand $brand, SupportConversation $conversation): JsonResponse
    {
        Gate::authorize('manage-support', $brand);

        if ($conversation->brand_id !== $brand->id) {
            return response()->json([
                'success' => false,
                'message' => 'Conversation not found',
            ], 404);
        }

        $validated = $request->validate([
            'agent_id' => 'required|exists:users,id',
        ]);

        $conversation->update([
            'assigned_agent_id' => $validated['agent_id'],
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Agent assigned successfully',
            'data' => $conversation->fresh()->load('assignedAgent'),
        ]);
    }

    /**
     * Send agent message.
     */
    public function sendAgentMessage(Request $request, Brand $brand, SupportConversation $conversation): JsonResponse
    {
        Gate::authorize('manage-support', $brand);

        if ($conversation->brand_id !== $brand->id) {
            return response()->json([
                'success' => false,
                'message' => 'Conversation not found',
            ], 404);
        }

        $validated = $request->validate([
            'message' => 'required|string|max:2000',
        ]);

        $message = SupportMessage::create([
            'conversation_id' => $conversation->id,
            'sender_type' => 'agent',
            'sender_id' => $request->user()->id,
            'message_text' => $validated['message'],
        ]);

        $conversation->incrementMessageCount();

        return response()->json([
            'success' => true,
            'data' => $message->load('sender'),
        ]);
    }

    /**
     * Resolve conversation.
     */
    public function resolveConversation(Brand $brand, SupportConversation $conversation): JsonResponse
    {
        Gate::authorize('manage-support', $brand);

        if ($conversation->brand_id !== $brand->id) {
            return response()->json([
                'success' => false,
                'message' => 'Conversation not found',
            ], 404);
        }

        $conversation->resolve();

        return response()->json([
            'success' => true,
            'message' => 'Conversation resolved',
            'data' => $conversation->fresh(),
        ]);
    }

    /**
     * Get bot settings.
     */
    public function getSettings(Brand $brand): JsonResponse
    {
        Gate::authorize('manage-support', $brand);

        $settings = SupportBotSettings::where('brand_id', $brand->id)->first();

        if (!$settings) {
            $settings = SupportBotSettings::create([
                'brand_id' => $brand->id,
                'bot_enabled' => true,
                'confidence_threshold' => 70.0,
                'max_messages_before_escalation' => 10,
                'welcome_message' => SupportBotSettings::defaultWelcomeMessage(),
                'escalation_message' => SupportBotSettings::defaultEscalationMessage(),
                'offline_message' => SupportBotSettings::defaultOfflineMessage(),
            ]);
        }

        return response()->json([
            'success' => true,
            'data' => $settings,
        ]);
    }

    /**
     * Update bot settings.
     */
    public function updateSettings(Request $request, Brand $brand): JsonResponse
    {
        Gate::authorize('manage-support', $brand);

        $validated = $request->validate([
            'bot_enabled' => 'sometimes|boolean',
            'confidence_threshold' => 'sometimes|numeric|min:0|max:100',
            'max_messages_before_escalation' => 'sometimes|integer|min:1|max:50',
            'business_hours' => 'sometimes|array',
            'welcome_message' => 'sometimes|string|max:500',
            'escalation_message' => 'sometimes|string|max:500',
            'offline_message' => 'sometimes|string|max:500',
            'widget_settings' => 'sometimes|array',
            'pii_redaction_rules' => 'sometimes|array',
            'collect_feedback' => 'sometimes|boolean',
            'enable_human_handoff' => 'sometimes|boolean',
            'notification_settings' => 'sometimes|array',
            'fallback_email' => 'sometimes|email|nullable',
        ]);

        $settings = SupportBotSettings::updateOrCreate(
            ['brand_id' => $brand->id],
            $validated
        );

        return response()->json([
            'success' => true,
            'message' => 'Settings updated successfully',
            'data' => $settings,
        ]);
    }

    /**
     * Get analytics data.
     */
    public function analytics(Request $request, Brand $brand): JsonResponse
    {
        Gate::authorize('manage-support', $brand);

        $startDate = $request->input('start_date', Carbon::now()->subDays(30)->toDateString());
        $endDate = $request->input('end_date', Carbon::now()->toDateString());

        $analytics = SupportAnalytics::forBrand($brand->id)
            ->dateRange($startDate, $endDate)
            ->orderBy('date', 'asc')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $analytics,
        ]);
    }

    /**
     * Get low confidence topics.
     */
    public function lowConfidenceTopics(Brand $brand): JsonResponse
    {
        Gate::authorize('manage-support', $brand);

        $lowConfidenceMessages = SupportMessage::whereHas('conversation', function ($query) use ($brand) {
            $query->where('brand_id', $brand->id);
        })
            ->fromBot()
            ->lowConfidence(70.0)
            ->with('conversation')
            ->latest()
            ->limit(50)
            ->get();

        // Group by similar topics (simplified)
        $topics = [];
        foreach ($lowConfidenceMessages as $message) {
            $topics[] = [
                'message' => $message->message_text,
                'confidence' => $message->confidence_score,
                'conversation_id' => $message->conversation->conversation_id,
                'created_at' => $message->created_at,
            ];
        }

        return response()->json([
            'success' => true,
            'data' => $topics,
        ]);
    }

    /**
     * Calculate statistics.
     */
    protected function getStatistics(int $brandId, Carbon $startDate): array
    {
        $conversations = SupportConversation::where('brand_id', $brandId)
            ->where('created_at', '>=', $startDate);

        $totalConversations = $conversations->count();
        $resolvedByBot = (clone $conversations)->where('escalated_to_human', false)->where('status', 'resolved')->count();
        $escalated = (clone $conversations)->where('escalated_to_human', true)->count();
        $active = (clone $conversations)->where('status', 'active')->count();

        $avgConfidence = (clone $conversations)->avg('avg_confidence_score');
        $avgSatisfaction = (clone $conversations)->whereNotNull('satisfaction_rating')->avg('satisfaction_rating');

        $messages = SupportMessage::whereHas('conversation', function ($query) use ($brandId, $startDate) {
            $query->where('brand_id', $brandId)->where('created_at', '>=', $startDate);
        });

        $positiveFeedback = (clone $messages)->where('helpful_flag', true)->count();
        $negativeFeedback = (clone $messages)->where('helpful_flag', false)->count();

        return [
            'total_conversations' => $totalConversations,
            'resolved_by_bot' => $resolvedByBot,
            'escalated' => $escalated,
            'active' => $active,
            'bot_resolution_rate' => $totalConversations > 0 ? round(($resolvedByBot / $totalConversations) * 100, 2) : 0,
            'escalation_rate' => $totalConversations > 0 ? round(($escalated / $totalConversations) * 100, 2) : 0,
            'avg_confidence_score' => round($avgConfidence ?? 0, 2),
            'avg_satisfaction_rating' => round($avgSatisfaction ?? 0, 2),
            'positive_feedback' => $positiveFeedback,
            'negative_feedback' => $negativeFeedback,
            'total_feedback' => $positiveFeedback + $negativeFeedback,
        ];
    }
}