<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\NotificationService;
use App\Services\DeepLinkService;
use App\Services\FCMService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class NotificationController extends Controller
{
    protected $notificationService;
    protected $deepLinkService;
    protected $fcmService;

    public function __construct(
        NotificationService $notificationService,
        DeepLinkService $deepLinkService,
        FCMService $fcmService
    ) {
        $this->notificationService = $notificationService;
        $this->deepLinkService = $deepLinkService;
        $this->fcmService = $fcmService;
    }

    /**
     * Get user's notifications.
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        
        $limit = $request->input('limit', 50);
        $offset = $request->input('offset', 0);
        $status = $request->input('status'); // delivered, opened, clicked

        $notifications = $this->notificationService->getUserNotifications($user, $limit);

        if ($status) {
            $notifications = $notifications->filter(function ($notification) use ($status) {
                return $notification->deliveries->first()->status === $status;
            });
        }

        return response()->json([
            'success' => true,
            'data' => $notifications->map(function ($notification) {
                return [
                    'id' => $notification->id,
                    'title' => $notification->title,
                    'message' => $notification->message,
                    'deep_link_url' => $notification->deep_link_url,
                    'sent_at' => $notification->sent_at,
                    'status' => $notification->deliveries->first()->status ?? 'unknown',
                    'delivery_status' => $notification->deliveries->first()->status_label ?? 'Unknown'
                ];
            }),
            'total' => $notifications->count()
        ]);
    }

    /**
     * Get specific notification.
     */
    public function show($id)
    {
        $user = Auth::user();
        
        $notifications = $this->notificationService->getUserNotifications($user, 1);
        $notification = $notifications->firstWhere('id', $id);

        if (!$notification) {
            return response()->json([
                'success' => false,
                'message' => 'Notification not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'id' => $notification->id,
                'title' => $notification->title,
                'message' => $notification->message,
                'deep_link_url' => $notification->deep_link_url,
                'sent_at' => $notification->sent_at,
                'status' => $notification->deliveries->first()->status ?? 'unknown'
            ]
        ]);
    }

    /**
     * Mark notification as read.
     */
    public function markAsRead($id, Request $request)
    {
        $user = Auth::user();
        
        $notifications = $this->notificationService->getUserNotifications($user, 1);
        $notification = $notifications->firstWhere('id', $id);

        if (!$notification) {
            return response()->json([
                'success' => false,
                'message' => 'Notification not found'
            ], 404);
        }

        $this->notificationService->markAsOpened($user, $notification);

        return response()->json([
            'success' => true,
            'message' => 'Notification marked as read'
        ]);
    }

    /**
     * Mark notification as clicked.
     */
    public function markAsClicked($id, Request $request)
    {
        $user = Auth::user();
        
        $notifications = $this->notificationService->getUserNotifications($user, 1);
        $notification = $notifications->firstWhere('id', $id);

        if (!$notification) {
            return response()->json([
                'success' => false,
                'message' => 'Notification not found'
            ], 404);
        }

        $this->notificationService->markAsClicked($user, $notification);

        return response()->json([
            'success' => true,
            'message' => 'Notification marked as clicked'
        ]);
    }

    /**
     * Delete notification.
     */
    public function delete($id)
    {
        $user = Auth::user();
        
        $notifications = $this->notificationService->getUserNotifications($user, 1);
        $notification = $notifications->firstWhere('id', $id);

        if (!$notification) {
            return response()->json([
                'success' => false,
                'message' => 'Notification not found'
            ], 404);
        }

        // For now, we'll just mark as deleted in delivery record
        // In a real implementation, you might want to soft delete
        $delivery = $notification->deliveries->first();
        if ($delivery) {
            $delivery->update(['status' => 'deleted']);
        }

        return response()->json([
            'success' => true,
            'message' => 'Notification deleted'
        ]);
    }

    /**
     * Get user's notification preferences.
     */
    public function getPreferences()
    {
        $user = Auth::user();
        
        $preference = $user->notificationPreference;

        if (!$preference) {
            // Create default preferences if none exist
            $preference = $user->notificationPreference()->create([
                'enabled' => true,
                'plan_notifications' => true,
                'category_notifications' => true,
                'location_notifications' => true,
                'deep_link_enabled' => true,
                'blocked_categories' => [],
                'blocked_locations' => [],
                'quiet_hours_start' => null,
                'quiet_hours_end' => null,
            ]);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'enabled' => $preference->enabled,
                'plan_notifications' => $preference->plan_notifications,
                'category_notifications' => $preference->category_notifications,
                'location_notifications' => $preference->location_notifications,
                'deep_link_enabled' => $preference->deep_link_enabled,
                'blocked_categories' => $preference->blocked_categories ?? [],
                'blocked_locations' => $preference->blocked_locations ?? [],
                'quiet_hours_start' => $preference->quiet_hours_start,
                'quiet_hours_end' => $preference->quiet_hours_end,
            ]
        ]);
    }

    /**
     * Update user's notification preferences.
     */
    public function updatePreferences(Request $request)
    {
        $user = Auth::user();
        
        $validated = $request->validate([
            'enabled' => 'boolean',
            'plan_notifications' => 'boolean',
            'category_notifications' => 'boolean',
            'location_notifications' => 'boolean',
            'deep_link_enabled' => 'boolean',
            'blocked_categories' => 'array',
            'blocked_locations' => 'array',
            'quiet_hours_start' => 'nullable|date_format:H:i',
            'quiet_hours_end' => 'nullable|date_format:H:i',
        ]);

        $preference = $user->notificationPreference;

        if (!$preference) {
            $preference = $user->notificationPreference()->create($validated);
        } else {
            $preference->update($validated);
        }

        return response()->json([
            'success' => true,
            'message' => 'Notification preferences updated',
            'data' => [
                'enabled' => $preference->enabled,
                'plan_notifications' => $preference->plan_notifications,
                'category_notifications' => $preference->category_notifications,
                'location_notifications' => $preference->location_notifications,
                'deep_link_enabled' => $preference->deep_link_enabled,
                'blocked_categories' => $preference->blocked_categories ?? [],
                'blocked_locations' => $preference->blocked_locations ?? [],
                'quiet_hours_start' => $preference->quiet_hours_start,
                'quiet_hours_end' => $preference->quiet_hours_end,
            ]
        ]);
    }

    /**
     * Test deep link generation.
     */
    public function testDeepLink(Request $request)
    {
        $validated = $request->validate([
            'screen' => 'required|string',
            'parameters' => 'array',
        ]);

        $deepLink = $this->deepLinkService->generateDeepLink(
            $validated['screen'],
            $validated['parameters'] ?? []
        );

        return response()->json([
            'success' => true,
            'data' => [
                'deep_link' => $deepLink,
                'parsed' => $this->deepLinkService->parseDeepLink($deepLink),
                'supported_screens' => $this->deepLinkService->getSupportedScreens()
            ]
        ]);
    }

    /**
     * Get notification statistics for user.
     */
    public function getStats()
    {
        $user = Auth::user();
        
        // Get user's notifications with deliveries
        $notifications = $this->notificationService->getUserNotifications($user, 1000);

        $stats = [
            'total_received' => $notifications->count(),
            'delivered' => $notifications->filter(function ($n) {
                return $n->deliveries->first()->wasDelivered();
            })->count(),
            'opened' => $notifications->filter(function ($n) {
                return $n->deliveries->first()->wasOpened();
            })->count(),
            'clicked' => $notifications->filter(function ($n) {
                return $n->deliveries->first()->wasClicked();
            })->count(),
            'delivery_rate' => 0,
            'open_rate' => 0,
            'click_rate' => 0
        ];

        if ($stats['total_received'] > 0) {
            $stats['delivery_rate'] = round(($stats['delivered'] / $stats['total_received']) * 100, 2);
            $stats['open_rate'] = $stats['delivered'] > 0 ? round(($stats['opened'] / $stats['delivered']) * 100, 2) : 0;
            $stats['click_rate'] = $stats['delivered'] > 0 ? round(($stats['clicked'] / $stats['delivered']) * 100, 2) : 0;
        }

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

    /**
     * Register FCM device token
     */
    public function registerDeviceToken(Request $request)
    {
        $validated = $request->validate([
            'device_token' => 'required|string',
            'platform' => 'required|in:android,ios,web',
        ]);

        $user = Auth::user();

        // Store the device token (you might want to create a device_tokens table)
        // For now, we'll store it in the user table or session
        $user->update([
            'fcm_token' => $validated['device_token'],
            'device_platform' => $validated['platform'],
        ]);

        // Validate the token with FCM
        $isValid = $this->fcmService->validateToken($validated['device_token']);

        return response()->json([
            'success' => true,
            'message' => 'Device token registered successfully',
            'data' => [
                'token_valid' => $isValid,
            ]
        ]);
    }

    /**
     * Send test notification
     */
    public function sendTestNotification(Request $request)
    {
        $user = Auth::user();

        if (!$user->fcm_token) {
            return response()->json([
                'success' => false,
                'message' => 'No device token registered'
            ], 400);
        }

        $result = $this->fcmService->sendToDevice(
            $user->fcm_token,
            'Test Notification',
            'This is a test notification from CLXpro!',
            [
                'type' => 'test',
                'timestamp' => now()->toIso8601String(),
            ]
        );

        return response()->json([
            'success' => $result !== false,
            'message' => $result ? 'Test notification sent successfully' : 'Failed to send notification',
            'data' => $result
        ]);
    }
}
