<?php

namespace App\Filament\Resources\Panel;

use Filament\Forms;
use Filament\Tables;
use Livewire\Component;
use Filament\Forms\Form;
use App\Models\EquipWork;
use Filament\Tables\Table;
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\TextInput;
use Illuminate\Database\Eloquent\Builder;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\RichEditor;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use App\Filament\Resources\Panel\EquipWorkResource\Pages;
use App\Filament\Resources\Panel\EquipWorkResource\RelationManagers;
use Carbon\Carbon;
use Filament\Forms\Components\Card;
use Filament\Forms\Get;
use Filament\Forms\Set;

class EquipWorkResource extends Resource
{
    protected static ?string $model = EquipWork::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.equipWorks.itemTitle');
    }

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

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

    public static function form(Forms\Form $form): Forms\Form
    {
        return $form
            ->schema([
                Card::make()
                    ->schema([
                        Grid::make(['default' => 1])
                            ->schema([
                                Select::make('equip_id')
                                    ->label('Equipment') 
                                    ->required()
                                    ->relationship('equip', 'type') 
                                    ->searchable()
                                    ->preload()
                                    ->native(false),
    
                                DatePicker::make('date')
                                    ->rules(['date'])
                                    ->default(Carbon::today())
                                    ->required()
                                    ->native(false),
    
                                Select::make('land_id')
                                    ->label('Lands') 
                                    ->required()
                                    ->relationship('lands', 'name')
                                    ->searchable()
                                    ->preload()
                                    ->multiple()
                                    ->native(false),
    
                                TextInput::make('hours_count')
                                    ->label('Hours Count')
                                    ->required()
                                    ->numeric()
                                    ->step(1)
                                    ->afterStateUpdated(function (Set $set, Get $get) { // Corrected argument order
                                        static::calculateTotals($get, $set);
                                    }),
    
                                TextInput::make('hour_price')
                                    ->label('Hour Price')
                                    ->required()
                                    ->numeric()
                                    ->live(onBlur: true)
                                    ->step(1)
                                    ->afterStateUpdated(function (Set $set, Get $get) { // Corrected argument order
                                        static::calculateTotals($get, $set);
                                    }),
    
                                TextInput::make('total')
                                    ->label('Total')
                                    ->required()
                                    ->numeric()
                                    ->live(onBlur: true)

                                    ->step(1)
                                    ->default(0) // Set a default value for 'total' to trigger initial calculation
                                    ->readOnly()
                                    , 
    
                                RichEditor::make('notes')
                                    ->nullable()
                                    ->string()
                                    ->fileAttachmentsVisibility('public'),
                            ])->columns(2),
                    ]),
            ]);
    }
    
    public static function calculateTotals(Get $get, Set $set): void
    {
        $hoursCount = $get('hours_count');
        $hourPrice = $get('hour_price');
        $total = $hoursCount * $hourPrice;
        $set('total', $total);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->poll('60s')
            ->columns([
                TextColumn::make('equip.type')->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('hours_count')->badge()
                ->searchable()
                ->sortable()
                ->toggleable(),

                TextColumn::make('hour_price')->badge()
                ->searchable()
                ->sortable()
                ->toggleable(),

                TextColumn::make('total')->badge()
                ->searchable()
                ->sortable()
                ->toggleable(),

                TextColumn::make('notes')->limit(255)->badge()
                ->searchable()
                ->sortable()
                ->toggleable(),
            ])
            ->filters([Tables\Filters\TrashedFilter::make()])
            ->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');
    }

    public static function getRelations(): array
    {
        return [];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListEquipWorks::route('/'),
            'create' => Pages\CreateEquipWork::route('/create'),
            'view' => Pages\ViewEquipWork::route('/{record}'),
            'edit' => Pages\EditEquipWork::route('/{record}/edit'),
        ];
    }

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