<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Models\Streamer;
use App\Traits\RefreshesSettingsCache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class StreamerController extends Controller
{
    use RefreshesSettingsCache;

    public function index(Request $request)
    {
        $query = Streamer::with('user');

        // Status filter
        if ($request->has('status') && $request->status) {
            $query->where('status', $request->status);
        }

        // Search functionality
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('code', 'like', "%{$search}%")
                    ->orWhere('id', 'like', "%{$search}%")
                    ->orWhere('discord_id', 'like', "%{$search}%")
                    ->orWhereHas('user', function ($userQuery) use ($search) {
                        $userQuery->where('name', 'like', "%{$search}%")
                            ->orWhere('truename', 'like', "%{$search}%");
                    });
            });
        }

        $streamers = $query->orderBy('created_at', 'desc')->paginate(20);

        // Get streamer settings
        $settings = $this->getStreamerSettings();

        return Inertia::render('admin/manage/streamer/index', [
            'streamers' => $streamers,
            'filters' => $request->only(['search', 'status']),
            'settings' => $settings,
        ]);
    }

    /**
     * Get streamer settings from database
     */
    private function getStreamerSettings(): array
    {
        $discordWebhook = DB::table('settings')->where('key', 'streamer_discord_webhook_url')->first();
        $defaultGoldReward = DB::table('settings')->where('key', 'streamer_default_gold_reward')->first();

        return [
            'discord_webhook_url' => $discordWebhook?->value ?? '',
            'default_gold_reward' => (int) ($defaultGoldReward?->value ?? 100),
        ];
    }

    /**
     * Update streamer settings
     */
    public function updateSettings(Request $request)
    {
        $validated = $request->validate([
            'discord_webhook_url' => 'nullable|string|url',
            'default_gold_reward' => 'required|integer|min:1|max:100000',
        ]);

        DB::table('settings')->updateOrInsert(
            ['key' => 'streamer_discord_webhook_url'],
            ['value' => $validated['discord_webhook_url'] ?? '', 'updated_at' => now()]
        );

        DB::table('settings')->updateOrInsert(
            ['key' => 'streamer_default_gold_reward'],
            ['value' => (string) $validated['default_gold_reward'], 'updated_at' => now()]
        );

        $this->refreshSettingsCache();

        return back()->with('success', 'Streamer settings updated successfully.');
    }

    public function approve(Request $request, $id)
    {
        $streamer = Streamer::findOrFail($id);

        if ($streamer->status !== 'pending') {
            return back()->withErrors(['message' => 'Only pending requests can be approved.']);
        }

        $validated = $request->validate([
            'percentage' => 'required|numeric|min:0|max:100',
        ]);

        $streamer->update([
            'status' => 'approved',
            'percentage' => $validated['percentage'],
            'is_active' => true,
            'processed_at' => now(),
        ]);

        return back()->with('success', 'Streamer request approved successfully.');
    }

    public function reject($id)
    {
        $streamer = Streamer::findOrFail($id);

        if ($streamer->status !== 'pending') {
            return back()->withErrors(['message' => 'Only pending requests can be rejected.']);
        }

        $streamer->update([
            'status' => 'rejected',
            'is_active' => false,
            'processed_at' => now(),
        ]);

        return back()->with('success', 'Streamer request rejected.');
    }

    public function update(Request $request, $id)
    {
        $streamer = Streamer::findOrFail($id);

        $request->validate([
            'percentage' => 'required|numeric|min:0|max:100',
            'discord_id' => 'nullable|string|max:255',
        ]);

        $streamer->update([
            'percentage' => $request->percentage,
            'discord_id' => $request->discord_id,
        ]);

        return back()->with('success', 'Streamer updated successfully.');
    }

    public function destroy($id)
    {
        $streamer = Streamer::findOrFail($id);
        $streamer->delete();

        return back()->with('success', 'Streamer deleted successfully.');
    }

    public function toggleActive($id)
    {
        $streamer = Streamer::findOrFail($id);
        $streamer->update([
            'is_active' => ! $streamer->is_active,
        ]);

        return back()->with('success', 'Streamer status updated successfully.');
    }

    /**
     * Get all streamer uploads with optional filtering
     */
    public function uploads(Request $request)
    {
        $query = \App\Models\StreamerUpload::with(['streamer.user', 'approvedBy']);

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

        // Filter by streamer
        if ($request->has('streamer_id') && $request->streamer_id) {
            $query->where('streamer_id', $request->streamer_id);
        }

        $uploads = $query->orderBy('created_at', 'desc')->paginate(20);

        return response()->json([
            'uploads' => $uploads->map(function ($upload) {
                return [
                    'id' => $upload->id,
                    'streamer' => [
                        'id' => $upload->streamer->id,
                        'code' => $upload->streamer->code,
                        'user_name' => $upload->streamer->user->truename ?? $upload->streamer->user->name,
                    ],
                    'image_url' => $upload->image_url,
                    'status' => $upload->status,
                    'gold_reward' => $upload->gold_reward,
                    'admin_notes' => $upload->admin_notes,
                    'approved_by_name' => $upload->approvedBy?->name,
                    'created_at' => $upload->created_at->format('Y-m-d H:i:s'),
                    'approved_at' => $upload->approved_at?->format('Y-m-d H:i:s'),
                ];
            }),
            'pagination' => [
                'current_page' => $uploads->currentPage(),
                'last_page' => $uploads->lastPage(),
                'per_page' => $uploads->perPage(),
                'total' => $uploads->total(),
            ],
        ]);
    }

    /**
     * Approve a streamer upload and award gold
     */
    public function approveUpload(Request $request, $id)
    {
        $validated = $request->validate([
            'gold_reward' => 'required|integer|min:1|max:100000',
        ]);

        $upload = \App\Models\StreamerUpload::with('streamer.user')->findOrFail($id);

        if ($upload->status !== 'pending') {
            return back()->withErrors(['message' => 'Only pending uploads can be approved.']);
        }

        $upload->approve($validated['gold_reward'], auth()->user()->ID);

        return back()->with('success', 'Upload approved and gold awarded successfully.');
    }

    /**
     * Reject a streamer upload
     */
    public function rejectUpload(Request $request, $id)
    {
        $validated = $request->validate([
            'admin_notes' => 'nullable|string|max:500',
        ]);

        $upload = \App\Models\StreamerUpload::findOrFail($id);

        if ($upload->status !== 'pending') {
            return back()->withErrors(['message' => 'Only pending uploads can be rejected.']);
        }

        $upload->reject(auth()->user()->ID, $validated['admin_notes'] ?? null);

        // Delete Discord notification message if exists
        $this->deleteDiscordMessage($upload);

        return back()->with('success', 'Upload rejected successfully.');
    }

    /**
     * Delete Discord notification message
     */
    private function deleteDiscordMessage(\App\Models\StreamerUpload $upload): void
    {
        if (! $upload->discord_message_id) {
            return;
        }

        try {
            $webhookUrl = DB::table('settings')
                ->where('key', 'streamer_discord_webhook_url')
                ->first()?->value;

            if (empty($webhookUrl)) {
                return;
            }

            // Append /messages/{messageId} to webhook URL to delete the message
            $deleteUrl = "{$webhookUrl}/messages/{$upload->discord_message_id}";

            \Illuminate\Support\Facades\Http::delete($deleteUrl);
        } catch (\Exception $e) {
            \Log::warning('Failed to delete Discord notification for streamer upload', [
                'upload_id' => $upload->id,
                'message_id' => $upload->discord_message_id,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
