<?php

namespace App\Livewire\Facilities;

use App\Domain\Facility\Enums\ReservationStatus;
use App\Domain\Facility\Models\Facility;
use App\Domain\Facility\Models\SpaceReservation;
use Carbon\Carbon;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تفاصيل المنشأة')]
class FacilityShow extends Component
{
    public Facility $facility;
    public string $activeTab = 'overview';

    public function mount(Facility $facility): void
    {
        $this->authorize('facilities.list');

        $this->facility = $facility->load([
            'branch',
            'layouts.segments',
            'reservations' => fn ($q) => $q->where('status', '!=', ReservationStatus::Cancelled)
                ->where('reservation_date', '>=', now()->toDateString())
                ->orderBy('reservation_date')
                ->orderBy('start_time'),
            'creator',
        ]);
    }

    public function cancelReservation(int $id): void
    {
        $this->authorize('facilities.update');

        $reservation = SpaceReservation::where('facility_id', $this->facility->id)
            ->where('id', $id)
            ->firstOrFail();

        $reservation->update([
            'status' => ReservationStatus::Cancelled,
            'cancelled_by' => auth()->id(),
            'cancelled_at' => now(),
        ]);

        session()->flash('success', __('تم إلغاء الحجز بنجاح'));
    }

    public function render()
    {
        $today = Carbon::today();
        $todayString = $today->toDateString();

        // KPI calculations
        $totalLayouts = $this->facility->layouts->count();
        $totalSegments = $this->facility->layouts->sum(fn ($layout) => $layout->segments->count());

        $todayReservations = SpaceReservation::where('facility_id', $this->facility->id)
            ->where('reservation_date', $todayString)
            ->where('status', ReservationStatus::Confirmed)
            ->get();

        $activeReservationsToday = $todayReservations->count();

        // Segments occupied today
        $occupiedSegmentsToday = $todayReservations->flatMap(fn ($r) => $r->segment_ids ?? [])->unique()->count();
        $utilizationPercent = $totalSegments > 0
            ? round(($occupiedSegmentsToday / $totalSegments) * 100, 1)
            : 0;

        // Upcoming reservations (next 7 days)
        $upcomingReservations = SpaceReservation::where('facility_id', $this->facility->id)
            ->where('reservation_date', '>=', $todayString)
            ->where('reservation_date', '<=', $today->copy()->addDays(7)->toDateString())
            ->where('status', '!=', ReservationStatus::Cancelled)
            ->orderBy('reservation_date')
            ->orderBy('start_time')
            ->get();

        // Today's schedule: reservations with time slots
        $todaySchedule = SpaceReservation::where('facility_id', $this->facility->id)
            ->where('reservation_date', $todayString)
            ->where('status', '!=', ReservationStatus::Cancelled)
            ->orderBy('start_time')
            ->get();

        return view('livewire.facilities.facility-show', [
            'totalLayouts' => $totalLayouts,
            'totalSegments' => $totalSegments,
            'activeReservationsToday' => $activeReservationsToday,
            'utilizationPercent' => $utilizationPercent,
            'upcomingReservations' => $upcomingReservations,
            'todaySchedule' => $todaySchedule,
        ]);
    }
}
