<?php

namespace App\Filament\Employee\Resources;

use App\Filament\Employee\Resources\MyActivityResource\Pages;
use App\Models\Activity;
use App\Models\Attendance;
use Carbon\Carbon;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

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

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

    protected static ?string $navigationGroup = 'Aktivitas Saya';

    protected static ?string $navigationLabel = 'Catatan Aktivitas';

    protected static ?string $modelLabel = 'Aktivitas';

    protected static ?string $pluralModelLabel = 'Catatan Aktivitas';

    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {
        $user = auth()->user();

        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Aktivitas')
                    ->schema([
                        Forms\Components\Hidden::make('user_id')
                            ->default($user->id),

                        Forms\Components\DatePicker::make('date')
                            ->label('Tanggal')
                            ->required()
                            ->native(false)
                            ->displayFormat('d M Y')
                            ->maxDate(now())
                            ->default(request()->get('date', now()))
                            ->live()
                            ->afterStateUpdated(function (Forms\Set $set, $state) use ($user) {
                                if ($state) {
                                    $attendance = Attendance::where('user_id', $user->id)
                                        ->whereDate('date', $state)
                                        ->first();
                                    $set('attendance_id', $attendance?->id);
                                }
                            }),

                        Forms\Components\Select::make('attendance_id')
                            ->label('Kehadiran Terkait')
                            ->options(function () use ($user) {
                                return Attendance::where('user_id', $user->id)
                                    ->orderBy('date', 'desc')
                                    ->limit(30)
                                    ->get()
                                    ->pluck('date', 'id')
                                    ->map(fn($date) => Carbon::parse($date)->translatedFormat('D, d M Y'));
                            })
                            ->searchable()
                            ->default(request()->get('attendance_id'))
                            ->helperText('Opsional - tautkan dengan data kehadiran'),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Waktu Aktivitas')
                    ->schema([
                        Forms\Components\TimePicker::make('start_time')
                            ->label('Jam Mulai')
                            ->required()
                            ->seconds(false)
                            ->native(false),

                        Forms\Components\TimePicker::make('end_time')
                            ->label('Jam Selesai')
                            ->required()
                            ->seconds(false)
                            ->native(false)
                            ->after('start_time'),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Detail Aktivitas')
                    ->schema([
                        Forms\Components\Textarea::make('activity')
                            ->label('Uraian Aktivitas')
                            ->required()
                            ->rows(3)
                            ->placeholder('Jelaskan aktivitas yang dilakukan...')
                            ->helperText('Deskripsi detail aktivitas yang dikerjakan')
                            ->columnSpanFull(),

                        Forms\Components\Textarea::make('output')
                            ->label('Output/Hasil')
                            ->rows(3)
                            ->placeholder('Hasil atau output dari aktivitas...')
                            ->helperText('Hasil atau deliverable dari aktivitas')
                            ->columnSpanFull(),

                        Forms\Components\Textarea::make('notes')
                            ->label('Catatan Tambahan')
                            ->rows(2)
                            ->placeholder('Catatan tambahan (opsional)...')
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('date')
                    ->label('Tanggal')
                    ->date('D, d M Y')
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('start_time')
                    ->label('Mulai')
                    ->time('H:i'),

                Tables\Columns\TextColumn::make('end_time')
                    ->label('Selesai')
                    ->time('H:i'),

                Tables\Columns\TextColumn::make('duration')
                    ->label('Durasi')
                    ->getStateUsing(function ($record) {
                        if (!$record->start_time || !$record->end_time) return '-';
                        $start = Carbon::parse($record->start_time);
                        $end = Carbon::parse($record->end_time);
                        $mins = $end->diffInMinutes($start);
                        $hours = floor($mins / 60);
                        $remainMins = $mins % 60;
                        return "{$hours}j {$remainMins}m";
                    }),

                Tables\Columns\TextColumn::make('activity')
                    ->label('Aktivitas')
                    ->limit(50)
                    ->tooltip(fn($record) => $record->activity)
                    ->wrap(),

                Tables\Columns\IconColumn::make('has_output')
                    ->label('Output')
                    ->boolean()
                    ->getStateUsing(fn($record) => !empty($record->output))
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Dibuat')
                    ->dateTime('d M Y H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('date', 'desc')
            ->filters([
                Tables\Filters\Filter::make('date')
                    ->form([
                        Forms\Components\DatePicker::make('from')
                            ->label('Dari Tanggal'),
                        Forms\Components\DatePicker::make('until')
                            ->label('Sampai Tanggal'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'], fn(Builder $query, $date) => $query->whereDate('date', '>=', $date))
                            ->when($data['until'], fn(Builder $query, $date) => $query->whereDate('date', '<=', $date));
                    }),
                Tables\Filters\Filter::make('no_output')
                    ->label('Tanpa Output')
                    ->query(fn(Builder $query) => $query->where(function ($q) {
                        $q->whereNull('output')->orWhere('output', '');
                    })),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->emptyStateHeading('Belum ada catatan aktivitas')
            ->emptyStateDescription('Mulai catat aktivitas harian Anda.')
            ->emptyStateIcon('heroicon-o-clipboard-document-list');
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListMyActivities::route('/'),
            'create' => Pages\CreateMyActivity::route('/create'),
            'view' => Pages\ViewMyActivity::route('/{record}'),
            'edit' => Pages\EditMyActivity::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->where('user_id', auth()->id())
            ->orderBy('date', 'desc');
    }

    public static function getNavigationBadge(): ?string
    {
        // Count activities without output this month
        $user = auth()->user();
        $startOfMonth = now()->startOfMonth();
        $today = now();

        $count = Activity::where('user_id', $user->id)
            ->whereBetween('date', [$startOfMonth, $today])
            ->where(function ($q) {
                $q->whereNull('output')->orWhere('output', '');
            })
            ->count();

        return $count > 0 ? (string) $count : null;
    }

    public static function getNavigationBadgeColor(): ?string
    {
        return 'warning';
    }
}
