<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ActivityResource\Pages;
use App\Filament\Resources\ActivityResource\RelationManagers;
use App\Models\Activity;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use App\Models\Attendance;
use App\Models\User;

class ActivityResource extends Resource
{
    protected static ?string $model = Activity::class;

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

    protected static ?string $navigationLabel = 'Aktivitas';

    protected static ?string $navigationGroup = 'Kehadiran';

    protected static ?int $navigationSort = 3;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Dasar')
                    ->schema([
                        Forms\Components\Select::make('user_id')
                            ->label('Karyawan')
                            ->options(function () {
                                $user = auth()->user();
                                $query = User::whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin'));

                                // Admin biasa hanya lihat company mereka
                                if ($user && !$user->hasRole('super_admin')) {
                                    $query->where('company_id', $user->company_id);
                                }

                                return $query->pluck('name', 'id');
                            })
                            ->searchable()
                            ->preload()
                            ->required()
                            ->live()
                            ->afterStateUpdated(fn (Forms\Set $set) => $set('attendance_id', null)),
                        Forms\Components\Select::make('attendance_id')
                            ->label('Presensi')
                            ->options(function (Forms\Get $get) {
                                $userId = $get('user_id');
                                if (!$userId) {
                                    return [];
                                }

                                return Attendance::where('user_id', $userId)
                                    ->whereNotNull('check_in_time')
                                    ->orderBy('date', 'desc')
                                    ->get()
                                    ->mapWithKeys(function ($attendance) {
                                        $date = $attendance->date->format('d/m/Y');
                                        $checkIn = $attendance->check_in_time ? \Carbon\Carbon::parse($attendance->check_in_time)->format('H:i') : '-';
                                        return [$attendance->id => "{$date} (Check-in: {$checkIn})"];
                                    });
                            })
                            ->searchable()
                            ->preload()
                            ->required()
                            ->helperText('Aktivitas hanya bisa dibuat jika ada presensi dengan check-in')
                            ->live()
                            ->afterStateUpdated(function (Forms\Set $set, $state) {
                                if ($state) {
                                    $attendance = Attendance::find($state);
                                    if ($attendance) {
                                        $set('date', $attendance->date->format('Y-m-d'));
                                    }
                                }
                            }),
                        Forms\Components\DatePicker::make('date')
                            ->label('Tanggal')
                            ->required()
                            ->disabled()
                            ->dehydrated()
                            ->displayFormat('d/m/Y')
                            ->helperText('Tanggal otomatis mengikuti presensi yang dipilih'),
                    ])
                    ->columns(3),

                Forms\Components\Section::make('Waktu Aktivitas')
                    ->schema([
                        Forms\Components\TimePicker::make('start_time')
                            ->label('Jam Mulai')
                            ->required()
                            ->seconds(false)
                            ->native(false)
                            ->displayFormat('H:i')
                            ->prefixIcon('heroicon-o-clock'),
                        Forms\Components\TimePicker::make('end_time')
                            ->label('Jam Selesai')
                            ->required()
                            ->seconds(false)
                            ->native(false)
                            ->displayFormat('H:i')
                            ->prefixIcon('heroicon-o-clock')
                            ->after('start_time'),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Detail Aktivitas')
                    ->schema([
                        Forms\Components\Textarea::make('activity')
                            ->label('Aktivitas')
                            ->required()
                            ->rows(3)
                            ->helperText('Deskripsi aktivitas yang dilakukan')
                            ->columnSpanFull(),
                        Forms\Components\Textarea::make('output')
                            ->label('Output/Hasil')
                            ->rows(3)
                            ->helperText('Output atau hasil dari aktivitas')
                            ->columnSpanFull(),
                        Forms\Components\Textarea::make('notes')
                            ->label('Catatan')
                            ->rows(2)
                            ->helperText('Catatan tambahan (opsional)')
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('user.name')
                    ->label('Karyawan')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('user.employee_id')
                    ->label('NIP/ID')
                    ->searchable()
                    ->toggleable(),
                Tables\Columns\TextColumn::make('date')
                    ->label('Tanggal')
                    ->date('d/m/Y')
                    ->sortable(),
                Tables\Columns\TextColumn::make('start_time')
                    ->label('Mulai')
                    ->dateTime('H:i')
                    ->sortable(),
                Tables\Columns\TextColumn::make('end_time')
                    ->label('Selesai')
                    ->dateTime('H:i')
                    ->sortable(),
                Tables\Columns\TextColumn::make('activity')
                    ->label('Aktivitas')
                    ->limit(50)
                    ->tooltip(fn ($record) => $record->activity)
                    ->wrap(),
                Tables\Columns\IconColumn::make('output')
                    ->label('Output')
                    ->boolean(fn ($record) => !empty($record->output))
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger'),
                Tables\Columns\TextColumn::make('attendance.id')
                    ->label('Presensi ID')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Dibuat')
                    ->dateTime('d/m/Y H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('user_id')
                    ->label('Karyawan')
                    ->relationship('user', 'name')
                    ->searchable()
                    ->preload(),
                Tables\Filters\Filter::make('date')
                    ->form([
                        Forms\Components\DatePicker::make('date_from')
                            ->label('Dari Tanggal'),
                        Forms\Components\DatePicker::make('date_to')
                            ->label('Sampai Tanggal'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['date_from'],
                                fn (Builder $query, $date): Builder => $query->whereDate('date', '>=', $date),
                            )
                            ->when(
                                $data['date_to'],
                                fn (Builder $query, $date): Builder => $query->whereDate('date', '<=', $date),
                            );
                    }),
                Tables\Filters\Filter::make('has_output')
                    ->label('Ada Output')
                    ->query(fn (Builder $query): Builder => $query->whereNotNull('output')->where('output', '!=', '')),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('date', 'desc');
    }

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

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

    /**
     * Hide super_admin activities from all lists
     */
    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();

        // Hide super_admin activities (using Spatie roles)
        $query->whereHas('user', function ($q) {
            $q->whereDoesntHave('roles', function ($r) {
                $r->where('name', 'super_admin');
            });
        });

        // Admin biasa hanya lihat company mereka
        $user = auth()->user();
        if ($user && !$user->hasRole('super_admin')) {
            $query->whereHas('user', function ($q) use ($user) {
                $q->where('company_id', $user->company_id);
            });
        }

        return $query;
    }
}
