<?php

namespace App\Filament\Pages;

use App\Models\CustomerPoMaster;
use App\Models\Plant;
use App\Models\ProductionPlan;
use App\Models\WireMasterPacking;
use Filament\Facades\Filament;
use Filament\Pages\Page;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Form;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\ViewField;
use Filament\Notifications\Notification;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\Hidden;
use Illuminate\Support\Facades\Auth;

class ProductionCalender extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static string $view = 'filament.pages.production-calender';

    protected static ?string $navigationGroup = 'Production';

    use InteractsWithForms;

    protected $listeners = ['setWorkingDays'];

    public $pId;

    public array $filters = [];

    public function setWorkingDays($days = null)
    {
        $this->form->fill([
            'working_days' => $days ?? 0,
        ]);
    }

    public function form(Form $form): Form
    {
        return $form
            ->statePath('filters')
            ->schema([
                Section::make('')
                    ->schema([
                        Select::make('plant_id')
                            ->label('Plant')
                            ->reactive()
                            //->options(Plant::pluck('name', 'id'))
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;
                                return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                            })
                            ->columnSpan(['default' => 10, 'sm' => 7])
                            ->required()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('working_days', null);
                            }),
                        TextInput::make('working_days')
                            ->label('No. of Working Days')
                            ->numeric()
                            ->readOnly()
                            ->columnSpan(['default' => 10, 'sm' => 2])
                            ->required()
                            ->minValue(0)
                            ->maxValue(31)
                            ->placeholder('Enter working days')
                            ->id('working_days'),

                        Hidden::make('month')
                            ->label('Month')
                            ->id('month'),

                        Hidden::make('year')
                            ->label('Year')
                            ->id('year'),

                        Hidden::make('selected_dates')
                            ->label('Selected Dates')
                            ->id('selected_dates'),

                        ViewField::make('save')
                            ->view('forms.save')
                            ->columnSpan(['default' => 10, 'sm' => 1]),

                        ViewField::make('calendar')
                            ->view('forms.calendar')
                            ->columnspan(10),
                    ])
                    ->columns(10)
            ]);
    }

    public function saveWorkingDays(){
        $plantId = $this->filters['plant_id'] ?? null;
        $workingDays = $this->filters['working_days'] ?? null;
        $month = $this->filters['month'] ?? null;
        $year = $this->filters['year'] ?? null;
        $dates = $this->filters['selected_dates'] ?? null;

        if (!$plantId) {
            Notification::make()
                ->title('Unknown Plant')
                ->body("Please select a plant first!")
                ->danger()
                ->send();
            return;
        }
        else if (!$workingDays) {
            Notification::make()
                ->title('Unknown Working Days')
                ->body("Working days can't be empty!")
                ->danger()
                ->send();
            return;
        }
        else if (!$month) {
            Notification::make()
                ->title('Unknown Month')
                ->body("month can't be empty!")
                ->danger()
                ->send();
            return;
        }
        else if (!$year) {
            Notification::make()
                ->title('Unknown Year')
                ->body("Year can't be empty!")
                ->danger()
                ->send();
            return;
        }

        $updated = ProductionPlan::where('plant_id', $plantId)
        ->whereMonth('created_at', $month)
        ->whereYear('created_at', $year)
        ->update([
            'working_days' => $workingDays,
            'leave_dates' => $dates,
            'updated_at' => now(),
        ]);

        if ($updated) {
            Notification::make()
                ->title('Success')
                ->body("Working days updated successfully!")
                ->success()
                ->send();
        } else {
            Notification::make()
                ->title('No Records Updated')
                ->body("No production plans found for this plant and month.")
                ->warning()
                ->send();
        }
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view production calender page');
    }

}
