<?php

namespace App\Http\Controllers\Meet;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Meet\Concerns\BuildsMeetIndexPage;
use App\Http\Controllers\Meet\Concerns\ScopesToAccount;
use App\Models\Room;
use App\Services\Meet\CalendarService;
use App\Services\Meet\InvitationService;
use App\Services\Meet\RoomService;
use App\Services\Meet\SessionService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class WebinarController extends Controller
{
    use BuildsMeetIndexPage, ScopesToAccount;

    public function __construct(
        protected RoomService $rooms,
        protected SessionService $sessions,
        protected InvitationService $invitations,
        protected CalendarService $calendar,
    ) {}

    public function index(Request $request): View
    {
        $this->authorizeAbility($request, 'meetings.view');
        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);

        $query = Room::owned($owner)
            ->where('organization_id', $organization->id)
            ->where('type', 'webinar');

        $this->scopeToBranch($request, $query);

        $webinars = $query->orderByDesc('scheduled_at')->paginate(20);

        $stats = $this->meetIndexStats($request, $query, 'Webinars', 'Live now');
        $items = $this->meetIndexItems($webinars, fn (Room $room) => route('meet.webinars.show', $room));

        return view('meet.webinars.index', compact('webinars', 'organization', 'stats', 'items'));
    }

    public function create(Request $request): View
    {
        $this->authorizeAbility($request, 'meetings.create');
        $organization = $this->organization($request);

        return view('meet.webinars.create', [
            'organization' => $organization,
            'timezones' => timezone_identifiers_list(),
            'defaultSettings' => config('meet.default_settings'),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $this->authorizeAbility($request, 'meetings.create');
        $organization = $this->organization($request);

        $validated = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:2000'],
            'scheduled_at' => ['required', 'date'],
            'duration_minutes' => ['nullable', 'integer', 'min:15', 'max:480'],
            'timezone' => ['nullable', 'timezone'],
            'passcode' => ['nullable', 'string', 'max:20'],
            'waiting_room' => ['sometimes', 'boolean'],
            'join_before_host' => ['sometimes', 'boolean'],
            'mute_on_join' => ['sometimes', 'boolean'],
            'auto_record' => ['sometimes', 'boolean'],
            'live_captions' => ['sometimes', 'boolean'],
            'panel_discussions' => ['sometimes', 'boolean'],
        ]);

        $settings = [
            'waiting_room' => $request->boolean('waiting_room', true),
            'join_before_host' => $request->boolean('join_before_host'),
            'mute_on_join' => $request->boolean('mute_on_join', true),
            'auto_record' => $request->boolean('auto_record'),
            'live_captions' => $request->boolean('live_captions'),
            'panel_discussions' => $request->boolean('panel_discussions'),
            'stage_layout' => 'plenary',
            'panels' => [],
            'stage_mode' => true,
        ];

        $data = array_merge($validated, [
            'settings' => $settings,
            'timezone' => $validated['timezone'] ?? $organization->timezone,
            'type' => 'webinar',
            'status' => 'scheduled',
        ]);

        $room = $this->rooms->create($request->user(), $organization, $data);

        if ($room->scheduled_at) {
            $this->calendar->syncRoomCreated($room, $request->user());
        }

        return redirect()->route('meet.webinars.show', $room)->with('success', 'Webinar created.');
    }

    public function show(Request $request, Room $room): View
    {
        $this->authorizeAbility($request, 'meetings.view');
        $this->authorizeOwner($request, $room);
        abort_unless($room->isWebinar(), 404);

        $room->load(['sessions.participants', 'invitations', 'sessions.recordings', 'sessions.aiSummaries', 'sessionFiles']);

        return view('meet.webinars.show', compact('room'));
    }

    public function start(Request $request, Room $room): RedirectResponse
    {
        $this->authorizeAbility($request, 'meetings.host');
        $this->authorizeOwner($request, $room);
        abort_unless($room->isWebinar(), 404);

        if ($room->status === 'cancelled') {
            return redirect()->route('meet.webinars.show', $room)
                ->withErrors(['start' => 'Webinar was cancelled.']);
        }

        $session = $this->sessions->start($room, $request->user());

        $participant = $this->sessions->joinedParticipantForUser($session, $request->user());
        abort_unless($participant, 500, 'Unable to join as host.');

        $this->sessions->rememberParticipantSession($request, $participant, $session);

        return redirect()->route('meet.room', $session);
    }

    public function updateSettings(Request $request, Room $room): RedirectResponse
    {
        $this->authorizeAbility($request, 'meetings.manage');
        $this->authorizeOwner($request, $room);
        abort_unless($room->isWebinar(), 404);

        $request->validate([
            'panel_discussions' => ['sometimes', 'boolean'],
        ]);

        if ($request->has('panel_discussions')) {
            $settings = array_merge($room->settings ?? [], [
                'panel_discussions' => $request->boolean('panel_discussions'),
            ]);
            $room->update(['settings' => $settings]);
        }

        return redirect()->route('meet.webinars.show', $room)->with('success', 'Webinar settings updated.');
    }
}
