<?php

namespace App\Filament\Resources;

use App\Filament\Exports\LineExporter;
use App\Filament\Imports\LineImporter;
use App\Filament\Resources\LineResource\Pages;
use App\Models\Block;
use App\Models\Line;
use App\Models\Plant;
use App\Models\WorkGroupMaster;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Section;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Forms\Set;
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\Validation\Rule;
use Illuminate\Validation\Rules\Unique;

class LineResource extends Resource
{
    protected static ?string $model = Line::class;

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

    protected static ?string $navigationGroup = 'Master Entries';

    protected static ?int $navigationSort = 5;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\Select::make('plant_id')
                            ->relationship('plant', 'name')
                            ->required()
                            // ->nullable(),
                            ->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();
                            })
                            ->default(function () {
                                return optional(Line::latest()->first())->plant_id;
                            })
                            ->disabled(fn (Get $get) => ! empty($get('id')))
                            // ->afterStateUpdated(fn ($set) => $set('block_id', null) & $set('name', null) & $set('start_time', null) & $set('duration', null) & $set('end_time', null))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                // Ensure `linestop_id` is not cleared
                                if (! $plantId) {
                                    $set('lPlantError', 'Please select a plant first.');

                                    return;
                                } else {
                                    $set('lPlantError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('lPlantError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('lPlantError') ? $get('lPlantError') : null)
                            ->hintColor('danger'),
                        Forms\Components\Select::make('block_id')
                            ->label('Block')
                            ->relationship('block', 'name')
                            ->required()
                            // ->nullable(),
                            ->reactive()
                            ->options(function (callable $get) {
                                if (! $get('plant_id')) {
                                    return [];
                                }

                                return Block::where('plant_id', $get('plant_id'))
                                    ->pluck('name', 'id')
                                    ->toArray();
                            })
                            ->default(function () {
                                return optional(Block::latest()->first())->plant_id;
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $blockId = $get('block_id');
                                if (! $blockId) {
                                    $set('lblockError', 'Please select a Block first.');

                                    return;
                                } else {
                                    $set('lblockError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('lblockError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('lblockError') ? $get('lblockError') : null)
                            ->hintColor('danger'),
                        Forms\Components\TextInput::make('name')
                            ->required()
                            ->placeholder('Scan the valid name')
                            ->autofocus(true)
                            // ->unique(
                            //     ignoreRecord: true,
                            //     modifyRuleUsing: function (Unique $rule) {
                            //         return $rule->where('plant_id', $this->data['plant_id']);
                            //     }
                            // )
                            // ->rule(function () {
                            //     return function ($attribute, $value, $fail) {
                            //         $exists = Line::where('name', $value)
                            //             ->where('plant_id', request()->input('plant_id'))
                            //             ->exists();

                            //         if ($exists) {
                            //             $fail('The combination of name and plant ID must be unique.');
                            //         }
                            //     };
                            // })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $lineNam = $get('name');
                                // Ensure `linestop_id` is not cleared
                                if (! $lineNam) {
                                    $set('lNameError', 'Scan the valid name.');

                                    return;
                                } else {
                                    // $exists = Line::where('name', $lineNam)
                                    //     ->where('plant_id', $get('plant_id'))
                                    //     ->exists();

                                    // if ($exists) {
                                    //     $set('name', null);
                                    //     $set('lNameError', 'The name has already been taken.');
                                    //     // $set('lNameError', 'The combination of name and plant ID must be unique.');
                                    //     return;
                                    // }
                                    $set('lNameError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('lNameError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('lNameError') ? $get('lNameError') : null)
                            ->hintColor('danger')
                            ->rule(function (callable $get) {
                                return Rule::unique('lines', 'name')
                                    ->where('plant_id', $get('plant_id'))
                                    ->ignore($get('id')); // Ignore current record during updates
                            }),
                        // Forms\Components\TextInput::make('type')
                        //     ->required()
                        //     ->placeholder('Scan the valid type')
                        //     ->reactive()
                        //     ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        //         $lineTyp = $get('type');
                        //         // Ensure `linestop_id` is not cleared
                        //         if (!$lineTyp) {
                        //             $set('lTypeError', 'Scan the valid type.');
                        //             return;
                        //         }
                        //         else
                        //         {
                        //             $set('lTypeError', null);
                        //         }
                        //     })
                        //     ->extraAttributes(fn ($get) => [
                        //         'class' => $get('lTypeError') ? 'border-red-500' : '',
                        //     ])
                        //     ->hint(fn ($get) => $get('lTypeError') ? $get('lTypeError') : null)
                        //     ->hintColor('danger'),
                        Forms\Components\Select::make('type')
                            ->label('Type')
                            ->required()
                            ->options([
                                'Sub Assembly Serial' => 'Sub Assembly Serial',
                                'Sub Assembly Lot' => 'Sub Assembly Lot',
                                'Base FG Line' => 'Base FG Line',
                                'SFG Line' => 'SFG Line',
                                'FG Line' => 'FG Line',
                                'Process Base FG Line' => 'Process Base FG Line',
                                'Process SFG Line' => 'Process SFG Line',
                                'Process FG Line' => 'Process FG Line',
                                'Machining Cell' => 'Machining Cell',
                                'Blanking Cell' => 'Blanking Cell',
                                'Forming Cell' => 'Forming Cell',
                                'Welding Cell' => 'Welding Cell',
                                'Die-Casting Cell' => 'Die-Casting Cell',
                                'Brazzing Cell' => 'Brazzing Cell',
                            ])
                            ->searchable()
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $lineTyp = $get('type');
                                // Ensure `linestop_id` is not cleared
                                if (! $lineTyp) {
                                    $set('lTypeError', 'Scan the valid type.');

                                    return;
                                } else {
                                    $set('lTypeError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('lTypeError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('lTypeError') ? $get('lTypeError') : null)
                            ->hintColor('danger'),

                        Forms\Components\TextInput::make('no_of_operation')
                            ->label('No of Operation')
                            ->required()
                            ->numeric()
                            ->reactive()
                            ->minValue(0)
                            ->maxValue(10)
                            ->placeholder('Scan the valid No Of Operatrion')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                $partValidationColumns = [
                                    'work_group1_id', 'work_group2_id', 'work_group3_id', 'work_group4_id', 'work_group5_id',
                                    'work_group6_id', 'work_group7_id', 'work_group8_id', 'work_group9_id', 'work_group10_id',
                                ];

                                foreach ($partValidationColumns as $column) {
                                    $set($column.'_visible', false);
                                    $set($column, null);
                                }

                                $partValidDispColumns = [
                                    'work_group1_actual_id', 'work_group2_actual_id', 'work_group3_actual_id', 'work_group4_actual_id', 'work_group5_actual_id',
                                    'work_group6_actual_id', 'work_group7_actual_id', 'work_group8_actual_id', 'work_group9_actual_id', 'work_group10_actual_id',
                                ];

                                foreach ($partValidDispColumns as $column) {
                                    $set($column, null);
                                }

                                if (is_numeric($state) && $state > 0) {
                                    for ($i = 1; $i <= (int) $state; $i++) {
                                        $set("work_group{$i}_id_visible", true);
                                    }
                                }
                            })
                            ->afterStateHydrated(function (callable $set, $state) {
                                for ($i = 1; $i <= 10; $i++) {
                                    $set("work_group{$i}_id_visible", $state >= $i);
                                }
                            }),

                        Forms\Components\Hidden::make('work_group1_id'),
                        // ->afterStateHydrated(function ($component, $state, Get $get, Set $set) {
                        //     if ($get('id')) {
                        //         $workGroupId = Line::where('id', $get('id'))->first()?->work_group1_id;
                        //         if ($workGroupId) {
                        //             $set('work_group1_id', $workGroupId);
                        //         } else {
                        //             $set('work_group1_id', null);
                        //         }
                        //     }
                        // }),
                        // ->required(fn (callable $get) => $get('no_of_operation') >= 1),

                        Forms\Components\TextInput::make('work_group1_actual_id')
                            ->label('Work Group Center 1')
                            ->hidden(fn (callable $get) => ! $get('work_group1_id_visible'))
                            ->default('')
                            ->reactive()
                            ->required()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup1) {
                                    $set('work_group1_actual_id', $record->workGroup1->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group1_id_error', null);
                                    $set('work_group1_id', null);

                                    return;
                                }

                                $set('work_group1_id_error', null);
                                $set('work_group1_id', null);

                                if (! $plantId) {
                                    $set('work_group1_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group1_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                // $existsInLines = Line::where(function ($query) use ($workGroupRecord) {
                                //     for ($i = 1; $i <= 10; $i++) {
                                //         $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                //     }
                                // })->count();
                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group1_actual_id', '');
                                    $set('work_group1_id', null);

                                    return;
                                } else {
                                    $set('work_group1_id_error', null);
                                    $set('work_group1_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                    'class' => $get('work_group1_id_error') ? 'border-red-500' : '',
                                ])
                            ->hint(fn ($get) => $get('work_group1_id_error'))
                            ->hintColor('danger'),

                        Forms\Components\Hidden::make('work_group2_id'),

                        Forms\Components\TextInput::make('work_group2_actual_id')
                            ->label('Work Group Center 2')
                            ->hidden(fn (callable $get) => ! $get('work_group2_id_visible'))
                            ->default('')
                            ->required()
                            ->reactive()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup2) {
                                    $set('work_group2_actual_id', $record->workGroup2->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group2_id_error', null);
                                    $set('work_group2_id', null);

                                    return;
                                }

                                $set('work_group2_id_error', null);
                                $set('work_group2_id', null);

                                if (! $plantId) {
                                    $set('work_group2_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group2_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group2_actual_id', '');
                                    $set('work_group2_id', null);

                                    return;
                                } else {
                                    $set('work_group2_id_error', null);
                                    $set('work_group2_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                    'class' => $get('work_group2_id_error') ? 'border-red-500' : '',
                                ])
                            ->hint(fn ($get) => $get('work_group2_id_error'))
                            ->hintColor('danger'),

                        Forms\Components\Hidden::make('work_group3_id'),

                        Forms\Components\TextInput::make('work_group3_actual_id')
                            ->label('Work Group Center 3')
                            ->hidden(fn (callable $get) => ! $get('work_group3_id_visible'))
                            ->default('')
                            ->required()
                            ->reactive()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup3) {
                                    $set('work_group3_actual_id', $record->workGroup3->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group3_id_error', null);
                                    $set('work_group3_id', null);

                                    return;
                                }

                                $set('work_group3_id_error', null);
                                $set('work_group3_id', null);

                                if (! $plantId) {
                                    $set('work_group3_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group3_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group3_actual_id', '');
                                    $set('work_group3_id', null);

                                    return;
                                } else {
                                    $set('work_group3_id_error', null);
                                    $set('work_group3_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                    'class' => $get('work_group3_id_error') ? 'border-red-500' : '',
                                ])
                            ->hint(fn ($get) => $get('work_group3_id_error'))
                            ->hintColor('danger'),

                        Forms\Components\Hidden::make('work_group4_id'),

                        Forms\Components\TextInput::make('work_group4_actual_id')
                            ->label('Work Group Center 4')
                            ->hidden(fn (callable $get) => ! $get('work_group4_id_visible'))
                            ->default('')
                            ->required()
                            ->reactive()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup4) {
                                    $set('work_group4_actual_id', $record->workGroup4->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group4_id_error', null);
                                    $set('work_group4_id', null);

                                    return;
                                }

                                $set('work_group4_id_error', null);
                                $set('work_group4_id', null);

                                if (! $plantId) {
                                    $set('work_group4_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group4_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group4_actual_id', '');
                                    $set('work_group4_id', null);

                                    return;
                                } else {
                                    $set('work_group4_id_error', null);
                                    $set('work_group4_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('work_group4_id_error') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('work_group4_id_error'))
                            ->hintColor('danger'),

                        Forms\Components\Hidden::make('work_group5_id'),

                        Forms\Components\TextInput::make('work_group5_actual_id')
                            ->label('Work Group Center 5')
                            ->hidden(fn (callable $get) => ! $get('work_group5_id_visible'))
                            ->default('')
                            ->required()
                            ->reactive()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup5) {
                                    $set('work_group5_actual_id', $record->workGroup5->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group5_id_error', null);
                                    $set('work_group5_id', null);

                                    return;
                                }

                                $set('work_group5_id_error', null);
                                $set('work_group5_id', null);

                                if (! $plantId) {
                                    $set('work_group5_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group5_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group5_actual_id', '');
                                    $set('work_group5_id', null);

                                    return;
                                } else {
                                    $set('work_group5_id_error', null);
                                    $set('work_group5_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('work_group5_id_error') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('work_group5_id_error'))
                            ->hintColor('danger'),

                        Forms\Components\Hidden::make('work_group6_id'),

                        Forms\Components\TextInput::make('work_group6_actual_id')
                            ->label('Work Group Center 6')
                            ->hidden(fn (callable $get) => ! $get('work_group6_id_visible'))
                            ->default('')
                            ->required()
                            ->reactive()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup6) {
                                    $set('work_group6_actual_id', $record->workGroup6->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group6_id_error', null);
                                    $set('work_group6_id', null);

                                    return;
                                }

                                $set('work_group6_id_error', null);
                                $set('work_group6_id', null);

                                if (! $plantId) {
                                    $set('work_group6_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group6_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group6_actual_id', '');
                                    $set('work_group6_id', null);

                                    return;
                                } else {
                                    $set('work_group6_id_error', null);
                                    $set('work_group6_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('work_group6_id_error') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('work_group6_id_error'))
                            ->hintColor('danger'),

                        Forms\Components\Hidden::make('work_group7_id'),

                        Forms\Components\TextInput::make('work_group7_actual_id')
                            ->label('Work Group Center 7')
                            ->hidden(fn (callable $get) => ! $get('work_group7_id_visible'))
                            ->default('')
                            ->required()
                            ->reactive()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup7) {
                                    $set('work_group7_actual_id', $record->workGroup7->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group7_id_error', null);
                                    $set('work_group7_id', null);

                                    return;
                                }

                                $set('work_group7_id_error', null);
                                $set('work_group7_id', null);

                                if (! $plantId) {
                                    $set('work_group7_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group7_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group7_actual_id', '');
                                    $set('work_group7_id', null);

                                    return;
                                } else {
                                    $set('work_group7_id_error', null);
                                    $set('work_group7_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('work_group7_id_error') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('work_group7_id_error'))
                            ->hintColor('danger'),

                        Forms\Components\Hidden::make('work_group8_id'),

                        Forms\Components\TextInput::make('work_group8_actual_id')
                            ->label('Work Group Center 8')
                            ->hidden(fn (callable $get) => ! $get('work_group8_id_visible'))
                            ->default('')
                            ->required()
                            ->reactive()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup8) {
                                    $set('work_group8_actual_id', $record->workGroup8->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group8_id_error', null);
                                    $set('work_group8_id', null);

                                    return;
                                }

                                $set('work_group8_id_error', null);
                                $set('work_group8_id', null);

                                if (! $plantId) {
                                    $set('work_group8_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group8_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group8_actual_id', '');
                                    $set('work_group8_id', null);

                                    return;
                                } else {
                                    $set('work_group8_id_error', null);
                                    $set('work_group8_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('work_group8_id_error') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('work_group8_id_error'))
                            ->hintColor('danger'),

                        Forms\Components\Hidden::make('work_group9_id'),

                        Forms\Components\TextInput::make('work_group9_actual_id')
                            ->label('Work Group Center 9')
                            ->hidden(fn (callable $get) => ! $get('work_group9_id_visible'))
                            ->default('')
                            ->required()
                            ->reactive()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup9) {
                                    $set('work_group9_actual_id', $record->workGroup9->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group9_id_error', null);
                                    $set('work_group9_id', null);

                                    return;
                                }

                                $set('work_group9_id_error', null);
                                $set('work_group9_id', null);

                                if (! $plantId) {
                                    $set('work_group9_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group9_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group9_actual_id', '');
                                    $set('work_group9_id', null);

                                    return;
                                } else {
                                    $set('work_group9_id_error', null);
                                    $set('work_group9_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('work_group9_id_error') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('work_group9_id_error'))
                            ->hintColor('danger'),

                        Forms\Components\Hidden::make('work_group10_id'),

                        Forms\Components\TextInput::make('work_group10_actual_id')
                            ->label('Work Group Center 10')
                            ->hidden(fn (callable $get) => ! $get('work_group10_id_visible'))
                            ->default('')
                            ->required()
                            ->reactive()
                            ->afterStateHydrated(function (callable $set, $record) {
                                if ($record && $record->workGroup10) {
                                    $set('work_group10_actual_id', $record->workGroup10->name);
                                }
                            })
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                // $workGroup1Id = $get('work_group1_actual_id');
                                $plantId = $get('plant_id');
                                $lineName = $get('name');

                                if ($state == null || trim($state) == '') {
                                    $set('work_group10_id_error', null);
                                    $set('work_group10_id', null);

                                    return;
                                }

                                $set('work_group10_id_error', null);
                                $set('work_group10_id', null);

                                if (! $plantId) {
                                    $set('work_group10_id_error', 'Invalid plant name.');

                                    return;
                                }

                                $workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
                                    ->where('name', $state)
                                    ->first();

                                if (! $workGroupRecord) {
                                    $set('work_group10_id_error', 'Work group does not exist for this plant in master.');

                                    return;
                                }

                                $existsInLines = Line::where('plant_id', $plantId)
                                    ->where('name', '!=', $lineName) // Exclude current line
                                    ->where(function ($query) use ($workGroupRecord) {
                                        for ($i = 1; $i <= 10; $i++) {
                                            $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
                                        }
                                    })
                                    ->count();

                                if ($existsInLines > 0) {
                                    \Filament\Notifications\Notification::make()
                                        ->title('Work Group Already Assigned')
                                        ->body("The work group '{$state}' is already assigned to a line.")
                                        ->danger()
                                        ->send();
                                    $set('work_group10_actual_id', '');
                                    $set('work_group10_id', null);

                                    return;
                                } else {
                                    $set('work_group10_id_error', null);
                                    $set('work_group10_id', $workGroupRecord->id);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('work_group10_id_error') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('work_group10_id_error'))
                            ->hintColor('danger'),

                        // Forms\Components\TextInput::make('group_work_center')
                        //     ->label('Group Work Center')
                        //     ->placeholder('Scan the valid Group Work Center'),
                        Forms\Components\TextInput::make('id')
                            ->hidden()
                            ->readOnly(),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                // Tables\Columns\TextColumn::make('id')
                //     ->label('ID')
                //     ->numeric()
                //     ->sortable(),
                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.name')
                    ->label('Plant')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('block.name')
                    ->label('Block')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('name')
                    ->label('Line')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('type')
                    ->label('Type')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('no_of_operation')
                    ->label('No of Operation')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup1.name')
                    ->label('Work Group Center 1')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup1.operation_number')
                    ->label('Operation Number 1')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup2.name')
                    ->label('Work Group Center 2')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup2.operation_number')
                    ->label('Operation Number 2')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup3.name')
                    ->label('Work Group Center 3')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup3.operation_number')
                    ->label('Operation Number 3')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup4.name')
                    ->label('Work Group Center 4')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup4.operation_number')
                    ->label('Operation Number 4')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup5.name')
                    ->label('Work Group Center 5')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup5.operation_number')
                    ->label('Operation Number 5')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup6.name')
                    ->label('Work Group Center 6')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup6.operation_number')
                    ->label('Operation Number 6')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup7.name')
                    ->label('Work Group Center 7')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup7.operation_number')
                    ->label('Operation Number 7')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup8.name')
                    ->label('Work Group Center 8')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup8.operation_number')
                    ->label('Operation Number 8')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup9.name')
                    ->label('Work Group Center 9')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup9.operation_number')
                    ->label('Operation Number 9')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup10.name')
                    ->label('Work Group Center 10')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('workGroup10.operation_number')
                    ->label('Operation Number 10')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->alignCenter()
                    ->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 Lines')
                    ->color('warning')
                    ->importer(LineImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import line');
                    }),
                ExportAction::make()
                    ->label('Export Lines')
                    ->color('warning')
                    ->exporter(LineExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export line');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListLines::route('/'),
            'create' => Pages\CreateLine::route('/create'),
            'view' => Pages\ViewLine::route('/{record}'),
            'edit' => Pages\EditLine::route('/{record}/edit'),
        ];
    }

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