<?php

namespace App\Filament\Construction\Resources;

use App\Filament\Construction\Concerns\AuthorizesConstructionResource;
use App\Filament\Construction\Resources\DailyProgressReportResource\Pages;
use App\Models\DailyProgressReport;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class DailyProgressReportResource extends Resource
{
    use AuthorizesConstructionResource;

    protected static ?string $model = DailyProgressReport::class;

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

    protected static ?string $navigationGroup = 'Site Reports';

    protected static ?string $navigationLabel = 'Daily Progress Reports';

    protected static ?int $navigationSort = 1;

    protected static function viewPermission(): string
    {
        return 'cn_view_dpr';
    }

    protected static function managePermission(): string
    {
        return 'cn_manage_dpr';
    }

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make()->schema([
                Forms\Components\Select::make('project_id')
                    ->relationship('project', 'name')
                    ->required()
                    ->searchable()
                    ->preload(),
                Forms\Components\Select::make('user_id')
                    ->relationship('user', 'name')
                    ->default(fn (): ?int => auth()->id())
                    ->required()
                    ->searchable()
                    ->preload(),
                Forms\Components\DatePicker::make('report_date')
                    ->default(now())
                    ->required(),
                Forms\Components\Textarea::make('work_description')
                    ->required()
                    ->columnSpanFull(),
                Forms\Components\TextInput::make('labor_count')
                    ->numeric()
                    ->default(0)
                    ->required(),
                Forms\Components\Select::make('weather')
                    ->options([
                        'sunny' => 'Sunny',
                        'cloudy' => 'Cloudy',
                        'rainy' => 'Rainy',
                        'windy' => 'Windy',
                        'stormy' => 'Stormy',
                    ]),
                Forms\Components\Textarea::make('notes')
                    ->columnSpanFull(),
            ])->columns(2),

            Forms\Components\Section::make('Site Photos & Documents')
                ->icon('heroicon-o-camera')
                ->description('Upload site photos, work progress images, or PDF reports')
                ->schema([
                    Forms\Components\FileUpload::make('attachments')
                        ->label('Attachments')
                        ->disk('public')
                        ->multiple()
                        ->directory('dpr-attachments')
                        ->visibility('public')
                        ->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp', 'application/pdf'])
                        ->maxSize(5120)
                        ->downloadable()
                        ->openable()
                        ->imagePreviewHeight('150')
                        ->reorderable()
                        ->helperText('Images or PDF — max 5 MB each')
                        ->columnSpanFull(),
                ]),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('report_date')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('project.name')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('user.name')
                    ->label('Reported By')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('work_description')
                    ->limit(50)
                    ->searchable(),
                Tables\Columns\TextColumn::make('labor_count')
                    ->label('Labor')
                    ->sortable(),
                Tables\Columns\TextColumn::make('weather')
                    ->badge()
                    ->toggleable(),
                Tables\Columns\IconColumn::make('attachments')
                    ->label('Files')
                    ->boolean()
                    ->getStateUsing(fn (DailyProgressReport $record): bool => ! empty($record->attachments))
                    ->trueIcon('heroicon-o-paper-clip')
                    ->falseIcon('heroicon-o-minus')
                    ->trueColor('success')
                    ->falseColor('gray'),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('report_date', 'desc')
            ->filters([
                Tables\Filters\SelectFilter::make('project')
                    ->relationship('project', 'name')
                    ->searchable()
                    ->preload(),
                Tables\Filters\SelectFilter::make('user')
                    ->relationship('user', 'name')
                    ->label('Reported By')
                    ->searchable()
                    ->preload(),
                Tables\Filters\Filter::make('report_date')
                    ->form([
                        Forms\Components\DatePicker::make('from'),
                        Forms\Components\DatePicker::make('until'),
                    ])
                    ->query(function ($query, array $data) {
                        return $query
                            ->when($data['from'], fn ($q, $date) => $q->whereDate('report_date', '>=', $date))
                            ->when($data['until'], fn ($q, $date) => $q->whereDate('report_date', '<=', $date));
                    }),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListDailyProgressReports::route('/'),
            'create' => Pages\CreateDailyProgressReport::route('/create'),
            'edit' => Pages\EditDailyProgressReport::route('/{record}/edit'),
        ];
    }
}
