<?php

namespace App\Filament\Resources;

use App\Filament\Exports\AlertMailRuleExporter;
use App\Filament\Imports\AlertMailRuleImporter;
use App\Filament\Resources\AlertMailRuleResource\Pages;
use App\Models\AlertMailRule;
use App\Models\InvoiceMaster;
use App\Models\Plant;
use App\Models\Machine;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\Section;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Artisan;

class AlertMailRuleResource extends Resource
{
    protected static ?string $model = AlertMailRule::class;

    protected static ?string $navigationIcon = 'heroicon-m-bell-alert';

    protected static ?string $navigationGroup = 'Alert Mail';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\Select::make('plant')
                            ->label('Plant')
                            ->reactive()
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
                            })
                            ->required(fn ($get) => ! $get('is_active'))
                            ->afterStateUpdated(fn ($state, callable $set) => $state ? $set('is_active', false) : null),
                        // ->options(fn () => Plant::pluck('id', 'name')->toArray()),
                        Forms\Components\Select::make('machine_id')
                            ->label('Work Center')
                            ->options(function (callable $get) {
                                $plantId = $get('plant');

                                if (!$plantId) {
                                    return [];
                                }

                                return Machine::where('plant_id', $plantId)
                                ->whereNotNull('work_center')
                                ->pluck('work_center', 'id')
                                ->toArray();
                            })
                            ->searchable()
                            ->reactive()
                            ->afterStateUpdated(function (callable $set) {
                                $set('module', null);
                            }),
                        Forms\Components\Select::make('module')
                            ->label('Module')
                            ->required()
                            ->options([
                                'InvoiceValidation' => 'InvoiceValidation',
                                'InvoiceDataReport' => 'InvoiceDataReport',
                                'ProductionQuantities' => 'ProductionQuantities',
                                'QualityValidation' => 'QualityValidation',
                                'InvoiceTransit' => 'InvoiceTransit',
                                'ImportTransit' => 'ImportTransit',
                                'VehicleReport' => 'VehicleReport',
                                'ExportDispatchReport' => 'ExportDispatchReport',
                                'LaserStopAlert' => 'LaserStopAlert',
                                'LaserStopReport' => 'LaserStopReport',
                            ]),
                        Forms\Components\Select::make('rule_name')
                            ->label('Rule Name')
                            ->options([
                                'InvoiceMail' => 'Invoice Mail',
                                'SerialInvoiceMail' => 'Serial Invoice Mail',
                                'MaterialInvoiceMail' => 'Material Invoice Mail',
                                'ProductionMail' => 'Production Mail',
                                'InvoiceDataMail' => 'Invoice Data Mail',
                                'QualityMail' => 'Quality Mail',
                                'InvoiceTransitMail' => 'Invoice Transit Mail',
                                'ImportTransitMail' => 'Import Transit Mail',
                                'VehicleReportMail' => 'Vehicle Report Mail',
                                'ExportDispatchReportMail' => 'Export Dispatch Report Mail',
                                'LaserStopAlertMail' => 'Laser Stop Alert Mail',
                                'LaserStopMail' => 'Laser Stop Report Mail'
                            ])
                            ->required(),
                        Forms\Components\TextInput::make('email')
                            ->label('Email')
                            ->required(),
                        Forms\Components\Textarea::make('cc_emails')
                            ->label('CC Emails'),
                        Forms\Components\Select::make('schedule_type')
                            ->label('Schedule Type')
                            ->options([
                                'Live' => 'Live',
                                'Hourly' => 'Hourly',
                                'Daily' => 'Daily',
                            ]),
                        Forms\Components\Select::make('receiving_plant_name')
                            ->label('Receiving Plant')
                            ->options(
                                InvoiceMaster::query()
                                    ->whereNotNull('receiving_plant_name')
                                    ->select('receiving_plant_name')
                                    ->distinct()
                                    ->pluck('receiving_plant_name', 'receiving_plant_name')
                            )
                            ->searchable()
                            ->reactive()
                            ->afterStateUpdated(function (callable $set) {
                                $set('invoice_master_id', null);
                            }),
                        Forms\Components\Select::make('invoice_master_id')
                            ->label('Transporter Name')
                            ->options(function (callable $get) {
                                $recPlant = $get('receiving_plant_name');

                                if (! $recPlant) {
                                    return [];
                                }

                                return InvoiceMaster::query()
                                    ->where('receiving_plant_name', $recPlant)
                                    ->whereNotNull('transport_name')
                                    ->where('transport_name', '!=', '')
                                    ->orderBy('transport_name')
                                    ->pluck('transport_name', 'id')
                                    ->toArray();
                            })
                            ->searchable(),
                        Checkbox::make('is_active')
                            ->label('All Plants Reports')
                            ->afterStateUpdated(fn ($state, callable $set) => $state ? $set('plant', null) : null)
                            ->reactive(),
                        // Forms\Components\Actions::make([
                        //     Action::make('sendInvoiceData')
                        //         ->label('Invoice Data Report')
                        //         ->action(function ($get) {

                        //             $plantIds = AlertMailRule::where('module', 'InvoiceDataReport')
                        //                 ->orderBy('plant')
                        //                 ->pluck('plant')
                        //                 ->toArray();

                        //             foreach ($plantIds as $plantId) {
                        //                 Artisan::call('send:invoice-data-report', [
                        //                     'schedule_type' => 'Daily',
                        //                     'plant' => $plantId,
                        //                 ]);
                        //             }

                        //             // Notify user in Filament
                        //             Notification::make()
                        //                 ->title('Invoice data report sent successfully!')
                        //                 ->success()
                        //                 ->send();
                        //         }),

                        //     ]),
                        Forms\Components\Hidden::make('created_by')
                            ->default(fn () => Filament::auth()->user()?->name),
                        Forms\Components\Hidden::make('updated_by')
                            ->default(fn () => Filament::auth()->user()?->name),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;

                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('plant')
                    ->label('Plant Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->formatStateUsing(function ($state) {
                        static $plants;
                        if (! $plants) {
                            $plants = Plant::pluck('name', 'id')->toArray();
                        }

                        return $plants[$state] ?? 'All Plants';
                    }),
                Tables\Columns\TextColumn::make('machine.work_center')
                    ->label('Work Center')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('module')
                    ->label('Module Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('rule_name')
                    ->label('Rule Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                // Tables\Columns\TextColumn::make('invoiceMaster.receiving_plant_name')
                //     ->label('Receiving Plant')
                //     ->alignCenter()
                //     ->sortable(),
                // Tables\Columns\TextColumn::make('invoiceMaster.transport_name')
                //     ->label('Transporter')
                //     ->alignCenter()
                //     ->sortable(),
                Tables\Columns\TextColumn::make('email')
                    ->label('TO Emails')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('cc_emails')
                    ->label('CC Emails')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('schedule_type')
                    ->label('Schedule Type')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: false),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->label('Import Alert Mail Rule')
                    ->color('warning')
                    ->importer(AlertMailRuleImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import alert mail rule');
                    }),
                ExportAction::make()
                    ->label('Export Alert Mail Rule')
                    ->color('warning')
                    ->exporter(AlertMailRuleExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export alert mail rule');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAlertMailRules::route('/'),
            'create' => Pages\CreateAlertMailRule::route('/create'),
            'view' => Pages\ViewAlertMailRule::route('/{record}'),
            'edit' => Pages\EditAlertMailRule::route('/{record}/edit'),
        ];
    }

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