<?php

namespace App\Filament\App\Resources;

use App\Filament\App\Resources\HasilRapatResource\Pages;
use App\Filament\App\Resources\HasilRapatResource\RelationManagers;
use App\Models\AgendaRapat;
use App\Models\HasilRapat;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Components\Section;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Support\Enums\Alignment;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;


class HasilRapatResource extends Resource
{
    protected static ?string $model = HasilRapat::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static bool $shouldRegisterNavigation = false;

    public static function form(Form $form): Form
    {
        $hasilRapat = $form->getRecord(); // Ini instance HasilRapat
        $agendaRapat = AgendaRapat::find($hasilRapat->agenda_rapat_id); // Ambil agenda rapat berdasarkan id

        return $form
            ->schema([
                Section::make("Hasil Rapat")
                    ->schema([

                        Forms\Components\Textarea::make('risalah_rapat')
                            ->columnSpanFull(),
                        Forms\Components\Textarea::make('deskripsi')
                            ->columnSpanFull(),
                        Forms\Components\Repeater::make('dokumen')
                            ->relationship('dokumen')
                            //->addActionAlignment(Alignment::Start)
                            ->label('Dokumen Hasil Rapat')
                            ->addActionLabel('Tambah Dokumen')
                            ->itemLabel(fn(array $state): ?string => $state['name'] ?? null)
                            ->grid(2)
                            ->collapsible()
                            ->schema([
                                Forms\Components\TextInput::make('name')
                                    ->label('Nama Dokumen')
                                    ->required()
                                    ->columnSpanFull(),
                                Forms\Components\TextArea::make('deskripsi')
                                    ->label('Deskripsi')
                                    ->columnSpanFull(),
                                Forms\Components\FileUpload::make('dokumen')
                                    ->label('Dokumen')
                                    ->maxSize(1024 * 1024 * 2)
                                    ->disk('public')
                                    ->directory('dokumen-rapat')
                                    ->required()
                                    ->downloadable()
                                    ->columnSpanFull(),
                            ]),
                        Forms\Components\Repeater::make('foto')
                            ->relationship('foto')
                            //->addActionAlignment(Alignment::Start)
                            ->label('Foto Hasil Rapat')
                            ->addActionLabel('Tambah Foto')
                            ->schema([
                                Forms\Components\FileUpload::make('foto')
                                    ->label('Foto')
                                    ->image()
                                    ->maxSize(1024 * 1024 * 5)
                                    ->disk('public')
                                    ->directory('foto-rapat')
                                    ->required()
                                    ->downloadable()
                                    ->columnSpanFull(),
                            ]),
                    ]),
                Section::make("Tindak Lanjut")->schema([
                    Forms\Components\Repeater::make('TindakLanjut')
                        ->relationship('TindakLanjut')
                        ->label('')
                        ->addActionLabel('Tambah PIC')
                        ->schema([
                            Forms\Components\Hidden::make('agenda_rapat_id')
                                ->default(fn() => $hasilRapat->agenda_rapat_id),
                            Forms\Components\Select::make('user_id')
                                ->searchable()
                                ->label('PIC')
                                ->options(function () use ($agendaRapat) {
                                    return self::ambilPesertaRapat($agendaRapat);
                                })
                                ->getSearchResultsUsing(function (string $search) use ($agendaRapat) {
                                    return self::SearchPesertaRapat($search, $agendaRapat);
                                })
                                ->getOptionLabelUsing(function ($value) {
                                    $user = User::with('departemen')->find($value);
                                    return $user?->name ?? '-'; // Hanya nama saat dipilih
                                })
                                ->prefix(function ($state) {
                                    if (!$state) {
                                        return '-';
                                    }
                                    $user = User::with('departemen')->find($state);
                                    return $user?->departemen?->name ?? 'External'; // Prefix = nama departemen
                                })
                                ->placeholder('Pilih PIC')
                                ->reactive()
                                ->live()
                                ->preload()
                                ->required()
                                ->columnSpanFull(),
                            Forms\Components\DatePicker::make('target')
                                ->displayFormat('d/m/Y')
                                ->native(false)
                                ->required(),
                            Forms\Components\Textarea::make('tanggapan'),
                        ])
                        ->columns(2)
                        ->columnSpanFull(),
                ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('agenda_rapat_id')
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

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

    public static function AmbilPesertaRapat($agendaRapat)
    {
        return $agendaRapat->PesertaRapat()
            ->with('user')
            //->with('user.departemen')
            ->get()
            ->mapWithKeys(function ($peserta) {
                $user = $peserta->user;
                //$departemenName = $user?->departemen?->name ?? 'External';
                return [$user->id => "{$user->name}"];
            })
            ->toArray();
    }
    public static function SearchPesertaRapat($search, $agendaRapat)
    {
        return $agendaRapat->pesertaRapat()
            ->whereHas('user', function ($query) use ($search) {
                $query->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('pegawai_id', 'like', "%{$search}%")
                    ->Where('is_guest', "Internal%")
                    ->orWhereHas('departemen', function ($q) use ($search) {
                        $q->where('name', 'like', "%{$search}%");
                    });
            })
            ->with('user.departemen')
            ->limit(10)
            ->get()
            ->mapWithKeys(function ($peserta) {
                $user = $peserta->user;
                $departemen = $user?->departemen?->name ?? '-';
                return [$user->id => "{$user->name}"];
            })
            ->toArray();
    }
}
