<?php

namespace App\Http\Controllers\Api;

use App\Services\ClarityService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Dedoc\Scramble\Attributes\HeaderParameter;

/**
 * @tags 12. Analytics & Tracking
 */
class ClarityController extends ApiController
{
    protected $clarityService;

    public function __construct(ClarityService $clarityService)
    {
        $this->clarityService = $clarityService;
    }

    /**
     * Track Page View
     * 
     * Track when user visits a page/screen in the mobile app.
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication (optional)', required: false, type: 'string')]
    public function trackPageView(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'page_url' => 'required|string|max:500',
            'page_title' => 'nullable|string|max:200',
            'session_id' => 'nullable|string|max:100',
            'platform' => 'required|in:android,ios',
            'device_type' => 'nullable|string|max:50',
            'app_version' => 'nullable|string|max:20',
            'custom_data' => 'nullable|array',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $user = $request->user();
        $data = $request->all();
        
        // Add user info if authenticated
        if ($user) {
            $data['user_id'] = $user->id;
            $data['user_type'] = $user->is_guest ? 'guest' : 'registered';
        }

        // Add locale info
        $locale = $this->getCurrentLocale($request);
        $data['custom_data'] = array_merge($data['custom_data'] ?? [], [
            'country_id' => $locale['country_id'],
            'language_id' => $locale['language_id'],
            'locale_id' => $locale['locale_id'],
        ]);

        $result = $this->clarityService->trackPageView($data);

        if ($result['success']) {
            return $this->successResponse([
                'tracked' => true,
                'session_id' => $result['session_id'],
            ], 'Page view tracked successfully');
        }

        return $this->errorResponse('Failed to track page view', 500);
    }

    /**
     * Track Custom Event
     * 
     * Track custom events like offer clicks, store follows, etc.
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication (optional)', required: false, type: 'string')]
    public function trackEvent(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'event_name' => 'required|string|max:100',
            'event_data' => 'nullable|array',
            'session_id' => 'nullable|string|max:100',
            'platform' => 'required|in:android,ios',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $user = $request->user();
        $data = $request->all();

        // Add user info if authenticated
        if ($user) {
            $data['user_id'] = $user->id;
        }

        // Add locale info to event data
        $locale = $this->getCurrentLocale($request);
        $data['event_data'] = array_merge($data['event_data'] ?? [], [
            'country_id' => $locale['country_id'],
            'language_id' => $locale['language_id'],
        ]);

        $result = $this->clarityService->trackEvent($data['event_name'], $data);

        if ($result['success']) {
            return $this->successResponse([
                'tracked' => true,
                'event_id' => $result['event_id'] ?? null,
            ], 'Event tracked successfully');
        }

        return $this->errorResponse('Failed to track event', 500);
    }

    /**
     * Track User Interaction
     * 
     * Track user interactions like taps, scrolls, swipes.
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication (optional)', required: false, type: 'string')]
    public function trackInteraction(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|in:tap,scroll,swipe,long_press,double_tap',
            'session_id' => 'required|string|max:100',
            'element_id' => 'nullable|string|max:100',
            'element_class' => 'nullable|string|max:100',
            'coordinates' => 'nullable|array',
            'coordinates.x' => 'nullable|numeric',
            'coordinates.y' => 'nullable|numeric',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $result = $this->clarityService->trackInteraction($request->all());

        if ($result['success']) {
            return $this->successResponse([
                'tracked' => true,
            ], 'Interaction tracked successfully');
        }

        return $this->errorResponse('Failed to track interaction', 500);
    }

    /**
     * Track Offer Usage
     * 
     * Track when user uses/clicks on an offer.
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication (optional)', required: false, type: 'string')]
    public function trackOfferUsage(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'offer_id' => 'required|exists:offers,id',
            'action' => 'required|in:view,click,copy_code,share,favorite',
            'session_id' => 'nullable|string|max:100',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $offerId = $request->input('offer_id');
        $action = $request->input('action');
        $user = $request->user();

        // Get offer details for tracking
        $offer = \App\Models\Offer::with(['countryStore.store', 'brand'])->find($offerId);
        
        $eventData = [
            'offer_id' => $offerId,
            'action' => $action,
            'store_id' => $offer->countryStore->store_id,
            'brand_id' => $offer->brand_id,
            'offer_type' => $offer->type,
            'discount_value' => $offer->discount_value,
        ];

        $data = [
            'event_data' => $eventData,
            'session_id' => $request->input('session_id'),
            'platform' => $request->input('platform', 'mobile'),
        ];

        if ($user) {
            $data['user_id'] = $user->id;
        }

        // Track with Clarity
        $result = $this->clarityService->trackEvent("offer_{$action}", $data);

        // Also update offer statistics in database
        if ($action === 'view') {
            $offer->incrementViews();
        } elseif ($action === 'click') {
            $offer->incrementUses();
        }

        return $this->successResponse([
            'tracked' => true,
            'offer_id' => $offerId,
            'action' => $action,
        ], 'Offer usage tracked successfully');
    }

    /**
     * Track Store Follow
     * 
     * Track when user follows/unfollows a store.
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication (optional)', required: false, type: 'string')]
    public function trackStoreFollow(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required|exists:country_store,id',
            'action' => 'required|in:follow,unfollow',
            'session_id' => 'nullable|string|max:100',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $storeId = $request->input('store_id');
        $action = $request->input('action');
        $user = $request->user();

        $data = [
            'event_data' => [
                'country_store_id' => $storeId,
                'action' => $action,
            ],
            'session_id' => $request->input('session_id'),
            'platform' => $request->input('platform', 'mobile'),
        ];

        if ($user) {
            $data['user_id'] = $user->id;
        }

        $result = $this->clarityService->trackEvent("store_{$action}", $data);

        return $this->successResponse([
            'tracked' => true,
            'store_id' => $storeId,
            'action' => $action,
        ], 'Store follow tracked successfully');
    }

    /**
     * Get Analytics Data
     * 
     * Get analytics data for admin panel (basic data from local storage).
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication', required: true, type: 'string')]
    public function getAnalytics(Request $request): JsonResponse
    {
        // Only allow admin users
        $user = $request->user();
        if (!$user || $user->role !== 'admin') {
            return $this->errorResponse('Unauthorized access', 403);
        }

        $validator = Validator::make($request->all(), [
            'start_date' => 'required|date|before_or_equal:today',
            'end_date' => 'required|date|after_or_equal:start_date|before_or_equal:today',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        $analytics = $this->clarityService->getAnalytics($startDate, $endDate);

        if ($analytics['success']) {
            return $this->successResponse($analytics['data'], 'Analytics data retrieved successfully');
        }

        return $this->errorResponse('Failed to retrieve analytics', 500);
    }

    /**
     * Get Session Statistics
     * 
     * Get basic session statistics for dashboard.
     */
    #[HeaderParameter('Authorization', 'Bearer {token} for authentication', required: true, type: 'string')]
    public function getSessionStats(Request $request): JsonResponse
    {
        $user = $request->user();
        if (!$user || $user->role !== 'admin') {
            return $this->errorResponse('Unauthorized access', 403);
        }

        $validator = Validator::make($request->all(), [
            'period' => 'nullable|in:today,yesterday,last_7_days,last_30_days',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorResponse($validator->errors());
        }

        $period = $request->input('period', 'today');

        // Calculate date range based on period
        switch ($period) {
            case 'today':
                $startDate = now()->format('Y-m-d');
                $endDate = now()->format('Y-m-d');
                break;
            case 'yesterday':
                $startDate = now()->subDay()->format('Y-m-d');
                $endDate = now()->subDay()->format('Y-m-d');
                break;
            case 'last_7_days':
                $startDate = now()->subDays(7)->format('Y-m-d');
                $endDate = now()->format('Y-m-d');
                break;
            case 'last_30_days':
                $startDate = now()->subDays(30)->format('Y-m-d');
                $endDate = now()->format('Y-m-d');
                break;
        }

        $analytics = $this->clarityService->getAnalytics($startDate, $endDate);

        if ($analytics['success']) {
            $data = $analytics['data'];
            
            return $this->successResponse([
                'period' => $period,
                'date_range' => [
                    'start' => $startDate,
                    'end' => $endDate,
                ],
                'stats' => [
                    'total_page_views' => count($data['page_views']),
                    'total_events' => count($data['events']),
                    'total_sessions' => $data['sessions']['total_sessions'],
                    'unique_sessions' => count($data['sessions']['unique_sessions']),
                ],
                'top_pages' => $this->getTopPages($data['page_views']),
                'top_events' => $this->getTopEvents($data['events']),
            ], 'Session statistics retrieved successfully');
        }

        return $this->errorResponse('Failed to retrieve session statistics', 500);
    }

    /**
     * Get top visited pages
     */
    private function getTopPages($pageViews, $limit = 10)
    {
        $pages = collect($pageViews)
            ->groupBy('page_url')
            ->map(function ($group) {
                return [
                    'url' => $group->first()['page_url'],
                    'title' => $group->first()['page_title'] ?? '',
                    'views' => $group->count(),
                ];
            })
            ->sortByDesc('views')
            ->take($limit)
            ->values();

        return $pages;
    }

    /**
     * Get top events
     */
    private function getTopEvents($events, $limit = 10)
    {
        $topEvents = collect($events)
            ->groupBy('event_name')
            ->map(function ($group, $eventName) {
                return [
                    'event_name' => $eventName,
                    'count' => $group->count(),
                ];
            })
            ->sortByDesc('count')
            ->take($limit)
            ->values();

        return $topEvents;
    }
}