<?php

namespace App\Filament\Resources\Panel;

use Filament\Forms;
use Filament\Tables;
use Livewire\Component;
use Filament\Forms\Form;
use Filament\Tables\Table;
use App\Models\Attendance;
use Filament\Resources\Resource;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Section;
use Filament\Tables\Columns\TextColumn;
use Filament\Forms\Components\Checkbox;
use Illuminate\Database\Eloquent\Builder;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\RichEditor;
use Filament\Tables\Columns\CheckboxColumn;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use App\Filament\Resources\Panel\AttendanceResource\Pages;
use App\Filament\Resources\Panel\AttendanceResource\RelationManagers;
use Carbon\Carbon;

use function Laravel\Prompts\select;
use App\Models\Employee;

class AttendanceResource extends Resource
{
    protected static ?string $model = Attendance::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static ?int $navigationSort = 1;

    protected static ?string $navigationGroup = 'العمل اليومي';

    public static function getModelLabel(): string
    {
        return __('crud.attendances.itemTitle');
    }

    public static function getPluralModelLabel(): string
    {
        return __('crud.attendances.collectionTitle');
    }

    public static function getNavigationLabel(): string
    {
        return __('crud.attendances.collectionTitle');
    }

    public static function form(Form $form): Form
    {
        return $form->schema([
            Section::make()->schema([
                Grid::make(['default' => 1])->schema([
                    DatePicker::make('date')
                        ->rules(['date'])
                        ->default(Carbon::today())
                        ->required()
                        ->native(false),

                    Select::make('land_id')
                        ->nullable()
                        ->relationship('lands', 'name')
                        ->searchable()
                        ->preload()
                        ->multiple()
                        ->native(false),

                    Select::make('work_type_id')
                        ->nullable()
                        ->relationship('workType', 'name')
                        ->searchable()
                        ->required()
                        ->preload()
                        ->native(false),

                    // Checkbox::make('present')
                    //     ->rules(['boolean'])
                    //     ->required()
                    //     ->inline(),
                    // select::make('day_type')
                    //     ->options([
                    //         'full_day' => 'يوم كامل',
                    //         'half_day' => 'نصف يوم',
                    //     ])
                    //     ->default('full_day')
                    //     ->required(),

                    Select::make('employees')
                        ->relationship('employees', 'name')
                        ->multiple()
                        ->preload()
                        // ->required(true)
                        ,

                    Select::make('employees_half_day')
                        // ->label('Employees (Half Day)') 
                        ->relationship('employees_half_day', 'name')
                        ->multiple()
                        ->preload()
                        // ->required(true)
                        ->options(function (callable $get) {
                            $selectedEmployees = $get('employees'); // Get selected employees from the first select

                            // Get all available employees
                            $allEmployees = Employee::all();

                            // Filter employees to exclude those already selected
                            $availableEmployees = $allEmployees->filter(function ($employee) use ($selectedEmployees) {
                                return !in_array($employee->id, $selectedEmployees);
                            });

                            return $availableEmployees->pluck('name', 'id');
                        }),

                    Select::make('employees_gamaeya')
                        ->relationship('employees_gamaeya', 'name')
                        ->multiple()
                        ->preload()
                    // ->required(true)
                    ,

                    RichEditor::make('notes')
                        ->nullable()
                        ->string()
                        ->fileAttachmentsVisibility('public'),

                ])->columns(2),
            ]),
        ]);
    }


    public static function table(Table $table): Table
{
    return $table
        ->poll('60s')
        ->columns([
            TextColumn::make('id')
            ->badge()
            ->searchable()
            ->sortable()
            ->toggleable(),
            TextColumn::make('date')->date('D-d-M-Y')
                ->badge()
                ->searchable()
                ->sortable()
                ->toggleable(),

            TextColumn::make('lands.name')
                ->badge()
                ->searchable()
                ->sortable()
                ->toggleable(),

            TextColumn::make('workType.name')
                ->badge()
                ->searchable()
                ->sortable()
                ->toggleable(),

            TextColumn::make('notes')
                ->badge()
                ->searchable()
                ->sortable()
                ->toggleable()
                ->limit(255)
                ->html(),

            TextColumn::make('employees.name')
                ->badge()
                ->searchable()
                ->sortable()
                ->toggleable(),

            TextColumn::make('employees_half_day.name')
                ->badge()
                ->searchable()
                ->sortable()
                ->toggleable(),

            TextColumn::make('employees_gamaeya.name')
                ->badge()
                ->searchable()
                ->toggleable(),
        ])
        ->filters([
            Tables\Filters\TrashedFilter::make(),

            // 🔹 Date Range Filter
            Tables\Filters\Filter::make('date')
                ->form([
                    DatePicker::make('from')->label('من تاريخ'),
                    DatePicker::make('to')->label('إلى تاريخ'),
                ])
                ->query(function (Builder $query, array $data) {
                    if (!empty($data['from']) && !empty($data['to'])) {
                        $query->whereBetween('date', [$data['from'], $data['to']]);
                    } elseif (!empty($data['from'])) {
                        $query->whereDate('date', '>=', $data['from']);
                    } elseif (!empty($data['to'])) {
                        $query->whereDate('date', '<=', $data['to']);
                    }
                }),

            // 🔹 Employee Filter
            Tables\Filters\SelectFilter::make('employee_id')
                ->label('الموظف')
                ->relationship('employees', 'name')
                ->multiple()
                ->preload()
                ->searchable()
                ->query(function (Builder $query, array $data) {
                    if (!empty($data['values'])) {
                        $query->whereHas('employees', function ($q) use ($data) {
                            $q->whereIn('id', $data['values']);
                        });
                    }
                }),
        ])
        ->actions([
            Tables\Actions\EditAction::make(),
            Tables\Actions\ViewAction::make(),
        ])
        ->bulkActions([
            Tables\Actions\BulkActionGroup::make([
                Tables\Actions\DeleteBulkAction::make(),
                Tables\Actions\ForceDeleteBulkAction::make(),
                Tables\Actions\RestoreBulkAction::make(),
            ]),
        ])
        ->defaultSort('date', 'desc')
         ->striped() // إضافة خطوط متباعدة لجمالية الجدول
         ; // تحديد ارتفاع الجدول;
}

    // public static function getRelations(): array
    // {
    //     return [RelationManagers\EmployeesRelationManager::class];
    // }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAttendances::route('/'),
            'create' => Pages\CreateAttendance::route('/create'),
            'view' => Pages\ViewAttendance::route('/{record}'),
            'edit' => Pages\EditAttendance::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->withoutGlobalScopes([
            SoftDeletingScope::class,
        ]);
    }
}
