<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\NotificationService;
use App\Services\FirebaseService;
use App\Services\DeepLinkService;
use App\Models\Notification;
use App\Models\User;
use App\Models\Ad;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;

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

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



    /**
     * Search users for targeting/deeplinking.
     */
    public function searchUsers(Request $request)
    {
        $query = $request->get('q');
        if (strlen($query) < 2) return response()->json([]);

        $users = User::where('name', 'like', "%{$query}%")
                    ->orWhere('email', 'like', "%{$query}%")
                    ->limit(20)
                    ->get(['id', 'name', 'email']);
        return response()->json($users);
    }

    /**
     * Search ads for deeplinking.
     */
    public function searchAds(Request $request)
    {
        $query = $request->get('q');
        if (strlen($query) < 2) return response()->json([]);

        $ads = Ad::where('title', 'like', "%{$query}%")
                ->limit(20)
                ->get(['id', 'title']);
        return response()->json($ads);
    }

    /**
     * Search cities for location targeting.
     */
    public function searchCities(Request $request)
    {
        $query = $request->get('q');
        if (strlen($query) < 2) return response()->json([]);

        $cities = User::whereNotNull('city')
                    ->where('city', 'like', "%{$query}%")
                    ->distinct()
                    ->limit(20)
                    ->pluck('city')
                    ->map(fn($city) => ['value' => $city, 'label' => $city]);
        
        return response()->json($cities);
    }

    /**
     * Search states for location targeting.
     */
    public function searchStates(Request $request)
    {
        $query = $request->get('q');
        if (strlen($query) < 2) return response()->json([]);

        $states = User::whereNotNull('state')
                    ->where('state', 'like', "%{$query}%")
                    ->distinct()
                    ->limit(20)
                    ->pluck('state')
                    ->map(fn($state) => ['value' => $state, 'label' => $state]);
        
        return response()->json($states);
    }

    /**
     * Search countries for location targeting.
     */
    public function searchCountries(Request $request)
    {
        $query = $request->get('q');
        if (strlen($query) < 2) return response()->json([]);

        $countries = User::whereNotNull('country')
                    ->where('country', 'like', "%{$query}%")
                    ->distinct()
                    ->limit(20)
                    ->pluck('country')
                    ->map(fn($country) => ['value' => $country, 'label' => $country]);
        
        return response()->json($countries);
    }

    /**
     * Display a listing of notifications.
     */
    public function index(Request $request)
    {
        $query = Notification::with(['deliveries'])
            ->orderBy('created_at', 'desc');

        // Filter by status
        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }

        // Filter by target type
        if ($targetType = $request->input('target_type')) {
            $query->where('target_type', $targetType);
        }

        // Search by title
        if ($search = $request->input('search')) {
            $query->where('title', 'like', "%{$search}%")
                  ->orWhere('message', 'like', "%{$search}%");
        }

        $notifications = $query->paginate(20);

        return view('admin.notifications.index', [
            'notifications' => $notifications,
            'firebaseConfigured' => $this->firebaseService->validateConfiguration()
        ]);
    }

    /**
     * Show the form for creating a new notification.
     */
    public function create()
    {
        $users = User::limit(100)->get();
        $premiumPlans = ['standard', 'VIP Buyer', 'VIP Seller', 'VIP Pro'];
        
        return view('admin.notifications.create', [
            'users' => $users,
            'premiumPlans' => $premiumPlans,
            'firebaseConfigured' => $this->firebaseService->validateConfiguration(),
            'deepLinkExamples' => $this->getDeepLinkExamples()
        ]);
    }

    /**
     * Store a newly created notification in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'deep_link_url' => 'nullable|string|max:500',
            'target_type' => 'required|in:all,single_user,premium_plan,custom',
            'target_value' => 'nullable|array',
            'scheduled_at' => 'nullable|date|after:now',
            'send_now' => 'boolean',
            'image' => 'nullable|image|max:2048' // Max 2MB
        ]);

        try {
            $imageUrl = null;
            if ($request->hasFile('image')) {
                $path = $request->file('image')->store('notifications', 'public');
                $imageUrl = Storage::url($path);
            }

            $notification = $this->notificationService->createNotification([
                'title' => $validated['title'],
                'message' => $validated['message'],
                'deep_link_url' => $validated['deep_link_url'],
                'target_type' => $validated['target_type'],
                'target_value' => $validated['target_value'] ?? null,
                'scheduled_at' => $validated['scheduled_at'] ?? null,
                'image' => $imageUrl
            ]);

            if ($validated['send_now'] ?? false) {
                $this->notificationService->sendNotification($notification);
                return redirect()->route('admin.notifications.index')
                    ->with('success', 'Notification created and sent successfully!');
            } else {
                return redirect()->route('admin.notifications.index')
                    ->with('success', 'Notification created successfully!');
            }
        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to create notification: ' . $e->getMessage()]);
        }
    }

    /**
     * Display the specified notification.
     */
    public function show(Notification $notification)
    {
        $notification->load(['deliveries.user']);
        $stats = $this->notificationService->getNotificationStats($notification);

        return view('admin.notifications.show', [
            'notification' => $notification,
            'stats' => $stats
        ]);
    }

    /**
     * Show the form for editing the specified notification.
     */
    public function edit(Notification $notification)
    {
        $users = User::limit(100)->get();
        $premiumPlans = ['standard', 'VIP Buyer', 'VIP Seller', 'VIP Pro'];

        return view('admin.notifications.edit', [
            'notification' => $notification,
            'users' => $users,
            'premiumPlans' => $premiumPlans,
            'firebaseConfigured' => $this->firebaseService->validateConfiguration(),
            'deepLinkExamples' => $this->getDeepLinkExamples()
        ]);
    }

    /**
     * Update the specified notification in storage.
     */
    public function update(Request $request, Notification $notification)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'deep_link_url' => 'nullable|string|max:500',
            'target_type' => 'required|in:all,single_user,premium_plan,custom',
            'target_value' => 'nullable|array',
            'scheduled_at' => 'nullable|date',
            'image' => 'nullable|image|max:2048'
        ]);

        try {
            $data = [
                'title' => $validated['title'],
                'message' => $validated['message'],
                'deep_link_url' => $validated['deep_link_url'],
                'target_type' => $validated['target_type'],
                'target_value' => $validated['target_value'] ?? null,
                'scheduled_at' => $validated['scheduled_at'] ?? null,
            ];

            if ($request->hasFile('image')) {
                $path = $request->file('image')->store('notifications', 'public');
                $data['image'] = Storage::url($path);
            }

            $notification->update($data);

            return redirect()->route('admin.notifications.index')
                ->with('success', 'Notification updated successfully!');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to update notification: ' . $e->getMessage()]);
        }
    }

    /**
     * Remove the specified notification from storage.
     */
    public function destroy(Notification $notification)
    {
        try {
            $notification->delete();
            return redirect()->route('admin.notifications.index')
                ->with('success', 'Notification deleted successfully!');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to delete notification: ' . $e->getMessage()]);
        }
    }

    /**
     * Send a notification immediately.
     */
    public function send(Notification $notification)
    {
        try {
            if ($this->notificationService->sendNotification($notification)) {
                return redirect()->route('admin.notifications.show', $notification)
                    ->with('success', 'Notification sent successfully!');
            } else {
                return back()->withErrors(['error' => 'Failed to send notification.']);
            }
        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to send notification: ' . $e->getMessage()]);
        }
    }

    /**
     * Show scheduled notifications.
     */
    public function scheduled(Request $request)
    {
        $notifications = Notification::where('status', 'scheduled')
            ->orderBy('scheduled_at', 'asc')
            ->paginate(20);

        return view('admin.notifications.scheduled', [
            'notifications' => $notifications
        ]);
    }

    /**
     * Show sent notifications.
     */
    public function sent(Request $request)
    {
        $notifications = Notification::whereIn('status', ['sent', 'failed'])
            ->orderBy('sent_at', 'desc')
            ->paginate(20);

        return view('admin.notifications.sent', [
            'notifications' => $notifications
        ]);
    }

    /**
     * Show notification analytics.
     */
    public function analytics(Notification $notification)
    {
        $notification->load(['deliveries.user']);
        $stats = $this->notificationService->getNotificationStats($notification);

        // Get delivery breakdown by status
        $deliveryBreakdown = $notification->deliveries()
            ->selectRaw('status, COUNT(*) as count')
            ->groupBy('status')
            ->get();

        // Get user engagement by plan type
        $engagementByPlan = $notification->deliveries()
            ->join('users', 'notification_deliveries.user_id', '=', 'users.id')
            ->join('subscriptions', 'users.id', '=', 'subscriptions.user_id')
            ->where('subscriptions.status', 'active')
            ->selectRaw('subscriptions.plan_type, COUNT(*) as count, SUM(CASE WHEN notification_deliveries.status = "clicked" THEN 1 ELSE 0 END) as clicks')
            ->groupBy('subscriptions.plan_type')
            ->get();

        return view('admin.notifications.analytics', [
            'notification' => $notification,
            'stats' => $stats,
            'deliveryBreakdown' => $deliveryBreakdown,
            'engagementByPlan' => $engagementByPlan
        ]);
    }

    /**
     * Get example deep links for the UI.
     */
    /**
     * Search blogs for deeplinking.
     */
    public function searchBlogs(Request $request)
    {
        $query = $request->get('q');
        if (strlen($query) < 2) return response()->json([]);

        // Assuming Blog model exists and has title and slug
        $blogs = \App\Models\Blog::where('title', 'like', "%{$query}%")
                ->limit(20)
                ->get(['id', 'title', 'slug']);
        return response()->json($blogs);
    }

    /**
     * Get example deep links for the UI.
     */
    protected function getDeepLinkExamples()
    {
        return [
            'ad-details' => $this->deepLinkService->generateAdDeepLink(123),
            'user-profile' => $this->deepLinkService->generateUserProfileDeepLink(456),
            'category' => $this->deepLinkService->generateCategoryDeepLink(1, 'Mumbai'),
            'chat' => $this->deepLinkService->generateChatDeepLink(789),
            'premium-plans' => $this->deepLinkService->generatePremiumPlansDeepLink('VIP Pro'),
            'notifications' => $this->deepLinkService->generateNotificationsDeepLink(),
            'banner-promotion' => $this->deepLinkService->generateBannerPromotionDeepLink(),
            'post-ad' => $this->deepLinkService->generatePostAdDeepLink(),
            'packages' => $this->deepLinkService->generatePackagesDeepLink(),
            'analytics' => $this->deepLinkService->generateAnalyticsDeepLink(),
            'trust-score' => $this->deepLinkService->generateTrustScoreDeepLink(),
            'my-reviews' => $this->deepLinkService->generateMyReviewsDeepLink(),
            'favorites' => $this->deepLinkService->generateFavoritesDeepLink(),
            'my-plan' => $this->deepLinkService->generateMyPlanDeepLink(),
            'blogs' => $this->deepLinkService->generateBlogsDeepLink(),
            'blog-detail' => $this->deepLinkService->generateBlogDetailDeepLink('example-blog-slug'),
        ];
    }

    /**
     * Test Firebase configuration.
     */
    public function testFirebase()
    {
        $status = $this->firebaseService->getConfigurationStatus();
        
        return response()->json([
            'success' => true,
            'data' => $status
        ]);
    }

    /**
     * Get Firebase configuration status.
     */
    public function firebaseStatus()
    {
        return response()->json([
            'success' => true,
            'configured' => $this->firebaseService->validateConfiguration(),
            'status' => $this->firebaseService->getConfigurationStatus()
        ]);
    }
}
