<?php

namespace App\Filament\Pages;

use App\Models\AdminsTask;
use App\Models\AdminsTaskStatus;
use App\Models\User;
use BezhanSalleh\FilamentShield\Traits\HasPageShield;
use Filament\Actions\Action;
use Filament\Forms;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Infolists\Components\TextEntry;
use Filament\Support\Enums\MaxWidth;
use Heloufir\FilamentKanban\Filament\KanbanBoard;
use Heloufir\FilamentKanban\ValueObjects\KanbanStatuses;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class AdminTasksKanbanBoard extends KanbanBoard
{
    use HasPageShield;

    protected static ?string $navigationIcon = 'heroicon-o-clipboard-document-list';

    protected static ?int $navigationSort = 6;

    protected bool $showViewTabs = true;

    protected bool $persistCurrentTab = true;

    protected bool $shouldShowFilters = false;

    public static function getNavigationLabel(): string
    {
        return __('admins_task.admins_tasks');
    }

    public function getTitle(): string|Htmlable
    {
        return __('admins_task.admins_tasks');
    }

    public static function getModelLabel(): string
    {
        return __('admins_task.admins_task');
    }

    public static function getPluralModelLabel(): string
    {
        return __('admins_task.admins_tasks');
    }

    public static function getNavigationGroup(): ?string
    {
        return __('common.navigation.group.project_management');
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view_any_admins::task');
    }

    public function model(): string
    {
        return AdminsTask::class;
    }

    public function getStatuses(): KanbanStatuses
    {
        return KanbanStatuses::make(
            AdminsTaskStatus::all()
        );
    }

    public function query(Builder $query): Builder
    {
        return $query
            ->with(['assignedUsers', 'status', 'media'])
            ->when($this->filtersData['assigned_to'] ?? null, function ($query, $userId) {
                $query->whereHas('assignedUsers', function ($q) use ($userId) {
                    $q->where('users.id', $userId);
                });
            })
            ->when($this->filtersData['start_date_from'] ?? null, function ($query, $date) {
                $query->where('start_date', '>=', $date);
            })
            ->when($this->filtersData['start_date_to'] ?? null, function ($query, $date) {
                $query->where('start_date', '<=', $date);
            });
    }

    public function recordForm(): array
    {
        return [
            Forms\Components\Section::make(__('admins_task.basic_information'))
                ->schema([
                    Forms\Components\Grid::make(2)
                        ->schema([
                            Forms\Components\TextInput::make('name')
                                ->label(__('admins_task.name'))
                                ->placeholder(__('admins_task.name_placeholder'))
                                ->helperText(__('admins_task.name_helper'))
                                ->required()
                                ->maxLength(255)
                                ->columnSpanFull(),

                            Forms\Components\Textarea::make('description')
                                ->label(__('admins_task.description'))
                                ->placeholder(__('admins_task.description_placeholder'))
                                ->helperText(__('admins_task.description_helper'))
                                ->rows(3)
                                ->columnSpanFull(),
                        ]),
                ]),

            Forms\Components\Section::make(__('admins_task.dates_information'))
                ->schema([
                    Forms\Components\Grid::make(2)
                        ->schema([
                            Forms\Components\DateTimePicker::make('start_date')
                                ->label(__('admins_task.start_date'))
                                ->helperText(__('admins_task.start_date_helper'))
                                ->seconds(false),

                            Forms\Components\DateTimePicker::make('end_date')
                                ->label(__('admins_task.end_date'))
                                ->helperText(__('admins_task.end_date_helper'))
                                ->seconds(false)
                                ->after('start_date'),
                        ]),
                ]),

            Forms\Components\Section::make(__('admins_task.assignment_information'))
                ->schema([
                    Forms\Components\Grid::make(2)
                        ->schema([
                            Forms\Components\Select::make('status_id')
                                ->label(__('admins_task.status'))
                                ->relationship('status', 'title')
                                ->required()
                                ->searchable()
                                ->preload(),

                            Forms\Components\Select::make('assignedUsers')
                                ->label(__('admins_task.assigned_users'))
                                ->helperText(__('admins_task.assigned_users_helper'))
                                ->relationship('assignedUsers', 'name', fn (Builder $query) => $query->whereNull('association_id'))
                                ->multiple()
                                ->searchable()
                                ->preload()
                                ->getOptionLabelFromRecordUsing(fn (User $record): string => "{$record->name} ({$record->email})")
                                ->columnSpanFull(),
                        ]),
                ]),

            Forms\Components\Section::make(__('admins_task.attachments'))
                ->schema([
                    SpatieMediaLibraryFileUpload::make('task_attachments')
                        ->label(__('admins_task.task_attachments'))
                        ->helperText(__('admins_task.task_attachments_helper'))
                        ->collection('task_attachments')
                        ->visibility('private')
                        ->multiple()
                        ->reorderable()
                        ->openable()
                        ->downloadable()
                        ->deletable()
                        ->columnSpanFull(),
                ])
                ->collapsible(),

            Forms\Components\Section::make(__('admins_task.checklist'))
                ->schema([
                    Forms\Components\Repeater::make('checklistItems')
                        ->label(__('admins_task.checklist_items'))
                        ->relationship('checklistItems')
                        ->schema([
                            Forms\Components\Grid::make(3)
                                ->schema([
                                    Forms\Components\TextInput::make('title')
                                        ->label(__('admins_task.checklist_item_title'))
                                        ->required()
                                        ->maxLength(255)
                                        ->columnSpan(2),

                                    Forms\Components\Checkbox::make('is_completed')
                                        ->label(__('admins_task.completed'))
                                        ->columnSpan(1)
                                        ->live()
                                        ->afterStateUpdated(function ($state, $record, Forms\Set $set) {
                                            if ($record && $record->exists) {
                                                if ($state) {
                                                    $set('completed_at', now());
                                                    $set('completed_by', Auth::id());
                                                } else {
                                                    $set('completed_at', null);
                                                    $set('completed_by', null);
                                                }
                                            }
                                        }),

                                    Forms\Components\Textarea::make('description')
                                        ->label(__('admins_task.checklist_item_description'))
                                        ->rows(2)
                                        ->columnSpanFull(),

                                    SpatieMediaLibraryFileUpload::make('checklist_item_attachments')
                                        ->label(__('admins_task.checklist_item_attachments'))
                                        ->helperText(__('admins_task.checklist_item_attachments_helper'))
                                        ->collection('checklist_item_attachments')
                                        ->visibility('private')
                                        ->multiple()
                                        ->reorderable()
                                        ->openable()
                                        ->downloadable()
                                        ->deletable()
                                        ->columnSpanFull(),
                                ]),
                        ])
                        ->reorderable()
                        ->orderColumn('order_column')
                        ->addActionLabel(__('admins_task.add_checklist_item'))
                        ->collapsible()
                        ->itemLabel(fn (array $state): ?string => $state['title'] ?? null)
                        ->columnSpanFull(),
                ])
                ->collapsible()
                ->collapsed(fn ($record) => ! $record || $record->checklistItems()->count() === 0),

            Forms\Components\Hidden::make('created_by')
                ->default(fn () => Auth::id()),
        ];
    }

    public function recordInfolist(): array
    {
        return [
            \Filament\Infolists\Components\Section::make(__('admins_task.basic_information'))
                ->schema([
                    \Filament\Infolists\Components\Grid::make(2)
                        ->schema([
                            TextEntry::make('name')
                                ->label(__('admins_task.name'))
                                ->size(TextEntry\TextEntrySize::Large)
                                ->weight('bold')
                                ->columnSpanFull(),

                            TextEntry::make('description')
                                ->label(__('admins_task.description'))
                                ->html()
                                ->columnSpanFull(),

                            TextEntry::make('start_date')
                                ->label(__('admins_task.start_date'))
                                ->date(),

                            TextEntry::make('end_date')
                                ->label(__('admins_task.end_date'))
                                ->date(),
                        ]),
                ]),

            \Filament\Infolists\Components\Section::make(__('admins_task.assignment_information'))
                ->schema([
                    \Filament\Infolists\Components\Grid::make(2)
                        ->schema([
                            TextEntry::make('status.title')
                                ->label(__('admins_task.status'))
                                ->badge()
                                ->color(fn ($record) => match ($record->status?->key) {
                                    'pending' => 'warning',
                                    'in_progress' => 'info',
                                    'completed' => 'success',
                                    'cancelled' => 'danger',
                                    'on_hold' => 'gray',
                                    default => 'gray'
                                }),

                            TextEntry::make('assignedUsers.name')
                                ->label(__('admins_task.assigned_users'))
                                ->listWithLineBreaks()
                                ->limitList(3)
                                ->expandableLimitedList()
                                ->prefix('- ')
                                ->columnSpanFull(),
                        ]),
                ]),

            \Filament\Infolists\Components\Section::make(__('admins_task.checklist'))
                ->schema([
                    \Filament\Infolists\Components\RepeatableEntry::make('checklistItems')
                        ->label(__('admins_task.checklist_items'))
                        ->schema([
                            \Filament\Infolists\Components\Grid::make(3)
                                ->schema([
                                    TextEntry::make('title')
                                        ->label(__('admins_task.checklist_item_title'))
                                        ->columnSpan(2),

                                    \Filament\Infolists\Components\IconEntry::make('is_completed')
                                        ->label(__('admins_task.completed'))
                                        ->boolean()
                                        ->trueIcon('heroicon-o-check-circle')
                                        ->falseIcon('heroicon-o-x-circle')
                                        ->trueColor('success')
                                        ->falseColor('danger')
                                        ->columnSpan(1),

                                    TextEntry::make('description')
                                        ->label(__('admins_task.checklist_item_description'))
                                        ->columnSpanFull(),

                                    // TextEntry::make('completed_at')
                                    //     ->label('Completed At')
                                    //     ->date()
                                    //     ->placeholder('Not completed')
                                    //     ->columnSpan(1),

                                    // TextEntry::make('completedBy.name')
                                    //     ->label('Completed By')
                                    //     ->placeholder('Not completed')
                                    //     ->columnSpan(2),
                                ]),
                        ])
                        ->columnSpanFull(),
                ])
                ->collapsible()
                ->collapsed(fn ($record) => ! $record || $record->checklistItems()->count() === 0),

            \Filament\Infolists\Components\Section::make(__('admins_task.attachments'))
                ->schema([
                    \Filament\Infolists\Components\RepeatableEntry::make('media')
                        ->label(__('admins_task.task_attachments'))
                        ->schema([
                            TextEntry::make('name')
                                ->label('File Name'),
                            TextEntry::make('human_readable_size')
                                ->label('Size'),
                        ])
                        ->columnSpanFull(),
                ])
                ->collapsible()
                ->collapsed(fn ($record) => ! $record || $record->getMedia('task_attachments')->count() === 0),

            \Filament\Infolists\Components\Section::make(__('admins_task.metadata'))
                ->schema([
                    \Filament\Infolists\Components\Grid::make(2)
                        ->schema([
                            TextEntry::make('creator.name')
                                ->label(__('admins_task.created_by')),

                            TextEntry::make('created_at')
                                ->label(__('admins_task.created_at'))
                                ->date(),

                            TextEntry::make('updated_at')
                                ->label(__('admins_task.updated_at'))
                                ->date()
                                ->columnSpanFull(),
                        ]),
                ]),
        ];
    }

    public function filters(Form $form): Form
    {
        return $form
            ->statePath('filtersData')
            ->live()
            ->debounce()
            ->schema($this->filtersSchema());
    }

    protected function filtersSchema(): array
    {
        return [
            Grid::make(3)
                ->schema([
                    Select::make('assigned_to')
                        ->label('Assigned To')
                        ->options(User::pluck('name', 'id'))
                        ->searchable(),

                    DatePicker::make('start_date_from')
                        ->label('Start Date From'),

                    DatePicker::make('start_date_to')
                        ->label('Start Date To'),
                ]),
        ];
    }

    protected function getHeaderActions(): array
    {
        return [
            // ...
            $this->addAction()
                ->label(__('admins_task.create_task'))
                ->modalHeading(__('admins_task.create_task')),
            Action::make('view_chart')
                ->label(__('widgets.view_chart'))
                ->icon('heroicon-o-chart-bar')
                ->color('success')
                ->slideOver()
                ->modalWidth(MaxWidth::FiveExtraLarge)
                ->modalHeading('')
                ->modalSubmitAction(false)
                ->modalCancelAction(false)
                ->modalContent(fn () => view('filament.custom.tasks-gantt-modal')),
        ];
    }

    public function recordActions(): array
    {
        return [
            $this->viewAction(),
            $this->editAction(),
            $this->deleteAction(),
        ];
    }
}
