<?php

namespace App\Livewire\Trainer;

use App\Domain\Attendance\Enums\AttendanceStatus;
use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Scheduling\Enums\AssignmentStatus;
use App\Domain\Scheduling\Models\Assignment;
use App\Domain\Training\Enums\SessionStatus;
use App\Domain\Training\Models\TrainingGroup;
use App\Domain\Training\Models\TrainingSession;
use App\Domain\Shared\Traits\UsesBranchScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('لوحة المدرب')]
class TrainerDashboard extends Component
{
    use UsesBranchScope;

    public function mount(): void
    {
        $this->authorize('attendance.mark');

        // A coach dashboard cannot mean anything across branches, so refuse to
        // open in all-branches mode. The id itself is deliberately not kept on
        // the component: every query below reads through BranchScope, and a
        // public property holding a branch id is settable from the browser.
        $this->getActiveBranchIdOrFail();
    }

    public function render()
    {
        $user = auth()->user();
        $today = now()->toDateString();

        // Get group IDs assigned to this trainer (active assignments)
        $assignedGroupIds = Assignment::active()
            ->forUser($user->id)
            ->where('assignable_type', TrainingGroup::class)
            ->pluck('assignable_id');

        // Today's sessions for assigned groups
        $todaySessions = TrainingSession::whereIn('training_group_id', $assignedGroupIds)
            ->where('session_date', $today)
            ->whereIn('status', [SessionStatus::Scheduled, SessionStatus::InProgress, SessionStatus::Completed])
            ->with('group')
            ->orderBy('start_time')
            ->get();

        // Upcoming sessions (next 7 days, excluding today)
        $upcomingSessions = TrainingSession::whereIn('training_group_id', $assignedGroupIds)
            ->where('session_date', '>', $today)
            ->where('session_date', '<=', now()->addDays(7)->toDateString())
            ->where('status', SessionStatus::Scheduled)
            ->with('group')
            ->orderBy('session_date')
            ->orderBy('start_time')
            ->get();

        // Assigned groups with participant count
        $assignedGroups = TrainingGroup::whereIn('id', $assignedGroupIds)
            ->whereIn('status', ['active', 'forming', 'full'])
            ->orderBy('name_ar')
            ->get();

        // Monthly stats: sessions conducted this month
        $monthStart = now()->startOfMonth()->toDateString();
        $monthEnd = now()->endOfMonth()->toDateString();

        $sessionsThisMonth = TrainingSession::whereIn('training_group_id', $assignedGroupIds)
            ->whereBetween('session_date', [$monthStart, $monthEnd])
            ->where('status', SessionStatus::Completed)
            ->count();

        $totalSessionsThisMonth = TrainingSession::whereIn('training_group_id', $assignedGroupIds)
            ->whereBetween('session_date', [$monthStart, $monthEnd])
            ->whereIn('status', [SessionStatus::Scheduled, SessionStatus::InProgress, SessionStatus::Completed])
            ->count();

        // My attendance stats (this month)
        $myAttendanceQuery = AttendanceRecord::where('subject_type', \App\Models\User::class)
            ->where('subject_id', $user->id)
            ->whereBetween('created_at', [$monthStart . ' 00:00:00', $monthEnd . ' 23:59:59']);

        $myTotalRecords = (clone $myAttendanceQuery)->count();
        $myPresentCount = (clone $myAttendanceQuery)->where('status', AttendanceStatus::Present)->count();
        $myLateCount = (clone $myAttendanceQuery)->where('status', AttendanceStatus::Late)->count();
        $myAbsentCount = (clone $myAttendanceQuery)->whereIn('status', [AttendanceStatus::Absent, AttendanceStatus::NoShow])->count();
        $myCancelledExempt = (clone $myAttendanceQuery)->whereIn('status', [AttendanceStatus::Cancelled, AttendanceStatus::Exempt])->count();

        $myAttendanceDenominator = $myTotalRecords - $myCancelledExempt;
        $myAttendanceRate = $myAttendanceDenominator > 0
            ? round(($myPresentCount + $myLateCount) / $myAttendanceDenominator * 100, 1)
            : 0;

        // Recent attendance records (last 15)
        $recentAttendance = AttendanceRecord::where('subject_type', \App\Models\User::class)
            ->where('subject_id', $user->id)
            ->with('session.group')
            ->orderByDesc('created_at')
            ->limit(15)
            ->get();

        return view('livewire.trainer.trainer-dashboard', [
            'todaySessions' => $todaySessions,
            'upcomingSessions' => $upcomingSessions,
            'assignedGroups' => $assignedGroups,
            'sessionsThisMonth' => $sessionsThisMonth,
            'totalSessionsThisMonth' => $totalSessionsThisMonth,
            'myPresentCount' => $myPresentCount,
            'myLateCount' => $myLateCount,
            'myAbsentCount' => $myAbsentCount,
            'myAttendanceRate' => $myAttendanceRate,
            'recentAttendance' => $recentAttendance,
        ]);
    }
}
