<?php

namespace App\Filament\Resources\WorkOrders;

use App\Filament\Resources\WorkOrders\Pages\CreateWorkOrder;
use App\Filament\Resources\WorkOrders\Pages\EditWorkOrder;
use App\Filament\Resources\WorkOrders\Pages\ListWorkOrders;
use App\Models\WorkOrder;
use App\Models\Company;
use App\Models\Site;
use App\Models\Machine;
use App\Models\Driver;
use App\Models\Contract;
use App\Models\Service;
use App\Models\ContractItem;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Repeater;
use Filament\Schemas\Components\Section;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Notifications\Notification;


class WorkOrderResource extends Resource
{
    protected static ?string $model = WorkOrder::class;

    protected static ?string $navigationLabel = null;

    protected static ?string $modelLabel = null;

    protected static ?string $pluralModelLabel = null;

    protected static ?int $navigationSort = 1;
    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentList;

    public static function getNavigationGroup(): string|null
    {
        return 'التشغيل والصيانة';
    }

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::count();
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('filament/admin/work_order_resource.معلوماتأمرالتشغيل'))
                    ->schema([
                        TextInput::make('order_no')
                            ->label(__('filament/admin/work_order_resource.order_no'))
                            ->disabled()
                            ->dehydrated(false)
                            ->placeholder('يولد تلقائياً'),

                        DatePicker::make('order_date')
                            ->label(__('filament/admin/work_order_resource.order_date'))
                            ->required()
                            ->default(today())
                            ->native(false)
                            ->displayFormat('Y-m-d'),

                        Select::make('company_id')
                            ->label(__('filament/admin/work_order_resource.company_id'))
                            ->options(Company::query()->where('is_active', true)->pluck('name', 'id')->toArray())
                            ->searchable()
                            ->required()
                            ->preload()
                            ->reactive()
                            ->afterStateUpdated(function (callable $set) {
                                $set('site_id', null);
                                $set('contract_id', null);
                            })
                            ->createOptionForm([
                                Section::make('بيانات الشركة')
                                    ->schema([
                                        TextInput::make('name')
                                            ->label('الاسم')
                                            ->required()
                                            ->maxLength(255)
                                            ->columnSpanFull(),
                                        TextInput::make('contact_person')
                                            ->label('الشخص المسؤول')
                                            ->maxLength(255),
                                        TextInput::make('phone')
                                            ->label('الهاتف')
                                            ->tel()
                                            ->maxLength(20),
                                        TextInput::make('email')
                                            ->label('البريد الإلكتروني')
                                            ->email()
                                            ->maxLength(255),
                                        Textarea::make('address')
                                            ->label('العنوان')
                                            ->rows(2)
                                            ->columnSpanFull(),
                                    ])
                                    ->columns(2)
                            ])
                            ->createOptionUsing(function ($data) {
                                return \App\Models\Company::create($data)->id;
                            })
                            ->createOptionModalHeading('إضافة شركة جديدة'),

                        Select::make('site_id')
                            ->label(__('filament/admin/work_order_resource.site_id'))
                            ->options(function (callable $get) {
                                $companyId = $get('company_id');
                                if (!$companyId) {
                                    return [];
                                }
                                return Site::query()
                                    ->where('company_id', $companyId)
                                    ->where('is_active', true)
                                    ->pluck('name', 'id')
                                    ->toArray();
                            })
                            ->searchable()
                            ->required()
                            ->preload()
                            ->reactive()
                            ->createOptionForm([
                                Select::make('company_id')
                                    ->label('الشركة')
                                    ->relationship('company', 'name')
                                    ->required()
                                    ->searchable()
                                    ->preload(),
                                TextInput::make('name')
                                    ->label('الاسم')
                                    ->required()
                                    ->maxLength(255),
                                TextInput::make('code')
                                    ->label('الرمز')
                                    ->maxLength(50),
                                TextInput::make('location')
                                    ->label('الموقع')
                                    ->maxLength(255),
                            ])
                            ->createOptionUsing(function ($data) {
                                return \App\Models\Site::create($data)->id;
                            }),

                        Select::make('contract_id')
                            ->label(__('filament/admin/work_order_resource.contract_id'))
                            ->options(function (callable $get) {
                                $companyId = $get('company_id');
                                if (!$companyId) {
                                    return [];
                                }
                                return Contract::query()
                                    ->where('company_id', $companyId)
                                    ->where('status', 'active')
                                    ->get()
                                    ->pluck('contract_no', 'id')
                                    ->toArray();
                            })
                            ->searchable()
                            ->preload()
                            ->reactive()
                            ->createOptionForm([
                                Select::make('company_id')
                                    ->label('الشركة')
                                    ->relationship('company', 'name')
                                    ->required()
                                    ->searchable()
                                    ->preload(),
                                TextInput::make('contract_no')
                                    ->label('رقم العقد')
                                    ->required()
                                    ->maxLength(100),
                                DatePicker::make('start_date')
                                    ->label('تاريخ البداية')
                                    ->required(),
                                DatePicker::make('end_date')
                                    ->label('تاريخ النهاية')
                                    ->required(),
                            ])
                            ->createOptionUsing(function ($data) {
                                $data['status'] = 'draft';
                                return \App\Models\Contract::create($data)->id;
                            }),

                        Select::make('machine_id')
                            ->label(__('filament/admin/work_order_resource.machine_id'))
                            ->options(Machine::query()->where('is_active', true)->pluck('name', 'id')->toArray())
                            ->searchable()
                            ->required()
                            ->preload()
                            ->createOptionForm([
                                TextInput::make('name')
                                    ->label('الاسم')
                                    ->required()
                                    ->maxLength(255),
                                TextInput::make('code')
                                    ->label('الرمز')
                                    ->maxLength(50),
                                TextInput::make('plate_no')
                                    ->label('رقم اللوحة')
                                    ->maxLength(50),
                                TextInput::make('type')
                                    ->label('النوع')
                                    ->maxLength(100),
                            ])
                            ->createOptionUsing(function ($data) {
                                return \App\Models\Machine::create($data)->id;
                            }),

                        Select::make('driver_id')
                            ->label(__('filament/admin/work_order_resource.driver_id'))
                            ->options(Driver::query()->where('is_active', true)->pluck('name', 'id')->toArray())
                            ->searchable()
                            ->preload()
                            ->createOptionForm([
                                TextInput::make('name')
                                    ->label('الاسم')
                                    ->required()
                                    ->maxLength(255),
                                TextInput::make('code')
                                    ->label('الرمز')
                                    ->maxLength(50),
                                TextInput::make('license_no')
                                    ->label('رقم الرخصة')
                                    ->maxLength(50),
                                TextInput::make('phone')
                                    ->label('الهاتف')
                                    ->tel()
                                    ->maxLength(20),
                            ])
                            ->createOptionUsing(function ($data) {
                                return \App\Models\Driver::create($data)->id;
                            }),

                        Select::make('shift_type')
                            ->label(__('filament/admin/work_order_resource.shift_type'))
                            ->options(['morning' => __('filament/admin/work_order_resource.shift_type.morning'), 'evening' => __('filament/admin/work_order_resource.shift_type.evening'), 'night' => __('filament/admin/work_order_resource.shift_type.night'), 'full_day' => __('filament/admin/work_order_resource.shift_type.full_day')])
                            ->default('full_day')
                            ->required()
                            ->preload(),

                        Select::make('status')
                            ->label(__('filament/admin/work_order_resource.status'))
                            ->options(['draft' => __('filament/admin/work_order_resource.status.draft'), 'submitted' => __('filament/admin/work_order_resource.status.submitted'), 'approved' => __('filament/admin/work_order_resource.status.approved'), 'rejected' => __('filament/admin/work_order_resource.status.rejected'), 'invoiced' => __('filament/admin/work_order_resource.status.invoiced')])
                            ->default('draft')
                            ->required()
                            ->preload()
                            ->disabled(fn ($record) => $record && in_array($record->status, ['approved', 'invoiced'])),
                    ])->columns(2),

                Section::make(__('filament/admin/work_order_resource.ملاحظات'))
                    ->schema([
                        Textarea::make('notes')
                            ->label(__('filament/admin/work_order_resource.notes'))
                            ->maxLength(1000)
                            ->columnSpanFull(),

                        Textarea::make('approval_notes')
                            ->label(__('filament/admin/work_order_resource.approval_notes'))
                            ->maxLength(1000)
                            ->disabled()
                            ->visible(fn ($record) => $record && $record->approval_notes)
                            ->columnSpanFull(),
                    ]),

                Section::make(__('filament/admin/work_order_resource.الخدماتالمنفذة'))
                    ->schema([
                        Repeater::make('lines')
                    ->label(__('filament/admin/work_order_resource.lines'))
                            ->relationship('lines')
                            ->schema([
                                Select::make('service_id')
                                    ->label(__('filament/admin/work_order_resource.service_id'))
                                    ->options(Service::query()->where('is_active', true)->pluck('name', 'id')->toArray())
                                    ->searchable()
                                    ->required()
                                    ->preload()
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $get, callable $set) {
                                        $contractId = $get('../../contract_id');
                                        if ($contractId && $state) {
                                            // Get unit price from contract item
                                            $contractItem = ContractItem::where('contract_id', $contractId)
                                                ->where('service_id', $state)
                                                ->first();
                                            if ($contractItem) {
                                                $set('contract_item_id', $contractItem->id);
                                                $set('unit_price', $contractItem->unit_price);
                                            }
                                        }
                                    })
                                    ->createOptionForm([
                                        TextInput::make('name')
                                            ->label('الاسم')
                                            ->required()
                                            ->maxLength(255),
                                        TextInput::make('code')
                                            ->label('الرمز')
                                            ->maxLength(50),
                                        Textarea::make('description')
                                            ->label('الوصف')
                                            ->rows(2),
                                    ])
                                    ->createOptionUsing(function ($data) {
                                        return \App\Models\Service::create($data)->id;
                                    })
                                    ->columnSpan(2),

                                TextInput::make('executed_qty')
                                    ->label(__('filament/admin/work_order_resource.executed_qty'))
                                    ->numeric()
                                    ->required()
                                    ->default(0)
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $get, callable $set) {
                                        $qty = (float) $state;
                                        $price = (float) $get('unit_price');
                                        $set('amount', $qty * $price);
                                    }),

                                TextInput::make('unit_price')
                                    ->label(__('filament/admin/work_order_resource.unit_price'))
                                    ->numeric()
                                    ->required()
                                    ->default(0)
                                    ->prefix('EGP')
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $get, callable $set) {
                                        $qty = (float) $get('executed_qty');
                                        $price = (float) $state;
                                        $set('amount', $qty * $price);
                                    }),

                                TextInput::make('amount')
                                    ->label(__('filament/admin/work_order_resource.amount'))
                                    ->numeric()
                                    ->disabled()
                                    ->dehydrated(true)
                                    ->prefix('EGP')
                                    ->default(0),

                                Textarea::make('notes')
                                    ->label('ملاحظات')
                                    ->maxLength(500)
                                    ->columnSpanFull(),
                            ])
                            ->columns(5)
                            ->defaultItems(1)
                            ->reorderable(false)
                            ->collapsible()
                            ->itemLabel(fn (array $state): ?string => 
                                isset($state['service_id']) 
                                    ? Service::find($state['service_id'])?->name 
                                    : 'خدمة جديدة'
                            )
                            ->addActionLabel('إضافة خدمة')
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->applyTenantScope()
            ->columns([
                TextColumn::make('order_no')
                    ->label(__('filament/admin/work_order_resource.order_no'))
                    ->searchable()
                    ->sortable(),
                
                TextColumn::make('order_date')
                    ->label(__('filament/admin/work_order_resource.order_date'))
                    ->date('Y-m-d')
                    ->sortable(),
                
                TextColumn::make('company.name')
                    ->label(__('filament/admin/work_order_resource.company.name'))
                    ->searchable()
                    ->sortable(),
                
                TextColumn::make('site.name')
                    ->label(__('filament/admin/work_order_resource.site.name'))
                    ->searchable()
                    ->toggleable(),
                
                TextColumn::make('machine.name')
                    ->label(__('filament/admin/work_order_resource.machine.name'))
                    ->searchable()
                    ->sortable(),
                
                TextColumn::make('driver.name')
                    ->label(__('filament/admin/work_order_resource.driver.name'))
                    ->searchable()
                    ->toggleable(),
                
                TextColumn::make('shift_type')
                    ->label(__('filament/admin/work_order_resource.shift_type'))
                    ->formatStateUsing(function ($state) {
                        $shifts = [
                            'morning' => 'صباحي',
                            'evening' => 'مسائي',
                            'night' => 'ليلي',
                            'full_day' => 'يوم كامل',
                        ];
                        return $shifts[$state] ?? $state;
                    })
                    ->toggleable(),
                
                BadgeColumn::make('status')
                    ->label('الحالة')
                    ->formatStateUsing(function ($state) {
                        $statuses = [
                            'draft' => 'مسودة',
                            'submitted' => 'مُقدم',
                            'approved' => 'مُعتمد',
                            'rejected' => 'مرفوض',
                            'invoiced' => 'تم الفوترة',
                        ];
                        return $statuses[$state] ?? $state;
                    })
                    ->colors([
                        'secondary' => 'draft',
                        'warning' => 'submitted',
                        'success' => 'approved',
                        'danger' => 'rejected',
                        'primary' => 'invoiced',
                    ]),
                
                TextColumn::make('lines_count')
                    ->label(__('filament/admin/work_order_resource.lines_count'))
                    ->counts('lines')
                    ->sortable(),
            ])
            ->recordActions([
                Action::make('approve')
                    ->label(__('filament/admin/work_order_resource.approve'))
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->modalHeading('اعتماد أمر التشغيل')
                    ->modalDescription('هل أنت متأكد من اعتماد أمر التشغيل هذا؟')
                    ->modalSubmitActionLabel('اعتماد')
                    ->visible(fn (WorkOrder $record): bool => $record->status === 'submitted')
                    ->action(function (WorkOrder $record) {
                        $record->approve();
                        Notification::make()
                            ->success()
                            ->title('تم الاعتماد بنجاح')
                            ->send();
                    }),
                
                Action::make('reject')
                    ->label(__('filament/admin/work_order_resource.reject'))
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->modalHeading('رفض أمر التشغيل')
                    ->modalDescription('هل أنت متأكد من رفض أمر التشغيل هذا؟')
                    ->modalSubmitActionLabel('رفض')
                    ->visible(fn (WorkOrder $record): bool => in_array($record->status, ['submitted', 'approved']))
                    ->action(function (WorkOrder $record) {
                        $record->reject();
                        Notification::make()
                            ->success()
                            ->title('تم الرفض')
                            ->send();
                    }),
                
                EditAction::make(),
                DeleteAction::make()
                    ->requiresConfirmation()
                    ->visible(fn (WorkOrder $record): bool => $record->status === 'draft'),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->requiresConfirmation(),
                ]),
            ])
            ->defaultSort('order_date', 'desc');
    }

    public static function getPages(): array
    {
        return [
            'index' => ListWorkOrders::route('/'),
            'create' => CreateWorkOrder::route('/create'),
            'edit' => EditWorkOrder::route('/{record}/edit'),
        ];
    }

    public static function canViewAny(): bool
    {
        return true;
    }

    public static function canCreate(): bool
    {
        return true;
    }

    public static function canEdit($record): bool
    {
        return true;
    }

    public static function canDelete($record): bool
    {
        return true;
    }

    public static function canDeleteAny(): bool
    {
        return true;
    }
    public static function getNavigationLabel(): string
    {
        return __('filament/admin/work_order_resource.navigation_label');
    }
    public static function getModelLabel(): string
    {
        return __('filament/admin/work_order_resource.model_label');
    }
    public static function getPluralModelLabel(): string
    {
        return __('filament/admin/work_order_resource.plural_model_label');
    }



}
